hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c82c23f20625dffba354f9c06231149dcfc6c66d | 1,236 | cpp | C++ | Bison C Compiler Source/instructions.cpp | kpatel122/Bison-C-Compiler | 42d6ddf6389f0125578ae1a45cecb94496a4e6f1 | [
"MIT"
] | null | null | null | Bison C Compiler Source/instructions.cpp | kpatel122/Bison-C-Compiler | 42d6ddf6389f0125578ae1a45cecb94496a4e6f1 | [
"MIT"
] | null | null | null | Bison C Compiler Source/instructions.cpp | kpatel122/Bison-C-Compiler | 42d6ddf6389f0125578ae1a45cecb94496a4e6f1 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "token.h"
#include "instructions.h"
CInstrTable::CInstrTable()
{
currInstr = 0;
}
CInstrTable::~CInstrTable()
{
}
int CInstrTable::AddInstr(char *name,int token,int numParams)
{
if(strlen(name) >= MAX_INSTR_NAME)
return -1;
InstrLookup *func = (InstrLookup*)malloc(sizeof(InstrLookup));
strcpy(func->name,name);
func->token = token;
func->numParam = numParams;
func->opList = (Operand*)malloc((sizeof(Operand)) * numParams);
instr.push_back(func);
return currInstr++;
}
void CInstrTable::SetInstrOp(int instrIndex,int opIndex,int values)
{
InstrLookup* f = instr[instrIndex];
f->opList[opIndex].type = values;
}
InstrLookup* CInstrTable::GetInstrByIndex(int index)
{
for (int i=0; i<currInstr;i++)
{
if (i == index)
return instr[i];
}
return NULL;
}
InstrLookup* CInstrTable::GetInstrByName(char *name)
{
for (int i=0; i<currInstr;i++)
{
if (strcmp(instr[i]->name, name) == 0)
return instr[i];
}
return NULL;
}
bool CInstrTable::IsValidInstr(char *name)
{
char *t;
for (int i=0; i<currInstr;i++)
{
t = instr[i]->name;
if (strcmp(t, name) == 0)
return true;
}
return false;
} | 16.263158 | 67 | 0.66343 | kpatel122 |
c82e52aa23432987d4cbbe6b0d8d793b8d94b1f2 | 388 | cpp | C++ | ModbusReadCoils.cpp | joluxer/modbus-master-cxx | 787ea5994b2a21b7f46fbf6c400b2d93c62b7271 | [
"Zlib"
] | null | null | null | ModbusReadCoils.cpp | joluxer/modbus-master-cxx | 787ea5994b2a21b7f46fbf6c400b2d93c62b7271 | [
"Zlib"
] | null | null | null | ModbusReadCoils.cpp | joluxer/modbus-master-cxx | 787ea5994b2a21b7f46fbf6c400b2d93c62b7271 | [
"Zlib"
] | null | null | null | /*
* ModbusReadCoils.cpp
*
* Created on: 09.02.2016
* Author: lode
*/
#include "ModbusReadCoils.h"
namespace Modbus
{
ReadCoils2Array::ReadCoils2Array(unsigned* array, uint16_t numOfBits, TxnReturnPath* rp)
: ReadBits2Array(FunctionCode, array, numOfBits, rp)
{}
//ReadCoils2Array::~ReadCoils2Array()
//{
// // Auto-generated destructor stub
//}
} /* namespace Modbus */
| 16.869565 | 88 | 0.701031 | joluxer |
c82fd5620635ae8ed4c1da27a2daff3cb8b49a08 | 779 | cpp | C++ | libneuralnet/nalu.cpp | Rufaim/Filtering-Clouds | 5703884a55f449ed737a3350d5276e29a69372f2 | [
"MIT"
] | null | null | null | libneuralnet/nalu.cpp | Rufaim/Filtering-Clouds | 5703884a55f449ed737a3350d5276e29a69372f2 | [
"MIT"
] | null | null | null | libneuralnet/nalu.cpp | Rufaim/Filtering-Clouds | 5703884a55f449ed737a3350d5276e29a69372f2 | [
"MIT"
] | null | null | null | #include "nalu.h"
//#include <cmath>
#include "math.h"
Nalu::Nalu(int input_dim, int out_dim, float *weight, float *gate) :
weights_(weight),
gate_(gate),
Layer ( input_dim, out_dim)
{}
void Nalu::process(float* input,float* output) {
for(int i = 0; i < out_dim_; i++) {
float lin = 0;
float log_ = 0;
float gate = 0;
for(int j = 0; j < input_dim_; j++) {
gate += gate_[i * input_dim_ + j] * input[j];
lin += weights_[i * input_dim_ + j] * input[j];
log_ += weights_[i * input_dim_ + j] * log(fabs(input[j])+0.00001);
}
gate = 0.5*tanh(gate)+1;
output[i] = gate * lin + (1-gate) * exp(log_);
}
}
void Nalu::free() {
delete [] weights_;
delete [] gate_;
}
| 25.129032 | 79 | 0.526316 | Rufaim |
c830df2e62804911cb559d62bbc6ec3fd8f12ea9 | 1,523 | hpp | C++ | core/runtime/core.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/runtime/core.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | core/runtime/core.hpp | iceseer/kagome | a405921659cc19e9fdb851e5f13f1e607fdf8af4 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_RUNTIME_CORE_HPP
#define KAGOME_RUNTIME_CORE_HPP
#include <outcome/outcome.hpp>
#include <vector>
#include "primitives/authority.hpp"
#include "primitives/block.hpp"
#include "primitives/block_id.hpp"
#include "primitives/common.hpp"
#include "primitives/transaction_validity.hpp"
#include "primitives/version.hpp"
namespace kagome::runtime {
/**
* Core represents mandatory part of runtime api
*/
class Core {
public:
virtual ~Core() = default;
/**
* @brief Returns the version of the runtime
* @return runtime version
*/
virtual outcome::result<primitives::Version> version(
const boost::optional<primitives::BlockHash> &block_hash) = 0;
/**
* @brief Executes the given block
* @param block block to execute
*/
virtual outcome::result<void> execute_block(
const primitives::Block &block) = 0;
/**
* @brief Initialize a block with the given header.
* @param header header used for block initialization
*/
virtual outcome::result<void> initialise_block(
const primitives::BlockHeader &header) = 0;
/**
* Get current authorities
* @return collection of authorities
*/
virtual outcome::result<std::vector<primitives::AuthorityId>> authorities(
const primitives::BlockId &block_id) = 0;
};
} // namespace kagome::runtime
#endif // KAGOME_RUNTIME_CORE_HPP
| 25.813559 | 78 | 0.682206 | iceseer |
c83288fdd7892d0a685ab3eb3de7a91456d2e06e | 22,923 | cc | C++ | descriptor/reader/vehicle_reader.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 38 | 2017-07-26T14:48:12.000Z | 2022-03-24T23:48:55.000Z | descriptor/reader/vehicle_reader.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 74 | 2017-03-15T21:07:34.000Z | 2022-03-18T07:53:11.000Z | descriptor/reader/vehicle_reader.cc | chris-nada/simutrans-extended | 71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f | [
"Artistic-1.0"
] | 43 | 2017-03-10T15:27:28.000Z | 2022-03-05T10:55:38.000Z | /*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
#include <stdio.h>
#include "../../simdebug.h"
#include "../../simconst.h"
#include "../../bauer/vehikelbauer.h"
#include "../sound_desc.h"
#include "../vehicle_desc.h"
#include "../intro_dates.h"
#include "vehicle_reader.h"
#include "../obj_node_info.h"
#include "../../network/pakset_info.h"
void vehicle_reader_t::register_obj(obj_desc_t *&data)
{
vehicle_desc_t *desc = static_cast<vehicle_desc_t *>(data);
vehicle_builder_t::register_desc(desc);
obj_for_xref(get_type(), desc->get_name(), data);
checksum_t *chk = new checksum_t();
desc->calc_checksum(chk);
pakset_info_t::append(desc->get_name(), get_type(), chk);
}
bool vehicle_reader_t::successfully_loaded() const
{
return vehicle_builder_t::successfully_loaded();
}
obj_desc_t *vehicle_reader_t::read_node(FILE *fp, obj_node_info_t &node)
{
ALLOCA(char, desc_buf, node.size);
vehicle_desc_t *desc = new vehicle_desc_t();
// Read data
fread(desc_buf, node.size, 1, fp);
char * p = desc_buf;
// old versions of PAK files have no version stamp.
// But we know, the higher most bit was always cleared.
const uint16 v = decode_uint16(p);
int version = v & 0x8000 ? v & 0x7FFF : 0;
// Whether the read file is from Simutrans-Extended
//@author: jamespetts
const bool extended = version > 0 ? v & EX_VER : false;
uint16 extended_version = 0;
if(extended)
{
// Extended version to start at 0 and increment.
version = version & EX_VER ? version & 0x3FFF : 0;
while(version > 0x100)
{
version -= 0x100;
extended_version ++;
}
extended_version -= 1;
}
way_constraints_of_vehicle_t way_constraints;
if(version == 1) {
// Versioned node, version 1
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
}
else if(version == 2) {
// Versioned node, version 2
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
}
else if (version==3 || version==4 || version==5) {
// Versioned node, version 3 with retire date
// version 4 identical, just other values for the waytype
// version 5 just uses the new scheme for data calculation
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint8(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
}
else if (version==6) {
// version 5 just 32 bit for power and 16 Bit for gear
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
}
else if (version==7) {
// different length of cars ...
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
}
else if (version==8) {
// multiple freight images...
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version <= 6)
{
desc->classes = 1;
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
desc->can_lead_from_rear = decode_uint8(p);
desc->comfort = new uint8[1];
desc->comfort[0] = decode_uint8(p);
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
if(extended_version == 1)
{
desc->base_fixed_cost = decode_uint16(p);
}
else if(extended_version >= 2)
{
desc->base_fixed_cost = decode_uint32(p);
}
else
{
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
}
if(extended_version >= 3)
{
desc->tractive_effort = decode_uint16(p);
}
else
{
desc->tractive_effort = 0;
}
if(extended_version >=4)
{
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
}
else
{
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
}
if(extended_version >= 5)
{
desc->livery_image_type = decode_uint8(p);
}
else
{
desc->livery_image_type = 0;
}
if(extended_version >= 6)
{
// With minimum and maximum loading times in seconds
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
}
else
{
desc->min_loading_time_seconds = desc->max_loading_time_seconds = 65535;
}
desc->is_tall = false;
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else if (version==9) {
// new: fixed_cost (previously Extended only), loading_time, axle_load
desc->base_cost = decode_uint32(p);
desc->capacity = new uint16[1];
desc->capacity[0] = decode_uint16(p);
if(extended_version == 0)
{
// The new Standard datum for loading times is read here.
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
}
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->axle_load = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
if(extended_version == 0)
{
// Extended has this as a 32-bit integer, and reads it later.
desc->base_fixed_cost = decode_uint16(p);
}
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
desc->sound = decode_sint8(p);
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version <= 7)
{
desc->classes = 1;
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
desc->can_lead_from_rear = decode_uint8(p);
desc->comfort = new uint8[1];
desc->comfort[0] = decode_uint8(p);
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
if(extended_version == 1)
{
desc->base_fixed_cost = decode_uint16(p);
}
else if(extended_version >= 2)
{
desc->base_fixed_cost = decode_uint32(p);
}
else
{
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
}
if(extended_version >= 3)
{
desc->tractive_effort = decode_uint16(p);
}
else
{
desc->tractive_effort = 0;
}
if(extended_version >= 4)
{
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
}
else
{
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
}
if(extended_version >= 5)
{
desc->livery_image_type = decode_uint8(p);
}
else
{
desc->livery_image_type = 0;
}
if(extended_version >= 6)
{
// With minimum and maximum loading times in seconds
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
}
else
{
desc->min_loading_time_seconds = desc->max_loading_time_seconds = 65535;
}
if(extended_version >= 7)
{
uint32 rolling_resistance_tenths_thousands = decode_uint16(p);
desc->rolling_resistance = rolling_resistance_tenths_thousands * float32e8_t::ten_thousandth;
desc->brake_force = decode_uint16(p);
desc->minimum_runway_length = decode_uint16(p);
}
else
{
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
}
desc->is_tall = false;
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else if (version == 10 || version == 11) {
// new: weight in kgs
desc->base_cost = decode_uint32(p);
if (extended && extended_version >= 4)
{
// Multiple classes, therefore multiple capacities.
desc->classes = decode_uint8(p);
}
else
{
desc->classes = 1;
}
// Initialise the arrays
desc->capacity = new uint16[desc->classes];
desc->comfort = new uint8[desc->classes];
for (uint32 i = 0; i < desc->classes; i++)
{
desc->capacity[i] = decode_uint16(p);
}
if (!extended)
{
// The new Standard datum for loading times is read here.
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
}
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint32(p);
desc->axle_load = decode_uint16(p);
desc->power = decode_uint32(p);
desc->running_cost = decode_uint16(p);
if (!extended)
{
// Extended has this as a 32-bit integer, and reads it later.
desc->base_fixed_cost = decode_uint16(p);
}
desc->intro_date = decode_uint16(p);
desc->retire_date = decode_uint16(p);
desc->gear = decode_uint16(p);
desc->wtyp = decode_uint8(p);
if (extended_version >= 3)
{
desc->sound = decode_sint16(p);
}
else
{
desc->sound = decode_sint8(p);
}
desc->engine_type = (vehicle_desc_t::engine_t)decode_uint8(p);
desc->len = decode_uint8(p);
desc->leader_count = decode_uint8(p);
desc->trailer_count = decode_uint8(p);
desc->freight_image_type = decode_uint8(p);
if(extended)
{
if(extended_version < 7)
{
// NOTE: Extended version reset to 1 with incrementing of
// Standard version to 10.
desc->is_tilting = decode_uint8(p);
way_constraints.set_permissive(decode_uint8(p));
way_constraints.set_prohibitive(decode_uint8(p));
desc->catering_level = decode_uint8(p);
desc->bidirectional = decode_uint8(p);
if (extended && extended_version >= 5)
{
desc->basic_constraint_prev = decode_uint8(p);
}
else {
desc->can_lead_from_rear = decode_uint8(p);
desc->basic_constraint_prev = vehicle_desc_t::unknown_constraint;
}
for (uint32 i = 0; i < desc->classes; i++)
{
desc->comfort[i] = decode_uint8(p);
}
desc->overcrowded_capacity = decode_uint16(p);
desc->min_loading_time = desc->max_loading_time = decode_uint16(p);
desc->upgrades = decode_uint8(p);
desc->base_upgrade_price = decode_uint32(p);
desc->available_only_as_upgrade = decode_uint8(p);
if (!extended && version == 10)
{
desc->base_fixed_cost = decode_uint16(p);
}
else
{
desc->base_fixed_cost = decode_uint32(p);
}
desc->tractive_effort = decode_uint16(p);
uint32 air_resistance_hundreds = decode_uint16(p);
desc->air_resistance = air_resistance_hundreds * float32e8_t::centi;
if (extended && extended_version >= 5)
{
desc->basic_constraint_next = decode_uint8(p);
}
else
{
desc->can_be_at_rear = (bool)decode_uint8(p);
desc->basic_constraint_next = vehicle_desc_t::unknown_constraint;
}
desc->increase_maintenance_after_years = decode_uint16(p);
desc->increase_maintenance_by_percent = decode_uint16(p);
desc->years_before_maintenance_max_reached = decode_uint8(p);
desc->livery_image_type = decode_uint8(p);
desc->min_loading_time_seconds = decode_uint16(p);
desc->max_loading_time_seconds = decode_uint16(p);
uint32 rolling_resistance_tenths_thousands = decode_uint16(p);
desc->rolling_resistance = rolling_resistance_tenths_thousands * float32e8_t::ten_thousandth;
desc->brake_force = decode_uint16(p);
desc->minimum_runway_length = decode_uint16(p);
if(extended_version == 0)
{
desc->range = 0;
desc->way_wear_factor = UINT32_MAX_VALUE;
}
else
{
desc->range = decode_uint16(p);
desc->way_wear_factor = decode_uint32(p);
}
if (extended_version > 1)
{
desc->is_tall = decode_uint8(p);
}
else
{
desc->is_tall = false;
}
if (extended && extended_version >= 5)
{
desc->mixed_load_prohibition = decode_uint8(p);
}
else
{
desc->mixed_load_prohibition = false;
}
if (extended && extended_version >= 6)
{
desc->override_way_speed = decode_uint8(p);
}
else
{
desc->override_way_speed = false;
}
}
else
{
dbg->fatal( "vehicle_reader_t::read_node()","Incompatible pak file version for Simutrans-Ex, number %i", extended_version );
}
}
}
else {
if( version!=0 ) {
dbg->fatal( "vehicle_reader_t::read_node()","Do not know how to handle version=%i", version );
}
// old node, version 0
desc->wtyp = (sint8)v;
desc->capacity[0] = decode_uint16(p);
desc->base_cost = decode_uint32(p);
desc->topspeed = decode_uint16(p);
desc->weight = decode_uint16(p);
desc->power = decode_uint16(p);
desc->running_cost = decode_uint16(p);
desc->sound = decode_sint16(p);
desc->leader_count = (sint8)decode_uint16(p);
desc->trailer_count = (sint8)decode_uint16(p);
desc->intro_date = DEFAULT_INTRO_DATE*16;
desc->retire_date = (DEFAULT_RETIRE_DATE*16);
desc->gear = 64;
}
// correct the engine type for old vehicles
if(version<2) {
// steam eangines usually have a sound of 3
// electric engines will be overridden further down ...
desc->engine_type = (desc->sound==3) ? vehicle_desc_t::steam : vehicle_desc_t::diesel;
}
//change the vehicle type
if(version<4) {
if(desc->wtyp==4) {
desc->engine_type = vehicle_desc_t::electric;
desc->wtyp = 1;
}
// convert to new standard
static const waytype_t convert_from_old[8]={road_wt, track_wt, water_wt, air_wt, invalid_wt, monorail_wt, invalid_wt, tram_wt };
desc->wtyp = convert_from_old[desc->wtyp];
}
// before version 5 dates were based on base 12 ...
if(version<5) {
uint16 date=desc->intro_date;
desc->intro_date = (date/16)*12 + (date%16);
date=desc->retire_date;
desc->retire_date = (date/16)*12 + (date%16);
}
// before the length was always 1/8 (=half a tile)
if(version<7) {
desc->len = CARUNITS_PER_TILE/2;
}
// adjust length for different offset step sizes (which may arise in future)
desc->len *= OBJECT_OFFSET_STEPS/CARUNITS_PER_TILE;
// before version 8 vehicles could only have one freight image in each direction
if(version<8) {
desc->freight_image_type=0;
}
if(!extended)
{
// Default values for items not in the standard vehicle format.
desc->classes = 1;
desc->is_tilting = false;
desc->catering_level = 0;
desc->bidirectional = false;
desc->can_lead_from_rear = false;
desc->comfort = new uint8[1];
desc->comfort[0] = 100;
desc->overcrowded_capacity = 0;
desc->tractive_effort = 0;
switch(desc->get_waytype())
{
default:
case tram_wt:
case road_wt:
desc->min_loading_time = desc->max_loading_time = 2000;
break;
case monorail_wt:
case maglev_wt:
case narrowgauge_wt:
case track_wt:
desc->min_loading_time = desc->max_loading_time = 4000;
break;
case water_wt:
desc->min_loading_time = desc->max_loading_time = 20000;
break;
case air_wt:
desc->min_loading_time = desc->max_loading_time = 30000;
break;
}
desc->air_resistance = vehicle_desc_t::get_air_default(desc->wtyp) * float32e8_t::centi;
desc->rolling_resistance = vehicle_desc_t::get_rolling_default(desc->wtyp) * float32e8_t::ten_thousandth;
desc->upgrades = 0;
desc->base_upgrade_price = desc->base_cost;
desc->available_only_as_upgrade = false;
desc->base_fixed_cost = DEFAULT_FIXED_VEHICLE_MAINTENANCE;
desc->can_be_at_rear = true;
desc->increase_maintenance_after_years = 0;
desc->increase_maintenance_by_percent = 0;
desc->years_before_maintenance_max_reached = 0;
desc->livery_image_type = 0;
desc->min_loading_time_seconds = 20;
desc->max_loading_time_seconds = 60;
desc->brake_force = BRAKE_FORCE_UNKNOWN;
desc->minimum_runway_length = 10;
desc->range = 0;
desc->way_wear_factor = 1;
desc->is_tall = false;
desc->basic_constraint_prev = vehicle_desc_t::unknown_constraint;
desc->basic_constraint_next = vehicle_desc_t::unknown_constraint;
desc->mixed_load_prohibition = false;
desc->override_way_speed = false;
}
desc->set_way_constraints(way_constraints);
if(version<9) {
desc->base_fixed_cost = 0;
desc->axle_load = desc->weight;
}
// old weights were tons
if(version<10) {
desc->weight *= 1000;
desc->range = 0;
desc->way_wear_factor = UINT32_MAX_VALUE;
}
// Convert flag
if (version<11 || (version == 11 && extended && extended_version < 5)) {
if (desc->can_lead_from_rear == true && desc->bidirectional == false) {
desc->bidirectional = true;
}
}
if(desc->sound==LOAD_SOUND) {
uint8 len=decode_sint8(p);
char wavname[256];
wavname[len] = 0;
for(uint8 i=0; i<len; i++) {
wavname[i] = decode_sint8(p);
}
desc->sound = (sint16)sound_desc_t::get_sound_id(wavname);
DBG_MESSAGE("vehicle_reader_t::register_obj()","sound %s to %i",wavname,desc->sound);
}
else if(desc->sound>=0 && desc->sound<=MAX_OLD_SOUNDS) {
sint16 old_id = desc->sound;
desc->sound = (sint16)sound_desc_t::get_compatible_sound_id(old_id);
DBG_MESSAGE("vehicle_reader_t::register_obj()","old sound %i to %i",old_id,desc->sound);
}
desc->loaded();
DBG_DEBUG("vehicle_reader_t::read_node()",
"version=%d "
"way=%d classes=%d capacity=%d comfort=%d cost=%d topspeed=%d weight=%g axle_load=%d power=%d "
"betrieb=%d sound=%d vor=%d nach=%d "
"date=%d/%d gear=%d engine_type=%d len=%d is_tilting=%d mixed_load_prohibition=%d catering_level=%d "
"way_constraints_permissive=%d way_constraints_prohibitive%d bidirectional%d can_lead_from_rear%d coupling_constraint%d",
version,
desc->wtyp,
desc->classes,
desc->capacity[0],
desc->comfort[0],
desc->base_cost,
desc->topspeed,
desc->weight/1000.0,
desc->axle_load,
desc->power,
desc->running_cost,
desc->sound,
desc->leader_count,
desc->trailer_count,
(desc->intro_date%12)+1,
desc->intro_date/12,
desc->gear,
desc->engine_type,
desc->len,
desc->is_tilting,
desc->mixed_load_prohibition,
desc->override_way_speed,
desc->catering_level,
desc->get_way_constraints().get_permissive(),
desc->get_way_constraints().get_prohibitive(),
desc->bidirectional,
desc->basic_constraint_prev,
desc->basic_constraint_next);
return desc;
}
| 29.886571 | 130 | 0.687781 | chris-nada |
c836c9307d38132c8e2b76b00aca51eb6fd1a0bb | 22 | cpp | C++ | tests/Issue127.cpp | galorojo/cppinsights | 52ecab4ddd8e36fb99893551cf0fb8b5d58589f2 | [
"MIT"
] | 1,853 | 2018-05-13T21:49:17.000Z | 2022-03-30T10:34:45.000Z | tests/Issue127.cpp | tiandaoafei/cppinsights | af78ac299121354101a5e506dafccaac95d27a77 | [
"MIT"
] | 398 | 2018-05-15T14:48:51.000Z | 2022-03-24T12:14:33.000Z | tests/Issue127.cpp | SammyEnigma/cppinsights | c984b8e68139bbcc244c094fd2463eeced8fd997 | [
"MIT"
] | 104 | 2018-05-15T04:00:59.000Z | 2022-03-17T02:04:15.000Z | auto f = [](auto) {};
| 11 | 21 | 0.409091 | galorojo |
c836e6e739f6b0b920ecaab7bcd3dd297cb2bfbe | 1,014 | cpp | C++ | 21/dfuvcomp.cpp | johnoel/tagest | be0a6b164683c448c90f0c3952343f5963eece3d | [
"BSD-2-Clause"
] | 3 | 2015-08-26T17:14:02.000Z | 2015-11-17T04:18:56.000Z | 21/dfuvcomp.cpp | johnoel/tagest | be0a6b164683c448c90f0c3952343f5963eece3d | [
"BSD-2-Clause"
] | 10 | 2015-08-20T00:51:05.000Z | 2016-11-16T19:14:48.000Z | 21/dfuvcomp.cpp | johnoel/tagest | be0a6b164683c448c90f0c3952343f5963eece3d | [
"BSD-2-Clause"
] | 3 | 2016-11-16T00:52:23.000Z | 2021-09-10T02:17:40.000Z | #include "precomp.h"
#undef TRACE
#define TRACE(object) clogf << "line " << __LINE__ << ", file "\
<< __FILE__ << ", " << #object " = " << object << endl;
/* John: I think we should remove boundary references. P. */
extern ofstream clogf;
void dfuvcomp(par_t& param, par_t_reg& dfparam, dmatrix& dfu, dmatrix& dfv,
int season)
{
//clogf << " dfuvcomp for season = " << season << endl;
gridpartype_vector& dfug = (gridpartype_vector&)dfparam.get_usergrid(season);
double rdx = 30.0/param.get_deltax_eq();
double rdy = 30.0/param.get_deltay();
int _m = param.get_m();
ivector& jlb = param.get_jlb();
ivector& jub = param.get_jub();
for (int i=_m; i>=1; i--)
{
int j1 = jlb(i);
int jn = jub(i);
for (int j=jn; j>=j1; j--)
{
int k = param.get_gridmap(i, j);
//v[i][j] = ug[k].v*rdy;
dfug[k].v += rdy*dfv[i][j];
dfv[i][j] = 0.0;
//u[i][j] = ug[k].u*rdx;
dfug[k].u += rdx*dfu[i][j];
dfu[i][j] = 0.0;
}
}
}
| 24.731707 | 79 | 0.548323 | johnoel |
c83704ba0ce11494af1fa548d82c86c5c4ebde9b | 473 | cpp | C++ | src/layer.cpp | shugaa/florb | 85d2be7d851f83db8a289fd2018832aec295d526 | [
"MIT"
] | 16 | 2015-03-26T22:44:23.000Z | 2021-05-09T12:31:24.000Z | src/layer.cpp | pekdon/florb | 85d2be7d851f83db8a289fd2018832aec295d526 | [
"MIT"
] | 3 | 2018-09-01T13:03:29.000Z | 2020-11-29T09:37:31.000Z | src/layer.cpp | pekdon/florb | 85d2be7d851f83db8a289fd2018832aec295d526 | [
"MIT"
] | 6 | 2017-02-12T05:46:32.000Z | 2020-08-31T06:48:11.000Z | #include <string>
#include <FL/Fl.H>
#include "layer.hpp"
florb::layer::layer() :
m_name("N/A"),
m_enabled(true)
{
add_instance(this);
};
florb::layer::~layer()
{
del_instance(this);
};
const std::string& florb::layer::name() const
{
return m_name;
};
bool florb::layer::enabled() const
{
return m_enabled;
};
void florb::layer::name(const std::string &name)
{
m_name = name;
};
void florb::layer::enable(bool en)
{
m_enabled = en;
};
| 13.138889 | 48 | 0.617336 | shugaa |
c838b9c3c72a457c98bdcff04fa3c0431c9170ff | 10,361 | cpp | C++ | be/test/storage/persistent_index_test.cpp | zhangboya1/starrocks | ec7b4f622cf4341dbc8776ed5c8cc55552c44f4e | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | be/test/storage/persistent_index_test.cpp | zhangboya1/starrocks | ec7b4f622cf4341dbc8776ed5c8cc55552c44f4e | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | be/test/storage/persistent_index_test.cpp | zhangboya1/starrocks | ec7b4f622cf4341dbc8776ed5c8cc55552c44f4e | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "storage/persistent_index.h"
#include <gtest/gtest.h>
#include "env/env_memory.h"
#include "storage/fs/file_block_manager.h"
#include "storage/fs/fs_util.h"
#include "storage/storage_engine.h"
#include "testutil/parallel_test.h"
#include "util/coding.h"
#include "util/faststring.h"
#include "util/file_utils.h"
namespace starrocks {
PARALLEL_TEST(PersistentIndexTest, test_mutable_index) {
using Key = uint64_t;
vector<Key> keys;
vector<IndexValue> values;
int N = 1000;
for (int i = 0; i < N; i++) {
keys.emplace_back(i);
values.emplace_back(i * 2);
}
auto rs = MutableIndex::create(sizeof(Key));
ASSERT_TRUE(rs.ok());
std::unique_ptr<MutableIndex> idx = std::move(rs).value();
// test insert
ASSERT_TRUE(idx->insert(keys.size(), keys.data(), values.data()).ok());
// insert duplicate should return error
ASSERT_FALSE(idx->insert(keys.size(), keys.data(), values.data()).ok());
// test get
vector<IndexValue> get_values(keys.size());
KeysInfo get_not_found;
size_t get_num_found = 0;
ASSERT_TRUE(idx->get(keys.size(), keys.data(), get_values.data(), &get_not_found, &get_num_found).ok());
ASSERT_EQ(keys.size(), get_num_found);
ASSERT_EQ(get_not_found.key_idxes.size(), 0);
for (int i = 0; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
vector<Key> get2_keys;
for (int i = 0; i < N; i++) {
get2_keys.emplace_back(i * 2);
}
vector<IndexValue> get2_values(get2_keys.size());
KeysInfo get2_not_found;
size_t get2_num_found = 0;
// should only find 0,2,..N-2, not found: N,N+2, .. N*2-2
ASSERT_TRUE(
idx->get(get2_keys.size(), get2_keys.data(), get2_values.data(), &get2_not_found, &get2_num_found).ok());
ASSERT_EQ(N / 2, get2_num_found);
// test erase
vector<Key> erase_keys;
for (int i = 0; i < N + 3; i += 3) {
erase_keys.emplace_back(i);
}
vector<IndexValue> erase_old_values(erase_keys.size());
KeysInfo erase_not_found;
size_t erase_num_found = 0;
ASSERT_TRUE(idx->erase(erase_keys.size(), erase_keys.data(), erase_old_values.data(), &erase_not_found,
&erase_num_found)
.ok());
ASSERT_EQ(erase_num_found, (N + 2) / 3);
// N+2 not found
ASSERT_EQ(erase_not_found.key_idxes.size(), 1);
// test upsert
vector<Key> upsert_keys(N, 0);
vector<IndexValue> upsert_values(upsert_keys.size());
size_t expect_exists = 0;
size_t expect_not_found = 0;
for (int i = 0; i < N; i++) {
upsert_keys[i] = i * 2;
if (i % 3 != 0 && i * 2 < N) {
expect_exists++;
}
if (i * 2 >= N && i * 2 != N + 2) {
expect_not_found++;
}
upsert_values[i] = i * 3;
}
vector<IndexValue> upsert_old_values(upsert_keys.size());
KeysInfo upsert_not_found;
size_t upsert_num_found = 0;
ASSERT_TRUE(idx->upsert(upsert_keys.size(), upsert_keys.data(), upsert_values.data(), upsert_old_values.data(),
&upsert_not_found, &upsert_num_found)
.ok());
ASSERT_EQ(upsert_num_found, expect_exists);
ASSERT_EQ(upsert_not_found.key_idxes.size(), expect_not_found);
}
PARALLEL_TEST(PersistentIndexTest, test_mutable_index_wal) {
Env* env = Env::Default();
const std::string kPersistentIndexDir = "./ut_dir/persistent_index_test";
const std::string kIndexFile = "./ut_dir/persistent_index_test/index.l0.0.0";
ASSERT_TRUE(env->create_dir(kPersistentIndexDir).ok());
fs::BlockManager* block_mgr = fs::fs_util::block_manager();
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions wblock_opts({kIndexFile});
ASSERT_TRUE((block_mgr->create_block(wblock_opts, &wblock)).ok());
wblock->close();
using Key = uint64_t;
EditVersion version(0, 0);
PersistentIndexMetaPB index_meta;
index_meta.set_key_size(sizeof(Key));
index_meta.set_size(0);
version.to_pb(index_meta.mutable_version());
MutableIndexMetaPB* l0_meta = index_meta.mutable_l0_meta();
IndexSnapshotMetaPB* snapshot_meta = l0_meta->mutable_snapshot();
version.to_pb(snapshot_meta->mutable_version());
PersistentIndex index(kPersistentIndexDir);
ASSERT_TRUE(index.create(sizeof(Key), version).ok());
ASSERT_TRUE(index.load(index_meta).ok());
// insert
vector<Key> keys;
vector<IndexValue> values;
int N = 1000000;
for (int i = 0; i < N; i++) {
keys.emplace_back(i);
values.emplace_back(i * 2);
}
ASSERT_TRUE(index.prepare(EditVersion(1, 0)).ok());
ASSERT_TRUE(index.insert(100, keys.data(), values.data(), false).ok());
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
{
std::vector<IndexValue> old_values(keys.size());
ASSERT_TRUE(index.prepare(EditVersion(2, 0)).ok());
ASSERT_TRUE(index.upsert(keys.size(), keys.data(), values.data(), old_values.data()).ok());
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
}
// erase
vector<Key> erase_keys;
for (int i = 0; i < N / 2; i++) {
erase_keys.emplace_back(i);
}
vector<IndexValue> erase_old_values(erase_keys.size());
ASSERT_TRUE(index.prepare(EditVersion(3, 0)).ok());
ASSERT_TRUE(index.erase(erase_keys.size(), erase_keys.data(), erase_old_values.data()).ok());
// update PersistentMetaPB in memory
ASSERT_TRUE(index.commit(&index_meta).ok());
ASSERT_TRUE(index.on_commited().ok());
// append invalid wal
std::vector<Key> invalid_keys;
std::vector<IndexValue> invalid_values;
faststring fixed_buf;
for (int i = 0; i < N / 2; i++) {
invalid_keys.emplace_back(i);
invalid_values.emplace_back(i * 2);
}
{
const uint8_t* fkeys = reinterpret_cast<const uint8_t*>(invalid_keys.data());
for (int i = 0; i < N / 2; i++) {
fixed_buf.append(fkeys + i * sizeof(Key), sizeof(Key));
put_fixed64_le(&fixed_buf, invalid_values[i]);
}
fs::BlockManager* block_mgr = fs::fs_util::block_manager();
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions wblock_opts({"./ut_dir/persistent_index_test/index.l0.1.0"});
wblock_opts.mode = Env::MUST_EXIST;
ASSERT_TRUE((block_mgr->create_block(wblock_opts, &wblock)).ok());
ASSERT_TRUE(wblock->append(fixed_buf).ok());
wblock->close();
}
// rebuild mutableindex according PersistentIndexMetaPB
PersistentIndex new_index(kPersistentIndexDir);
ASSERT_TRUE(new_index.create(sizeof(Key), EditVersion(3, 0)).ok());
//ASSERT_TRUE(new_index.load(index_meta).ok());
Status st = new_index.load(index_meta);
if (!st.ok()) {
LOG(WARNING) << "load failed, status is " << st.to_string();
ASSERT_TRUE(false);
}
std::vector<IndexValue> get_values(keys.size());
ASSERT_TRUE(new_index.get(keys.size(), keys.data(), get_values.data()).ok());
ASSERT_EQ(keys.size(), get_values.size());
for (int i = 0; i < N / 2; i++) {
ASSERT_EQ(NullIndexValue, get_values[i]);
}
for (int i = N / 2; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
// upsert key/value to new_index
{
vector<IndexValue> old_values(invalid_keys.size());
ASSERT_TRUE(new_index.prepare(EditVersion(4, 0)).ok());
ASSERT_TRUE(new_index.upsert(invalid_keys.size(), invalid_keys.data(), invalid_values.data(), old_values.data())
.ok());
ASSERT_TRUE(new_index.commit(&index_meta).ok());
ASSERT_TRUE(new_index.on_commited().ok());
}
// rebuild mutableindex according to PersistentIndexMetaPB
{
PersistentIndex index(kPersistentIndexDir);
ASSERT_TRUE(index.create(sizeof(Key), EditVersion(4, 0)).ok());
ASSERT_TRUE(index.load(index_meta).ok());
std::vector<IndexValue> get_values(keys.size());
ASSERT_TRUE(index.get(keys.size(), keys.data(), get_values.data()).ok());
ASSERT_EQ(keys.size(), get_values.size());
for (int i = 0; i < values.size(); i++) {
ASSERT_EQ(values[i], get_values[i]);
}
}
ASSERT_TRUE(FileUtils::remove_all(kPersistentIndexDir).ok());
}
PARALLEL_TEST(PersistentIndexTest, test_mutable_flush_to_immutable) {
using Key = uint64_t;
int N = 200000;
vector<Key> keys(N);
vector<IndexValue> values(N);
for (int i = 0; i < N; i++) {
keys[i] = i;
values[i] = i * 2;
}
auto rs = MutableIndex::create(sizeof(Key));
ASSERT_TRUE(rs.ok());
std::unique_ptr<MutableIndex> idx = std::move(rs).value();
// test insert
ASSERT_TRUE(idx->insert(keys.size(), keys.data(), values.data()).ok());
ASSERT_TRUE(idx->flush_to_immutable_index(".", EditVersion(1, 1)).ok());
std::unique_ptr<fs::ReadableBlock> rb;
auto block_mgr = fs::fs_util::block_manager();
ASSERT_TRUE(block_mgr->open_block("./index.l1.1.1", &rb).ok());
auto st_load = ImmutableIndex::load(std::move(rb));
if (!st_load.ok()) {
LOG(WARNING) << st_load.status();
}
ASSERT_TRUE(st_load.ok());
auto& idx_loaded = st_load.value();
KeysInfo keys_info;
for (size_t i = 0; i < N; i++) {
keys_info.key_idxes.emplace_back(i);
uint64_t h = key_index_hash(&keys[i], sizeof(Key));
keys_info.hashes.emplace_back(h);
}
vector<IndexValue> get_values(N);
size_t num_found = 0;
auto st_get = idx_loaded->get(N, keys.data(), keys_info, get_values.data(), &num_found);
if (!st_get.ok()) {
LOG(WARNING) << st_get;
}
ASSERT_TRUE(st_get.ok());
ASSERT_EQ(N, num_found);
for (size_t i = 0; i < N; i++) {
ASSERT_EQ(values[i], get_values[i]);
}
ASSERT_TRUE(idx_loaded->check_not_exist(N, keys.data()).is_already_exist());
vector<Key> check_not_exist_keys(10);
for (int i = 0; i < 10; i++) {
check_not_exist_keys[i] = N + i;
}
ASSERT_TRUE(idx_loaded->check_not_exist(10, check_not_exist_keys.data()).ok());
}
} // namespace starrocks
| 37.136201 | 120 | 0.633144 | zhangboya1 |
c83a0d23657c910d8910539eee91fb66ae803d86 | 528 | cpp | C++ | introduction/file/file.cpp | egorkaGubarev/modeling_2021_egorkaGubarev | cca05950c0455c4a378fd6ca3b399a6d9c277968 | [
"Unlicense"
] | null | null | null | introduction/file/file.cpp | egorkaGubarev/modeling_2021_egorkaGubarev | cca05950c0455c4a378fd6ca3b399a6d9c277968 | [
"Unlicense"
] | null | null | null | introduction/file/file.cpp | egorkaGubarev/modeling_2021_egorkaGubarev | cca05950c0455c4a378fd6ca3b399a6d9c277968 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
typedef unsigned int uint;
void write_file(std::string path, uint number)
{
std::ofstream file;
file.open(path, std::ios::app);
if (file.is_open()){
file << number << ' ';
file.close();
}else{
std::cerr << "File isn't opened!";
}
}
int main()
{
std::string path = "file.txt";
for (uint number = 1; number < 31; number ++){
write_file(path, number);
}
std::cout << "File is created";
return 0;
}
| 18.206897 | 50 | 0.560606 | egorkaGubarev |
c83a88d0419cf2edc1feef83733fdff75625f036 | 13,156 | cpp | C++ | Engine/Core/Source/Molten/Renderer/OpenGL/OpenGLWin32Renderer.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 2 | 2019-11-11T21:17:14.000Z | 2019-11-11T22:07:26.000Z | Engine/Core/Source/Molten/Renderer/OpenGL/OpenGLWin32Renderer.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | null | null | null | Engine/Core/Source/Molten/Renderer/OpenGL/OpenGLWin32Renderer.cpp | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 1 | 2020-04-05T03:50:57.000Z | 2020-04-05T03:50:57.000Z | /*
* MIT License
*
* Copyright (c) 2021 Jimmie Bergmann
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files(the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "Molten/Renderer/OpenGL/OpenGLWin32Renderer.hpp"
#if defined(MOLTEN_ENABLE_OPENGL)
#if MOLTEN_PLATFORM == MOLTEN_PLATFORM_WINDOWS
#include "Molten/Renderer/OpenGL/OpengGLFunctions.hpp"
#include "Molten/Renderer/PushConstant.hpp"
#include "Molten/Window/Window.hpp"
#include "Molten/System/Exception.hpp"
#include <array>
namespace Molten
{
OpenGLWin32Renderer::OpenGLWin32Renderer() :
m_deviceContext(NULL),
m_context(NULL)
{}
OpenGLWin32Renderer::OpenGLWin32Renderer(RenderTarget& renderTarget, const Version& version, Logger* logger) :
OpenGLWin32Renderer()
{
Open(renderTarget, version, logger);
}
OpenGLWin32Renderer::~OpenGLWin32Renderer()
{
Close();
}
bool OpenGLWin32Renderer::Open(RenderTarget& renderTarget, const Version& version, Logger* /*logger*/)
{
HGLRC temporaryContext = NULL;
auto deviceContext = renderTarget.GetWin32DeviceContext();
if (deviceContext == NULL)
{
throw Exception("OpenGLWin32Renderer: Device context of parameter \"window\" is null.");
}
try
{
static PIXELFORMATDESCRIPTOR pixelFormatDescriptor =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
16, //DepthBits,
8, //StencilBits,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
// Choose and set the pixel format
GLuint pixelFormat;
if ((pixelFormat = ChoosePixelFormat(deviceContext, &pixelFormatDescriptor)) == 0)
{
throw Exception("OpenGLWin32Renderer: Failed to choose pixel format for Win32 device context.");
}
if ((SetPixelFormat(deviceContext, pixelFormat, &pixelFormatDescriptor)) == false)
{
throw Exception("OpenGLWin32Renderer: Failed to set pixel format for Win32 device context.");
}
temporaryContext = ::wglCreateContext(deviceContext);
if (temporaryContext == NULL)
{
throw Exception("OpenGLWin32Renderer: Failed to create primitive Win32 OpenGL context.");
}
::wglMakeCurrent(NULL, NULL);
::wglMakeCurrent(deviceContext, temporaryContext);
if (version == Version::None)
{
Version openedVersion;
OpenBestVersion(deviceContext, openedVersion);
m_version = openedVersion;
}
else
{
OpenVersion(deviceContext, version);
m_version = version;
}
}
catch (Exception &)
{
if (temporaryContext)
{
::wglDeleteContext(temporaryContext);
}
::wglMakeCurrent(NULL, NULL);
throw;
}
catch (...)
{
throw;
}
OpenGL::BindOpenGLExtensions();
return false;
}
void OpenGLWin32Renderer::Close()
{
if (m_context)
{
// Release the context from the current thread
if (!wglMakeCurrent(NULL, NULL))
{
throw Exception("OpenGLWin32Renderer: Failed to set current context to null.");
}
// Delete the context
if (!wglDeleteContext(m_context))
{
throw Exception("OpenGLWin32Renderer: Failed to delete context.");
}
m_context = NULL;
}
}
bool OpenGLWin32Renderer::IsOpen() const
{
return false;
}
void OpenGLWin32Renderer::Resize(const Vector2ui32& /*size*/)
{
}
Renderer::BackendApi OpenGLWin32Renderer::GetBackendApi() const
{
return Renderer::BackendApi::OpenGL;
}
Version OpenGLWin32Renderer::GetVersion() const
{
return m_version;
}
const RendererCapabilities& OpenGLWin32Renderer::GetCapabilities() const
{
static RendererCapabilities tmpCapabilities = {};
return tmpCapabilities;
}
uint32_t OpenGLWin32Renderer::GetPushConstantLocation(Pipeline& /*pipeline*/, const uint32_t /*id*/)
{
return PushConstantLocation::UnknownLocation;
}
RenderResource<DescriptorSet> OpenGLWin32Renderer::CreateDescriptorSet(const DescriptorSetDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<FramedDescriptorSet> OpenGLWin32Renderer::CreateFramedDescriptorSet(const FramedDescriptorSetDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<IndexBuffer> OpenGLWin32Renderer::CreateIndexBuffer(const IndexBufferDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<Pipeline> OpenGLWin32Renderer::CreatePipeline(const PipelineDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<RenderPass> OpenGLWin32Renderer::CreateRenderPass(const RenderPassDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler1D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler2D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Sampler3D> OpenGLWin32Renderer::CreateSampler(const SamplerDescriptor3D& /*descriptor*/)
{
return { };
}
SharedRenderResource<ShaderProgram> OpenGLWin32Renderer::CreateShaderProgram(const VisualShaderProgramDescriptor& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture1D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture2D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<Texture3D> OpenGLWin32Renderer::CreateTexture(const TextureDescriptor3D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture1D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor1D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture2D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor2D& /*descriptor*/)
{
return { };
}
SharedRenderResource<FramedTexture3D> OpenGLWin32Renderer::CreateFramedTexture(const TextureDescriptor3D& /*descriptor*/)
{
return { };
}
RenderResource<UniformBuffer> OpenGLWin32Renderer::CreateUniformBuffer(const UniformBufferDescriptor&)
{
return { };
}
RenderResource<FramedUniformBuffer> OpenGLWin32Renderer::CreateFramedUniformBuffer(const FramedUniformBufferDescriptor& /*descriptor*/)
{
return { };
}
RenderResource<VertexBuffer> OpenGLWin32Renderer::CreateVertexBuffer(const VertexBufferDescriptor&)
{
return { };
}
bool OpenGLWin32Renderer::UpdateRenderPass(RenderPass& /*renderPass*/, const RenderPassUpdateDescriptor& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture1D& /*texture1D*/, const TextureUpdateDescriptor1D& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture2D& /*texture2D*/, const TextureUpdateDescriptor2D& /*descriptor*/)
{
return false;
}
bool OpenGLWin32Renderer::UpdateTexture(Texture3D& /*texture3D*/, const TextureUpdateDescriptor3D& /*descriptor*/)
{
return false;
}
void OpenGLWin32Renderer::UpdateUniformBuffer(RenderResource<UniformBuffer>& /*uniformBuffer*/, const void* /*data*/, const size_t /*size*/, const size_t /*offset*/)
{
}
void OpenGLWin32Renderer::UpdateFramedUniformBuffer(RenderResource<FramedUniformBuffer>& /*framedUniformBuffer*/, const void* /*data*/, const size_t /*size*/, const size_t /*offset*/)
{
}
bool OpenGLWin32Renderer::DrawFrame(const RenderPasses& /*renderPasses*/)
{
return false;
}
void OpenGLWin32Renderer::Destroy(DescriptorSet& /*descriptorSet*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedDescriptorSet& /*framedDescriptorSet*/)
{
}
void OpenGLWin32Renderer::Destroy(IndexBuffer& /*indexBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(Pipeline& /*pipeline*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler1D& /*sampler1D*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler2D& /*sampler2D*/)
{
}
void OpenGLWin32Renderer::Destroy(Sampler3D& /*sampler3D*/)
{
}
void OpenGLWin32Renderer::Destroy(ShaderProgram& /*shaderProgram*/ )
{
}
void OpenGLWin32Renderer::Destroy(Texture1D& /*texture1D*/)
{
}
void OpenGLWin32Renderer::Destroy(Texture2D& /*texture2D*/)
{
}
void OpenGLWin32Renderer::Destroy(Texture3D& /*texture3D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture1D& /*framedTexture1D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture2D& /*framedTexture2D*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedTexture3D& /*framedTexture3D*/)
{
}
void OpenGLWin32Renderer::Destroy(UniformBuffer& /*uniformBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(FramedUniformBuffer& /*framedUniformBuffer*/)
{
}
void OpenGLWin32Renderer::Destroy(VertexBuffer& /*vertexBuffer*/)
{
}
void OpenGLWin32Renderer::WaitForDevice()
{
}
bool OpenGLWin32Renderer::OpenVersion(HDC deviceContext, const Version& version)
{
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
if ((wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB")) == NULL)
{
throw Exception("Cannot get address of wglCreateContextAttribsARB.");
}
const int attributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(version.Major),
WGL_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(version.Minor),
0
};
if ((m_context = wglCreateContextAttribsARB(deviceContext, 0, attributes)) == NULL)
{
throw Exception("Failed to create OpenGL context version " + version.AsString());
}
return true;
}
void OpenGLWin32Renderer::OpenBestVersion(HDC deviceContext, Version& version)
{
static const std::array versions =
{
Version(4, 6),
Version(4, 5),
Version(4, 4),
Version(4, 3),
Version(4, 2),
Version(4, 1),
Version(4, 0),
Version(3, 3),
Version(3, 2),
Version(3, 1),
Version(3, 0),
Version(2, 1),
Version(2, 0)
};
version = Version::None;
for(auto it = versions.begin(); it != versions.end(); it++)
{
try
{
const Version& ver = *it;
if (OpenVersion(deviceContext, ver))
{
version = ver;
return;
}
}
catch (Exception & e)
{
if(std::next(it) != versions.end())
{
continue;
}
throw Exception("OpenGLWin32Renderer: Failed to create best OpenGL context, last error: " + e.GetMessage());
}
}
}
}
#endif
#endif | 28.537961 | 187 | 0.617741 | jimmiebergmann |
c83aeaa0239ea2a65bf9cc59b2846a10d9afe78a | 3,919 | cpp | C++ | dev/Tools/Wwise/SDK/samples/Plugins/AkDelay/Sources/AudioEngineFX/AkDelayFX.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 2 | 2020-08-20T03:40:24.000Z | 2021-02-07T20:31:43.000Z | dev/Tools/Wwise/SDK/samples/Plugins/AkDelay/Sources/AudioEngineFX/AkDelayFX.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | null | null | null | dev/Tools/Wwise/SDK/samples/Plugins/AkDelay/Sources/AudioEngineFX/AkDelayFX.cpp | chrisinajar/spark | 3c6b30592c00bc38738cc3aaca2144edfc6cc8b2 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | /*******************************************************************************
The content of this file includes portions of the AUDIOKINETIC Wwise Technology
released in source code form as part of the SDK installer package.
Commercial License Usage
Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
may use this file in accordance with the end user license agreement provided
with the software or, alternatively, in accordance with the terms contained in a
written agreement between you and Audiokinetic Inc.
Version: v2017.2.9 Build: 6726
Copyright (c) 2006-2019 Audiokinetic Inc.
*******************************************************************************/
//////////////////////////////////////////////////////////////////////
//
// AkDelayFX.cpp
//
// Sample delay FX implementation.
//
//////////////////////////////////////////////////////////////////////
#include "AkDelayFX.h"
#include <AK/Tools/Common/AkAssert.h>
#include <AK/AkWwiseSDKVersion.h>
/// Plugin mechanism. Instantiation method that must be registered to the plug-in manager.
AK::IAkPlugin* CreateAkDelayFX( AK::IAkPluginMemAlloc * in_pAllocator )
{
return AK_PLUGIN_NEW( in_pAllocator, CAkDelayFX( ) );
}
/// Plugin mechanism. Instantiation method that must be registered to the plug-in manager.
AK::IAkPluginParam * CreateAkDelayFXParams(AK::IAkPluginMemAlloc * in_pAllocator)
{
return AK_PLUGIN_NEW(in_pAllocator, CAkDelayFXParams());
}
AK_IMPLEMENT_PLUGIN_FACTORY(AkDelayFX, AkPluginTypeEffect, 0, 106)
/// Constructor.
CAkDelayFX::CAkDelayFX()
: m_pParams( NULL )
, m_pAllocator( NULL )
{
}
/// Destructor.
CAkDelayFX::~CAkDelayFX()
{
}
/// Initializes and allocate memory for the effect.
AKRESULT CAkDelayFX::Init( AK::IAkPluginMemAlloc * in_pAllocator, /// Memory allocator interface.
AK::IAkEffectPluginContext * in_pFXCtx, /// Sound engine plug-in execution context.
AK::IAkPluginParam * in_pParams, /// Associated effect parameters node.
AkAudioFormat & in_rFormat /// Input/output audio format.
)
{
m_pParams = (CAkDelayFXParams*)in_pParams;
m_pAllocator = in_pAllocator;
m_FXState.Setup( m_pParams, in_rFormat.uSampleRate );
AKRESULT eResult = m_FXState.InitDelay( in_pAllocator, m_pParams, in_rFormat.channelConfig );
m_FXState.ComputeTailLength( m_pParams->RTPC.bFeedbackEnabled, m_pParams->RTPC.fFeedback );
m_pParams->NonRTPC.bHasChanged = false;
m_pParams->RTPC.bHasChanged = false;
AK_PERF_RECORDING_RESET();
return eResult;
}
/// Effect termination.
AKRESULT CAkDelayFX::Term( AK::IAkPluginMemAlloc * in_pAllocator )
{
m_FXState.TermDelay( in_pAllocator );
AK_PLUGIN_DELETE( in_pAllocator, this ); /// Effect must delete itself
return AK_Success;
}
/// Actions to perform on FX reset (example on bypass)
AKRESULT CAkDelayFX::Reset( )
{
m_FXState.ResetDelay();
return AK_Success;
}
/// Effect info query.
AKRESULT CAkDelayFX::GetPluginInfo( AkPluginInfo & out_rPluginInfo )
{
out_rPluginInfo.eType = AkPluginTypeEffect;
out_rPluginInfo.bIsInPlace = true;
out_rPluginInfo.uBuildVersion = AK_WWISESDK_VERSION_COMBINED;
return AK_Success;
}
/// Effect plug-in DSP processing
void CAkDelayFX::Execute( AkAudioBuffer * io_pBuffer )
{
if ( AK_EXPECT_FALSE( m_pParams->NonRTPC.bHasChanged ) )
{
AKRESULT eResult = m_FXState.InitDelay( m_pAllocator, m_pParams, io_pBuffer->GetChannelConfig() );
if ( eResult != AK_Success )
return; // passthrough
m_FXState.ResetDelay();
m_pParams->NonRTPC.bHasChanged = false;
}
if ( AK_EXPECT_FALSE( m_pParams->RTPC.bHasChanged ) )
{
m_FXState.ComputeTailLength( m_pParams->RTPC.bFeedbackEnabled, m_pParams->RTPC.fFeedback );
m_pParams->RTPC.bHasChanged = false;
}
AK_PERF_RECORDING_START( "Delay", 25, 30 );
// Execute DSP processing synchronously here
m_FXState.Process( io_pBuffer, m_pParams );
AK_PERF_RECORDING_STOP( "Delay", 25, 30 );
}
| 32.38843 | 100 | 0.70222 | chrisinajar |
c83b37f18ec5a50cf411341f48e5efc86ab7b2e8 | 298 | cpp | C++ | tcp-plugin-qnx/plugin_lifecycle.cpp | mager-m/ietf-tcp-research-project | d4480d4dbec4f35ea61782c25bbe0a7dd05006bc | [
"MIT"
] | 2 | 2021-08-10T13:55:05.000Z | 2021-10-21T10:14:24.000Z | tcp-plugin-ubuntu/plugin_lifecycle.cpp | mager-m/ietf-tcp-research-project | d4480d4dbec4f35ea61782c25bbe0a7dd05006bc | [
"MIT"
] | null | null | null | tcp-plugin-ubuntu/plugin_lifecycle.cpp | mager-m/ietf-tcp-research-project | d4480d4dbec4f35ea61782c25bbe0a7dd05006bc | [
"MIT"
] | null | null | null | #include <cligen/cligen.h>
#include <clixon/clixon.h>
#include "plugin_lifecycle.h"
int LifecycleManager::plugin_start(clicon_handle h) {
return 0;
}
int LifecycleManager::plugin_exit(clicon_handle h) {
return 0;
}
int LifecycleManager::plugin_daemon(clicon_handle h) {
return 0;
}
| 17.529412 | 54 | 0.738255 | mager-m |
c83c63f95f9a64f606c336de55d9627b161721e2 | 504 | cpp | C++ | codes/moderncpp/nodiscard/nodiscard01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | 3 | 2022-01-25T07:33:43.000Z | 2022-03-30T10:25:09.000Z | codes/moderncpp/nodiscard/nodiscard01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | null | null | null | codes/moderncpp/nodiscard/nodiscard01/main.cpp | eric2003/ModernCMake | 48fe5ed2f25481a7c93f86af38a692f4563afcaa | [
"MIT"
] | 2 | 2022-01-17T13:39:12.000Z | 2022-03-30T10:25:12.000Z | #include <iostream>
struct [[nodiscard]] error_info { /*...*/ };
error_info enable_missile_safety_mode() { /*...*/ return {}; }
void launch_missiles() { /*...*/ }
void test_missiles()
{
enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value
launch_missiles();
}
// nodiscard( string-literal ) (since C++20):
struct [[nodiscard("OneFLOW CFD")]] cfd_info { /*...*/ };
void test_cfd()
{
cfd_info();
}
int main ( int argc, char **argv )
{
{
}
return 0;
}
| 19.384615 | 85 | 0.621032 | eric2003 |
c83d447f34dfa877f0e0b330ca08fcee7449fca4 | 1,882 | cpp | C++ | unittest/meta/TestNotificationFdbEvent.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 50 | 2016-03-23T08:04:44.000Z | 2022-03-25T05:06:16.000Z | unittest/meta/TestNotificationFdbEvent.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 589 | 2016-04-01T04:09:09.000Z | 2022-03-31T00:38:10.000Z | unittest/meta/TestNotificationFdbEvent.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 234 | 2016-03-28T20:59:21.000Z | 2022-03-23T09:26:22.000Z | #include "NotificationFdbEvent.h"
#include "Meta.h"
#include "MetaTestSaiInterface.h"
#include "sairediscommon.h"
#include "sai_serialize.h"
#include <gtest/gtest.h>
#include <memory>
using namespace sairedis;
using namespace saimeta;
static std::string s =
"[{\"fdb_entry\":\"{\\\"bvid\\\":\\\"oid:0x260000000005be\\\",\\\"mac\\\":\\\"52:54:00:86:DD:7A\\\",\\\"switch_id\\\":\\\"oid:0x21000000000000\\\"}\","
"\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\","
"\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_TYPE\",\"value\":\"SAI_FDB_ENTRY_TYPE_DYNAMIC\"},{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\"oid:0x3a000000000660\"}]}]";
static std::string null =
"[{\"fdb_entry\":\"{\\\"bvid\\\":\\\"oid:0x260000000005be\\\",\\\"mac\\\":\\\"52:54:00:86:DD:7A\\\",\\\"switch_id\\\":\\\"oid:0x0\\\"}\","
"\"fdb_event\":\"SAI_FDB_EVENT_LEARNED\","
"\"list\":[{\"id\":\"SAI_FDB_ENTRY_ATTR_TYPE\",\"value\":\"SAI_FDB_ENTRY_TYPE_DYNAMIC\"},{\"id\":\"SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID\",\"value\":\"oid:0x3a000000000660\"}]}]";
static std::string fullnull = "[]";
TEST(NotificationFdbEvent, ctr)
{
NotificationFdbEvent n(s);
}
TEST(NotificationFdbEvent, getSwitchId)
{
NotificationFdbEvent n(s);
EXPECT_EQ(n.getSwitchId(), 0x21000000000000);
NotificationFdbEvent n2(null);
EXPECT_EQ(n2.getSwitchId(), 0);
}
TEST(NotificationFdbEvent, getAnyObjectId)
{
NotificationFdbEvent n(s);
EXPECT_EQ(n.getAnyObjectId(), 0x21000000000000);
NotificationFdbEvent n2(null);
EXPECT_EQ(n2.getAnyObjectId(), 0x260000000005be);
NotificationFdbEvent n3(fullnull);
EXPECT_EQ(n3.getSwitchId(), 0x0);
EXPECT_EQ(n3.getAnyObjectId(), 0x0);
}
TEST(NotificationFdbEvent, processMetadata)
{
NotificationFdbEvent n(s);
auto sai = std::make_shared<MetaTestSaiInterface>();
auto meta = std::make_shared<Meta>(sai);
n.processMetadata(meta);
}
| 27.275362 | 175 | 0.675345 | vmittal-msft |
c83da0b0eb7e41bcb75a2418ba5e99f647d7d64a | 38,689 | cc | C++ | bench/f32-gemm-e2e.cc | 8thwall/XNNPACK | 6e03011a0fd74ff0b3bba3a874e452543ccbaa86 | [
"BSD-3-Clause"
] | null | null | null | bench/f32-gemm-e2e.cc | 8thwall/XNNPACK | 6e03011a0fd74ff0b3bba3a874e452543ccbaa86 | [
"BSD-3-Clause"
] | null | null | null | bench/f32-gemm-e2e.cc | 8thwall/XNNPACK | 6e03011a0fd74ff0b3bba3a874e452543ccbaa86 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#include <algorithm>
#include <cmath>
#include <functional>
#include <random>
#include <vector>
#include <xnnpack.h>
#include <benchmark/benchmark.h>
#include "bench/end2end.h"
#include "bench/utils.h"
#include "models/models.h"
#include <xnnpack/gemm.h>
#include <xnnpack/igemm.h>
#include <xnnpack/params.h>
static void GEMMEnd2EndBenchmark(
benchmark::State& state,
models::ExecutionPlanFactory model_factory,
xnn_f32_gemm_ukernel_function gemm,
xnn_f32_igemm_ukernel_function igemm,
xnn_f32_gemm_ukernel_function gemm1,
xnn_f32_igemm_ukernel_function igemm1,
uint8_t mr, uint8_t nr, uint8_t log2_kr = 0, uint8_t log2_sr = 0,
benchmark::utils::IsaCheckFunction isa_check = nullptr)
{
if (isa_check && !isa_check(state)) {
return;
}
if (xnn_initialize(nullptr /* allocator */) != xnn_status_success) {
state.SkipWithError("failed to initialize XNNPACK");
return;
}
// Override microkernels chosen in xnn_initialize
xnn_params.f32.gemm = (struct gemm_parameters) {
.gemm = xnn_gemm_ukernel_function(gemm),
.igemm = xnn_igemm_ukernel_function(igemm),
.gemm1 = xnn_gemm_ukernel_function(gemm1),
.igemm1 = xnn_igemm_ukernel_function(igemm1),
.mr = mr,
.nr = nr,
.log2_kr = log2_kr,
.log2_sr = log2_sr,
};
auto execution_plan = model_factory(nullptr);
if (execution_plan.empty()) {
state.SkipWithError("failed to create a model");
return;
}
for (auto _ : state) {
for (const std::unique_ptr<xnn_operator, decltype(&xnn_delete_operator)>& op : execution_plan) {
xnn_status status = xnn_run_operator(op.get(), nullptr);
if (status != xnn_status_success) {
state.SkipWithError("failed to run a model");
return;
}
}
}
state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency();
}
#if XNN_ARCH_ARM64 && XNN_ENABLE_ASSEMBLY
static void f32_gemm_4x12__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x12__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_4x12__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x12__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x12__aarch64_neonfma_cortex_a53,
4 /* mr */, 12 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_4x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__aarch64_neonfma_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch64_neonfma_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_5x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_5x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
5 /* mr */, 8 /* nr */);
}
static void f32_gemm_5x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_5x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
5 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a53,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a53,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a73(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a73,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a73,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a57(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a57,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a57,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_6x8__aarch64_neonfma_cortex_a75,
xnn_f32_gemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
xnn_f32_igemm_ukernel_1x8__aarch64_neonfma_cortex_a75,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__aarch64_neonfma_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__aarch64_neonfma_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__neonfma_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__neonfma_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__neonfma_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__neonfma_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_lane_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_lane_ld64,
6 /* mr */, 8 /* nr */);
}
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_ld64)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_ld128);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_ld64);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_ld128);
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a53)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a57)
BENCHMARK_END2END(f32_gemm_4x8__aarch64_neonfma_cortex_a75)
BENCHMARK_END2END(f32_gemm_5x8__aarch64_neonfma_cortex_a57);
BENCHMARK_END2END(f32_gemm_5x8__aarch64_neonfma_cortex_a75);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a53);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a73);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a57);
BENCHMARK_END2END(f32_gemm_6x8__aarch64_neonfma_cortex_a75);
BENCHMARK_END2END(f32_gemm_4x12__aarch64_neonfma_cortex_a53)
BENCHMARK_END2END(f32_gemm_4x8__neonfma_lane_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_lane_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_lane_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_lane_ld128);
#endif // XNN_ARCH_ARM64 && XNN_ENABLE_ASSEMBLY
#if XNN_ARCH_ARM && XNN_ENABLE_ASSEMBLY
static void f32_gemm_4x8__aarch32_neon_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_ld64,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_cortex_a53(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_cortex_a53,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_cortex_a75,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__aarch32_neon_pld_cortex_a75(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__aarch32_neon_pld_cortex_a75,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_ld64);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_cortex_a53);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_cortex_a75);
BENCHMARK_END2END(f32_gemm_4x8__aarch32_neon_pld_cortex_a75);
#endif // XNN_ARCH_ARM && XNN_ENABLE_ASSEMBLY
#if XNN_ARCH_ARM || XNN_ARCH_ARM64
static void f32_gemm_4x8__neon_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_lane_ld128,
xnn_f32_igemm_ukernel_4x8__neon_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_lane_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_6x8__neon_lane_ld64,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_lane_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_lane_ld128,
xnn_f32_igemm_ukernel_6x8__neon_lane_ld128,
xnn_f32_gemm_ukernel_1x8__neon_lane_ld64,
xnn_f32_igemm_ukernel_1x8__neon_lane_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_4x8__neon_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neon_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neon_dup_ld128,
xnn_f32_igemm_ukernel_4x8__neon_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_6x8__neon_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8__neon_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neon_dup_ld128,
xnn_f32_igemm_ukernel_6x8__neon_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neon_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neon_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8__neonfma_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_4x8__neonfma_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_4x8__neonfma_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__neonfma_dup_ld128,
xnn_f32_igemm_ukernel_4x8__neonfma_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8__neonfma_dup_ld64(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_6x8__neonfma_dup_ld64,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8__neonfma_dup_ld128(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__neonfma_dup_ld128,
xnn_f32_igemm_ukernel_6x8__neonfma_dup_ld128,
xnn_f32_gemm_ukernel_1x8__neonfma_dup_ld64,
xnn_f32_igemm_ukernel_1x8__neonfma_dup_ld64,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_4x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__neon,
xnn_f32_igemm_ukernel_4x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_4x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__neonfma,
xnn_f32_igemm_ukernel_4x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_6x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__neon,
xnn_f32_igemm_ukernel_6x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_6x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__neonfma,
xnn_f32_igemm_ukernel_6x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
static void f32_gemm_8x8s4__neon(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8s4__neon,
xnn_f32_igemm_ukernel_8x8s4__neon,
xnn_f32_gemm_ukernel_1x8s4__neon,
xnn_f32_igemm_ukernel_1x8s4__neon,
8 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEON);
}
static void f32_gemm_8x8s4__neonfma(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8s4__neonfma,
xnn_f32_igemm_ukernel_8x8s4__neonfma,
xnn_f32_gemm_ukernel_1x8s4__neonfma,
xnn_f32_igemm_ukernel_1x8s4__neonfma,
8 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */,
benchmark::utils::CheckNEONFMA);
}
BENCHMARK_END2END(f32_gemm_4x8__neon_lane_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neon_lane_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neon_lane_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neon_lane_ld128);
BENCHMARK_END2END(f32_gemm_4x8__neon_dup_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neon_dup_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neon_dup_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neon_dup_ld128);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_dup_ld64);
BENCHMARK_END2END(f32_gemm_4x8__neonfma_dup_ld128);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_dup_ld64);
BENCHMARK_END2END(f32_gemm_6x8__neonfma_dup_ld128);
BENCHMARK_END2END(f32_gemm_4x8s4__neon);
BENCHMARK_END2END(f32_gemm_6x8s4__neon);
BENCHMARK_END2END(f32_gemm_8x8s4__neon);
BENCHMARK_END2END(f32_gemm_4x8s4__neonfma);
BENCHMARK_END2END(f32_gemm_6x8s4__neonfma);
BENCHMARK_END2END(f32_gemm_8x8s4__neonfma);
#endif // XNN_ARCH_ARM || XNN_ARCH_ARM64
#if XNN_ARCH_X86 || XNN_ARCH_X86_64
static void f32_gemm_4x8__sse_load1(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__sse_load1,
xnn_f32_igemm_ukernel_4x8__sse_load1,
xnn_f32_gemm_ukernel_1x8__sse_load1,
xnn_f32_igemm_ukernel_1x8__sse_load1,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__sse_dup(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__sse_dup,
xnn_f32_igemm_ukernel_4x8__sse_dup,
xnn_f32_gemm_ukernel_1x8__sse_dup,
xnn_f32_igemm_ukernel_1x8__sse_dup,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8s4__sse(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__sse,
xnn_f32_igemm_ukernel_4x8s4__sse,
xnn_f32_gemm_ukernel_1x8s4__sse,
xnn_f32_igemm_ukernel_1x8s4__sse,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
static void f32_gemm_4x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__avx_broadcast,
xnn_f32_igemm_ukernel_4x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_5x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__avx_broadcast,
xnn_f32_igemm_ukernel_5x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
5 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_6x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__avx_broadcast,
xnn_f32_igemm_ukernel_6x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_7x8__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x8__avx_broadcast,
xnn_f32_igemm_ukernel_7x8__avx_broadcast,
xnn_f32_gemm_ukernel_1x8__avx_broadcast,
xnn_f32_igemm_ukernel_1x8__avx_broadcast,
7 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_3x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16__avx_broadcast,
xnn_f32_igemm_ukernel_3x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_4x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__avx_broadcast,
xnn_f32_igemm_ukernel_4x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_5x16__avx_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__avx_broadcast,
xnn_f32_igemm_ukernel_5x16__avx_broadcast,
xnn_f32_gemm_ukernel_1x16__avx_broadcast,
xnn_f32_igemm_ukernel_1x16__avx_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX);
}
static void f32_gemm_4x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__fma3_broadcast,
xnn_f32_igemm_ukernel_4x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
4 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x8__fma3_broadcast,
xnn_f32_igemm_ukernel_5x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
5 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_6x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__fma3_broadcast,
xnn_f32_igemm_ukernel_6x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
6 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_7x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x8__fma3_broadcast,
xnn_f32_igemm_ukernel_7x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
7 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_8x8__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x8__fma3_broadcast,
xnn_f32_igemm_ukernel_8x8__fma3_broadcast,
xnn_f32_gemm_ukernel_1x8__fma3_broadcast,
xnn_f32_igemm_ukernel_1x8__fma3_broadcast,
8 /* mr */, 8 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_3x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16__fma3_broadcast,
xnn_f32_igemm_ukernel_3x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__fma3_broadcast,
xnn_f32_igemm_ukernel_4x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x16__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__fma3_broadcast,
xnn_f32_igemm_ukernel_5x16__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16__fma3_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_3x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_3x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_3x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
3 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_4x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_5x16s4__fma3_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_5x16s4__fma3_broadcast,
xnn_f32_gemm_ukernel_1x16s4__fma3_broadcast,
xnn_f32_igemm_ukernel_1x16s4__fma3_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 2 /* log2_sr */,
benchmark::utils::CheckFMA3);
}
static void f32_gemm_4x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_4x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
4 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_5x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_5x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_5x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
5 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_6x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_6x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
6 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_7x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_7x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_7x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
7 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
static void f32_gemm_8x16__avx512f_broadcast(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_8x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_8x16__avx512f_broadcast,
xnn_f32_gemm_ukernel_1x16__avx512f_broadcast,
xnn_f32_igemm_ukernel_1x16__avx512f_broadcast,
8 /* mr */, 16 /* nr */, 0 /* log2_kr */, 0 /* log2_sr */,
benchmark::utils::CheckAVX512F);
}
BENCHMARK_END2END(f32_gemm_4x8__sse_load1);
BENCHMARK_END2END(f32_gemm_4x8__sse_dup);
BENCHMARK_END2END(f32_gemm_4x8s4__sse);
BENCHMARK_END2END(f32_gemm_4x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_5x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_6x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_7x8__avx_broadcast);
BENCHMARK_END2END(f32_gemm_3x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__avx_broadcast);
BENCHMARK_END2END(f32_gemm_4x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_6x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_7x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_8x8__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_3x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_3x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_5x16s4__fma3_broadcast);
BENCHMARK_END2END(f32_gemm_4x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_5x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_6x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_7x16__avx512f_broadcast);
BENCHMARK_END2END(f32_gemm_8x16__avx512f_broadcast);
#endif // XNN_ARCH_X86 || XNN_ARCH_X86_64
#if !XNN_ARCH_WASM && !XNN_ARCH_ASMJS
static void f32_gemm_4x8__psimd_loadsplat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_4x8__psimd_loadsplat,
xnn_f32_gemm_ukernel_1x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_1x8__psimd_loadsplat,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__psimd_loadsplat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_6x8__psimd_loadsplat,
xnn_f32_gemm_ukernel_1x8__psimd_loadsplat,
xnn_f32_igemm_ukernel_1x8__psimd_loadsplat,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8__psimd_splat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8__psimd_splat,
xnn_f32_igemm_ukernel_4x8__psimd_splat,
xnn_f32_gemm_ukernel_1x8__psimd_splat,
xnn_f32_igemm_ukernel_1x8__psimd_splat,
4 /* mr */, 8 /* nr */);
}
static void f32_gemm_6x8__psimd_splat(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8__psimd_splat,
xnn_f32_igemm_ukernel_6x8__psimd_splat,
xnn_f32_gemm_ukernel_1x8__psimd_splat,
xnn_f32_igemm_ukernel_1x8__psimd_splat,
6 /* mr */, 8 /* nr */);
}
static void f32_gemm_4x8s4__psimd(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x8s4__psimd,
xnn_f32_igemm_ukernel_4x8s4__psimd,
xnn_f32_gemm_ukernel_1x8s4__psimd,
xnn_f32_igemm_ukernel_1x8s4__psimd,
4 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
static void f32_gemm_6x8s4__psimd(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_6x8s4__psimd,
xnn_f32_igemm_ukernel_6x8s4__psimd,
xnn_f32_gemm_ukernel_1x8s4__psimd,
xnn_f32_igemm_ukernel_1x8s4__psimd,
6 /* mr */, 8 /* nr */, 0 /* log2(kr) */, 2 /* log2(sr) */);
}
BENCHMARK_END2END(f32_gemm_4x8__psimd_loadsplat);
BENCHMARK_END2END(f32_gemm_6x8__psimd_loadsplat);
BENCHMARK_END2END(f32_gemm_4x8__psimd_splat);
BENCHMARK_END2END(f32_gemm_6x8__psimd_splat);
BENCHMARK_END2END(f32_gemm_4x8s4__psimd);
BENCHMARK_END2END(f32_gemm_6x8s4__psimd);
#endif // !XNN_ARCH_WASM && !XNN_ARCH_ASMJS
#if XNN_ARCH_WASM
static void f32_gemm_2x4__wasm(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_2x4__wasm,
xnn_f32_igemm_ukernel_2x4__wasm,
xnn_f32_gemm_ukernel_1x4__wasm,
xnn_f32_igemm_ukernel_1x4__wasm,
2 /* mr */, 4 /* nr */);
}
static void f32_gemm_4x4__wasm(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x4__wasm,
xnn_f32_igemm_ukernel_4x4__wasm,
xnn_f32_gemm_ukernel_1x4__wasm,
xnn_f32_igemm_ukernel_1x4__wasm,
4 /* mr */, 4 /* nr */);
}
BENCHMARK_END2END(f32_gemm_2x4__wasm);
BENCHMARK_END2END(f32_gemm_4x4__wasm);
#endif // XNN_ARCH_WASM
static void f32_gemm_2x4__scalar(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_2x4__scalar,
xnn_f32_igemm_ukernel_2x4__scalar,
xnn_f32_gemm_ukernel_1x4__scalar,
xnn_f32_igemm_ukernel_1x4__scalar,
2 /* mr */, 4 /* nr */);
}
static void f32_gemm_4x4__scalar(benchmark::State& state, models::ExecutionPlanFactory model) {
GEMMEnd2EndBenchmark(state, model,
xnn_f32_gemm_ukernel_4x4__scalar,
xnn_f32_igemm_ukernel_4x4__scalar,
xnn_f32_gemm_ukernel_1x4__scalar,
xnn_f32_igemm_ukernel_1x4__scalar,
4 /* mr */, 4 /* nr */);
}
BENCHMARK_END2END(f32_gemm_2x4__scalar);
BENCHMARK_END2END(f32_gemm_4x4__scalar);
#ifndef XNNPACK_BENCHMARK_NO_MAIN
BENCHMARK_MAIN();
#endif
| 42.468716 | 118 | 0.758975 | 8thwall |
c83f0ec3181b13beda046594d829a86dfa6ac4c9 | 4,139 | cpp | C++ | private/shell/ext/intern/ftp.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/ext/intern/ftp.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/ext/intern/ftp.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | /*****************************************************************************
*
* ftp.cpp - FTP folder bookkeeping
*
*****************************************************************************/
#include "priv.h"
//#include "ftpinet.h"
//#include "ftpsite.h"
//#include "ftplist.h"
//#include "msieftp.h"
//#include "cookie.h"
extern struct GLOBALTIMEOUTINFO g_gti;
extern DWORD g_dwOpenConnections;
/*****************************************************************************
*
* Dynamic Globals. There should be as few of these as possible.
*
* All access to dynamic globals must be thread-safe.
*
*****************************************************************************/
ULONG g_cRef = 0; /* Global reference count */
CRITICAL_SECTION g_csDll; /* The shared critical section */
#ifdef DEBUG
DWORD g_TlsMem = 0xffffffff;
#endif // DEBUG
ULONG g_cRef_CFtpView = 0; // Needed to determine when to purge cache.
/*****************************************************************************
*
* DllAddRef / DllRelease
*
* Maintain the DLL reference count.
*
*****************************************************************************/
void DllAddRef(void)
{
InterlockedIncrement((LPLONG)&g_cRef);
}
void DllRelease(void)
{
InterlockedDecrement((LPLONG)&g_cRef);
}
/*****************************************************************************
*
* DllGetClassObject
*
* OLE entry point. Produces an IClassFactory for the indicated GUID.
*
* The artificial refcount inside DllGetClassObject helps to
* avoid the race condition described in DllCanUnloadNow. It's
* not perfect, but it makes the race window much smaller.
*
*****************************************************************************/
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID * ppvObj)
{
HRESULT hres;
DllAddRef();
// if (IsEqualIID(rclsid, CLSID_FtpFolder) ||
// IsEqualIID(rclsid, CLSID_FtpWebView))
{
hres = CFtpFactory_Create(rclsid, riid, ppvObj);
}
// else
// {
// *ppvObj = NULL;
// hres = CLASS_E_CLASSNOTAVAILABLE;
// }
DllRelease();
return hres;
}
/*****************************************************************************
*
* DllCanUnloadNow
*
* OLE entry point. Fail iff there are outstanding refs.
*
* There is an unavoidable race condition between DllCanUnloadNow
* and the creation of a new IClassFactory: Between the time we
* return from DllCanUnloadNow() and the caller inspects the value,
* another thread in the same process may decide to call
* DllGetClassObject, thus suddenly creating an object in this DLL
* when there previously was none.
*
* It is the caller's responsibility to prepare for this possibility;
* there is nothing we can do about it.
*
*****************************************************************************/
STDMETHODIMP DllCanUnloadNow(void)
{
HRESULT hres;
ENTERCRITICAL;
hres = g_cRef ? S_FALSE : S_OK;
TraceMsg(TF_FTP_DLLLOADING, "DllCanUnloadNow() returning hres=%#08lx. (S_OK means yes)", hres);
LEAVECRITICAL;
return hres;
}
/*****************************************************************************
*
* Entry32
*
* DLL entry point.
*
* BUGBUG -- On a thread detach, must check if the thread owns any
* global timeouts. If so, we must transfer the timeout to another
* thread or something.
*
*****************************************************************************/
STDAPI_(BOOL) DllEntry(HINSTANCE hinst, DWORD dwReason, LPVOID lpReserved)
{
static s_hresOle = E_FAIL;
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
InitializeCriticalSection(&g_csDll);
g_hinst = hinst;
DisableThreadLibraryCalls(hinst);
break;
case DLL_PROCESS_DETACH:
DeleteCriticalSection(&g_csDll);
break;
}
return 1;
}
const CLSID CLSID_FtpFolder = {0x63da6ec0, 0x2e98, 0x11cf, 0x8d,0x82,0x44,0x45,0x53,0x54,0,0};
| 26.876623 | 100 | 0.51051 | King0987654 |
c840e17677b80dd0f1995495c012c9b35d16fa86 | 18,358 | cpp | C++ | src/dawn_native/CopyTextureForBrowserHelper.cpp | AlexVestin/dawn-mirror | 2025d05accdb5b5de972ab50d0a3f68408280543 | [
"Apache-2.0"
] | null | null | null | src/dawn_native/CopyTextureForBrowserHelper.cpp | AlexVestin/dawn-mirror | 2025d05accdb5b5de972ab50d0a3f68408280543 | [
"Apache-2.0"
] | null | null | null | src/dawn_native/CopyTextureForBrowserHelper.cpp | AlexVestin/dawn-mirror | 2025d05accdb5b5de972ab50d0a3f68408280543 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The Dawn 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.
#include "dawn_native/CopyTextureForBrowserHelper.h"
#include "dawn_native/BindGroup.h"
#include "dawn_native/BindGroupLayout.h"
#include "dawn_native/Buffer.h"
#include "dawn_native/CommandBuffer.h"
#include "dawn_native/CommandEncoder.h"
#include "dawn_native/CommandValidation.h"
#include "dawn_native/Device.h"
#include "dawn_native/InternalPipelineStore.h"
#include "dawn_native/Queue.h"
#include "dawn_native/RenderPassEncoder.h"
#include "dawn_native/RenderPipeline.h"
#include "dawn_native/Sampler.h"
#include "dawn_native/Texture.h"
#include "dawn_native/ValidationUtils_autogen.h"
#include "dawn_native/utils/WGPUHelpers.h"
#include <unordered_set>
namespace dawn_native {
namespace {
static const char sCopyTextureForBrowserShader[] = R"(
[[block]] struct Uniforms {
u_scale: vec2<f32>;
u_offset: vec2<f32>;
u_alphaOp: u32;
};
[[binding(0), group(0)]] var<uniform> uniforms : Uniforms;
struct VertexOutputs {
[[location(0)]] texcoords : vec2<f32>;
[[builtin(position)]] position : vec4<f32>;
};
[[stage(vertex)]] fn vs_main(
[[builtin(vertex_index)]] VertexIndex : u32
) -> VertexOutputs {
var texcoord = array<vec2<f32>, 3>(
vec2<f32>(-0.5, 0.0),
vec2<f32>( 1.5, 0.0),
vec2<f32>( 0.5, 2.0));
var output : VertexOutputs;
output.position = vec4<f32>((texcoord[VertexIndex] * 2.0 - vec2<f32>(1.0, 1.0)), 0.0, 1.0);
// Y component of scale is calculated by the copySizeHeight / textureHeight. Only
// flipY case can get negative number.
var flipY = uniforms.u_scale.y < 0.0;
// Texture coordinate takes top-left as origin point. We need to map the
// texture to triangle carefully.
if (flipY) {
// We need to get the mirror positions(mirrored based on y = 0.5) on flip cases.
// Adopt transform to src texture and then mapping it to triangle coord which
// do a +1 shift on Y dimension will help us got that mirror position perfectly.
output.texcoords = (texcoord[VertexIndex] * uniforms.u_scale + uniforms.u_offset) *
vec2<f32>(1.0, -1.0) + vec2<f32>(0.0, 1.0);
} else {
// For the normal case, we need to get the exact position.
// So mapping texture to triangle firstly then adopt the transform.
output.texcoords = (texcoord[VertexIndex] *
vec2<f32>(1.0, -1.0) + vec2<f32>(0.0, 1.0)) *
uniforms.u_scale + uniforms.u_offset;
}
return output;
}
[[binding(1), group(0)]] var mySampler: sampler;
[[binding(2), group(0)]] var myTexture: texture_2d<f32>;
[[stage(fragment)]] fn fs_main(
[[location(0)]] texcoord : vec2<f32>
) -> [[location(0)]] vec4<f32> {
// Clamp the texcoord and discard the out-of-bound pixels.
var clampedTexcoord =
clamp(texcoord, vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 1.0));
if (!all(clampedTexcoord == texcoord)) {
discard;
}
// Swizzling of texture formats when sampling / rendering is handled by the
// hardware so we don't need special logic in this shader. This is covered by tests.
var srcColor = textureSample(myTexture, mySampler, texcoord);
// Handle alpha. Alpha here helps on the source content and dst content have
// different alpha config. There are three possible ops: DontChange, Premultiply
// and Unpremultiply.
// TODO(crbug.com/1217153): if wgsl support `constexpr` and allow it
// to be case selector, Replace 0u/1u/2u with a constexpr variable with
// meaningful name.
switch(uniforms.u_alphaOp) {
case 0u: { // AlphaOp: DontChange
break;
}
case 1u: { // AlphaOp: Premultiply
srcColor = vec4<f32>(srcColor.rgb * srcColor.a, srcColor.a);
break;
}
case 2u: { // AlphaOp: Unpremultiply
if (srcColor.a != 0.0) {
srcColor = vec4<f32>(srcColor.rgb / srcColor.a, srcColor.a);
}
break;
}
default: {
break;
}
}
return srcColor;
}
)";
struct Uniform {
float scaleX;
float scaleY;
float offsetX;
float offsetY;
wgpu::AlphaOp alphaOp;
};
static_assert(sizeof(Uniform) == 20, "");
// TODO(crbug.com/dawn/856): Expand copyTextureForBrowser to support any
// non-depth, non-stencil, non-compressed texture format pair copy. Now this API
// supports CopyImageBitmapToTexture normal format pairs.
MaybeError ValidateCopyTextureFormatConversion(const wgpu::TextureFormat srcFormat,
const wgpu::TextureFormat dstFormat) {
switch (srcFormat) {
case wgpu::TextureFormat::BGRA8Unorm:
case wgpu::TextureFormat::RGBA8Unorm:
break;
default:
return DAWN_FORMAT_VALIDATION_ERROR(
"Source texture format (%s) is not supported.", srcFormat);
}
switch (dstFormat) {
case wgpu::TextureFormat::R8Unorm:
case wgpu::TextureFormat::R16Float:
case wgpu::TextureFormat::R32Float:
case wgpu::TextureFormat::RG8Unorm:
case wgpu::TextureFormat::RG16Float:
case wgpu::TextureFormat::RG32Float:
case wgpu::TextureFormat::RGBA8Unorm:
case wgpu::TextureFormat::RGBA8UnormSrgb:
case wgpu::TextureFormat::BGRA8Unorm:
case wgpu::TextureFormat::BGRA8UnormSrgb:
case wgpu::TextureFormat::RGB10A2Unorm:
case wgpu::TextureFormat::RGBA16Float:
case wgpu::TextureFormat::RGBA32Float:
break;
default:
return DAWN_FORMAT_VALIDATION_ERROR(
"Destination texture format (%s) is not supported.", dstFormat);
}
return {};
}
RenderPipelineBase* GetCachedPipeline(InternalPipelineStore* store,
wgpu::TextureFormat dstFormat) {
auto pipeline = store->copyTextureForBrowserPipelines.find(dstFormat);
if (pipeline != store->copyTextureForBrowserPipelines.end()) {
return pipeline->second.Get();
}
return nullptr;
}
ResultOrError<RenderPipelineBase*> GetOrCreateCopyTextureForBrowserPipeline(
DeviceBase* device,
wgpu::TextureFormat dstFormat) {
InternalPipelineStore* store = device->GetInternalPipelineStore();
if (GetCachedPipeline(store, dstFormat) == nullptr) {
// Create vertex shader module if not cached before.
if (store->copyTextureForBrowser == nullptr) {
DAWN_TRY_ASSIGN(
store->copyTextureForBrowser,
utils::CreateShaderModule(device, sCopyTextureForBrowserShader));
}
ShaderModuleBase* shaderModule = store->copyTextureForBrowser.Get();
// Prepare vertex stage.
VertexState vertex = {};
vertex.module = shaderModule;
vertex.entryPoint = "vs_main";
// Prepare frgament stage.
FragmentState fragment = {};
fragment.module = shaderModule;
fragment.entryPoint = "fs_main";
// Prepare color state.
ColorTargetState target = {};
target.format = dstFormat;
// Create RenderPipeline.
RenderPipelineDescriptor renderPipelineDesc = {};
// Generate the layout based on shader modules.
renderPipelineDesc.layout = nullptr;
renderPipelineDesc.vertex = vertex;
renderPipelineDesc.fragment = &fragment;
renderPipelineDesc.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
fragment.targetCount = 1;
fragment.targets = ⌖
Ref<RenderPipelineBase> pipeline;
DAWN_TRY_ASSIGN(pipeline, device->CreateRenderPipeline(&renderPipelineDesc));
store->copyTextureForBrowserPipelines.insert({dstFormat, std::move(pipeline)});
}
return GetCachedPipeline(store, dstFormat);
}
} // anonymous namespace
MaybeError ValidateCopyTextureForBrowser(DeviceBase* device,
const ImageCopyTexture* source,
const ImageCopyTexture* destination,
const Extent3D* copySize,
const CopyTextureForBrowserOptions* options) {
DAWN_TRY(device->ValidateObject(source->texture));
DAWN_TRY(device->ValidateObject(destination->texture));
DAWN_TRY_CONTEXT(ValidateImageCopyTexture(device, *source, *copySize),
"validating the ImageCopyTexture for the source");
DAWN_TRY_CONTEXT(ValidateImageCopyTexture(device, *destination, *copySize),
"validating the ImageCopyTexture for the destination");
DAWN_TRY_CONTEXT(ValidateTextureCopyRange(device, *source, *copySize),
"validating that the copy fits in the source");
DAWN_TRY_CONTEXT(ValidateTextureCopyRange(device, *destination, *copySize),
"validating that the copy fits in the destination");
DAWN_TRY(ValidateTextureToTextureCopyCommonRestrictions(*source, *destination, *copySize));
DAWN_INVALID_IF(source->origin.z > 0, "Source has a non-zero z origin (%u).",
source->origin.z);
DAWN_INVALID_IF(copySize->depthOrArrayLayers > 1,
"Copy is for more than one array layer (%u)", copySize->depthOrArrayLayers);
DAWN_INVALID_IF(
source->texture->GetSampleCount() > 1 || destination->texture->GetSampleCount() > 1,
"The source texture sample count (%u) or the destination texture sample count (%u) is "
"not 1.",
source->texture->GetSampleCount(), destination->texture->GetSampleCount());
DAWN_TRY(ValidateCanUseAs(source->texture, wgpu::TextureUsage::CopySrc));
DAWN_TRY(ValidateCanUseAs(source->texture, wgpu::TextureUsage::TextureBinding));
DAWN_TRY(ValidateCanUseAs(destination->texture, wgpu::TextureUsage::CopyDst));
DAWN_TRY(ValidateCanUseAs(destination->texture, wgpu::TextureUsage::RenderAttachment));
DAWN_TRY(ValidateCopyTextureFormatConversion(source->texture->GetFormat().format,
destination->texture->GetFormat().format));
DAWN_INVALID_IF(options->nextInChain != nullptr, "nextInChain must be nullptr");
DAWN_TRY(ValidateAlphaOp(options->alphaOp));
return {};
}
MaybeError DoCopyTextureForBrowser(DeviceBase* device,
const ImageCopyTexture* source,
const ImageCopyTexture* destination,
const Extent3D* copySize,
const CopyTextureForBrowserOptions* options) {
// TODO(crbug.com/dawn/856): In D3D12 and Vulkan, compatible texture format can directly
// copy to each other. This can be a potential fast path.
// Noop copy
if (copySize->width == 0 || copySize->height == 0 || copySize->depthOrArrayLayers == 0) {
return {};
}
RenderPipelineBase* pipeline;
DAWN_TRY_ASSIGN(pipeline, GetOrCreateCopyTextureForBrowserPipeline(
device, destination->texture->GetFormat().format));
// Prepare bind group layout.
Ref<BindGroupLayoutBase> layout;
DAWN_TRY_ASSIGN(layout, pipeline->GetBindGroupLayout(0));
Extent3D srcTextureSize = source->texture->GetSize();
// Prepare binding 0 resource: uniform buffer.
Uniform uniformData = {
copySize->width / static_cast<float>(srcTextureSize.width),
copySize->height / static_cast<float>(srcTextureSize.height), // scale
source->origin.x / static_cast<float>(srcTextureSize.width),
source->origin.y / static_cast<float>(srcTextureSize.height), // offset
wgpu::AlphaOp::DontChange // alphaOp default value: DontChange
};
// Handle flipY. FlipY here means we flip the source texture firstly and then
// do copy. This helps on the case which source texture is flipped and the copy
// need to unpack the flip.
if (options->flipY) {
uniformData.scaleY *= -1.0;
uniformData.offsetY += copySize->height / static_cast<float>(srcTextureSize.height);
}
// Set alpha op.
uniformData.alphaOp = options->alphaOp;
Ref<BufferBase> uniformBuffer;
DAWN_TRY_ASSIGN(
uniformBuffer,
utils::CreateBufferFromData(
device, wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform, {uniformData}));
// Prepare binding 1 resource: sampler
// Use default configuration, filterMode set to Nearest for min and mag.
SamplerDescriptor samplerDesc = {};
Ref<SamplerBase> sampler;
DAWN_TRY_ASSIGN(sampler, device->CreateSampler(&samplerDesc));
// Prepare binding 2 resource: sampled texture
TextureViewDescriptor srcTextureViewDesc = {};
srcTextureViewDesc.baseMipLevel = source->mipLevel;
srcTextureViewDesc.mipLevelCount = 1;
srcTextureViewDesc.arrayLayerCount = 1;
Ref<TextureViewBase> srcTextureView;
DAWN_TRY_ASSIGN(srcTextureView,
device->CreateTextureView(source->texture, &srcTextureViewDesc));
// Create bind group after all binding entries are set.
Ref<BindGroupBase> bindGroup;
DAWN_TRY_ASSIGN(bindGroup, utils::MakeBindGroup(
device, layout,
{{0, uniformBuffer}, {1, sampler}, {2, srcTextureView}}));
// Create command encoder.
CommandEncoderDescriptor encoderDesc = {};
// TODO(dawn:723): change to not use AcquireRef for reentrant object creation.
Ref<CommandEncoder> encoder = AcquireRef(device->APICreateCommandEncoder(&encoderDesc));
// Prepare dst texture view as color Attachment.
TextureViewDescriptor dstTextureViewDesc;
dstTextureViewDesc.baseMipLevel = destination->mipLevel;
dstTextureViewDesc.mipLevelCount = 1;
dstTextureViewDesc.baseArrayLayer = destination->origin.z;
dstTextureViewDesc.arrayLayerCount = 1;
Ref<TextureViewBase> dstView;
DAWN_TRY_ASSIGN(dstView,
device->CreateTextureView(destination->texture, &dstTextureViewDesc));
// Prepare render pass color attachment descriptor.
RenderPassColorAttachment colorAttachmentDesc;
colorAttachmentDesc.view = dstView.Get();
colorAttachmentDesc.loadOp = wgpu::LoadOp::Load;
colorAttachmentDesc.storeOp = wgpu::StoreOp::Store;
colorAttachmentDesc.clearColor = {0.0, 0.0, 0.0, 1.0};
// Create render pass.
RenderPassDescriptor renderPassDesc;
renderPassDesc.colorAttachmentCount = 1;
renderPassDesc.colorAttachments = &colorAttachmentDesc;
// TODO(dawn:723): change to not use AcquireRef for reentrant object creation.
Ref<RenderPassEncoder> passEncoder =
AcquireRef(encoder->APIBeginRenderPass(&renderPassDesc));
// Start pipeline and encode commands to complete
// the copy from src texture to dst texture with transformation.
passEncoder->APISetPipeline(pipeline);
passEncoder->APISetBindGroup(0, bindGroup.Get());
passEncoder->APISetViewport(destination->origin.x, destination->origin.y, copySize->width,
copySize->height, 0.0, 1.0);
passEncoder->APIDraw(3);
passEncoder->APIEndPass();
// Finsh encoding.
// TODO(dawn:723): change to not use AcquireRef for reentrant object creation.
Ref<CommandBufferBase> commandBuffer = AcquireRef(encoder->APIFinish());
CommandBufferBase* submitCommandBuffer = commandBuffer.Get();
// Submit command buffer.
device->GetQueue()->APISubmit(1, &submitCommandBuffer);
return {};
}
} // namespace dawn_native
| 44.995098 | 107 | 0.586229 | AlexVestin |
c846a6d1428fec3fcb4b87b37d69b531a43feb7c | 12,533 | cc | C++ | chrome/browser/ui/webui/options/search_engine_manager_handler.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | chrome/browser/ui/webui/options/search_engine_manager_handler.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/options/search_engine_manager_handler.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options/search_engine_manager_handler.h"
#include "base/bind.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
#include "chrome/browser/ui/search_engines/keyword_editor_controller.h"
#include "chrome/browser/ui/search_engines/template_url_table_model.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/locale_settings.h"
#include "components/search_engines/template_url.h"
#include "components/search_engines/template_url_service.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_ui.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
enum EngineInfoIndexes {
ENGINE_NAME,
ENGINE_KEYWORD,
ENGINE_URL,
};
}; // namespace
namespace options {
SearchEngineManagerHandler::SearchEngineManagerHandler() {
}
SearchEngineManagerHandler::~SearchEngineManagerHandler() {
if (list_controller_.get() && list_controller_->table_model())
list_controller_->table_model()->SetObserver(NULL);
}
void SearchEngineManagerHandler::InitializeHandler() {
list_controller_.reset(
new KeywordEditorController(Profile::FromWebUI(web_ui())));
DCHECK(list_controller_.get());
list_controller_->table_model()->SetObserver(this);
}
void SearchEngineManagerHandler::InitializePage() {
OnModelChanged();
}
void SearchEngineManagerHandler::GetLocalizedValues(
base::DictionaryValue* localized_strings) {
DCHECK(localized_strings);
RegisterTitle(localized_strings, "searchEngineManagerPage",
IDS_SEARCH_ENGINES_EDITOR_WINDOW_TITLE);
localized_strings->SetString("defaultSearchEngineListTitle",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAIN_SEPARATOR));
localized_strings->SetString("otherSearchEngineListTitle",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_OTHER_SEPARATOR));
localized_strings->SetString("extensionKeywordsListTitle",
l10n_util::GetStringUTF16(
IDS_SEARCH_ENGINES_EDITOR_EXTENSIONS_SEPARATOR));
localized_strings->SetString("makeDefaultSearchEngineButton",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_EDITOR_MAKE_DEFAULT_BUTTON));
localized_strings->SetString("searchEngineTableNamePlaceholder",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_NAME_PLACEHOLDER));
localized_strings->SetString("searchEngineTableKeywordPlaceholder",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_KEYWORD_PLACEHOLDER));
localized_strings->SetString("searchEngineTableURLPlaceholder",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINE_ADD_NEW_URL_PLACEHOLDER));
localized_strings->SetString("editSearchEngineInvalidTitleToolTip",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_TITLE_TT));
localized_strings->SetString("editSearchEngineInvalidKeywordToolTip",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_KEYWORD_TT));
localized_strings->SetString("editSearchEngineInvalidURLToolTip",
l10n_util::GetStringUTF16(IDS_SEARCH_ENGINES_INVALID_URL_TT));
}
void SearchEngineManagerHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"managerSetDefaultSearchEngine",
base::Bind(&SearchEngineManagerHandler::SetDefaultSearchEngine,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"removeSearchEngine",
base::Bind(&SearchEngineManagerHandler::RemoveSearchEngine,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"editSearchEngine",
base::Bind(&SearchEngineManagerHandler::EditSearchEngine,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"checkSearchEngineInfoValidity",
base::Bind(&SearchEngineManagerHandler::CheckSearchEngineInfoValidity,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"searchEngineEditCancelled",
base::Bind(&SearchEngineManagerHandler::EditCancelled,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"searchEngineEditCompleted",
base::Bind(&SearchEngineManagerHandler::EditCompleted,
base::Unretained(this)));
}
void SearchEngineManagerHandler::OnModelChanged() {
DCHECK(list_controller_.get());
if (!list_controller_->loaded())
return;
// Find the default engine.
const TemplateURL* default_engine =
list_controller_->GetDefaultSearchProvider();
int default_index = list_controller_->table_model()->IndexOfTemplateURL(
default_engine);
// Build the first list (default search engine options).
base::ListValue defaults_list;
int last_default_engine_index =
list_controller_->table_model()->last_search_engine_index();
for (int i = 0; i < last_default_engine_index; ++i) {
// Third argument is false, as the engine is not from an extension.
defaults_list.Append(CreateDictionaryForEngine(
i, i == default_index));
}
// Build the second list (other search templates).
base::ListValue others_list;
int last_other_engine_index =
list_controller_->table_model()->last_other_engine_index();
if (last_default_engine_index < 0)
last_default_engine_index = 0;
for (int i = last_default_engine_index; i < last_other_engine_index; ++i) {
others_list.Append(CreateDictionaryForEngine(i, i == default_index));
}
// Build the extension keywords list.
base::ListValue keyword_list;
if (last_other_engine_index < 0)
last_other_engine_index = 0;
int engine_count = list_controller_->table_model()->RowCount();
for (int i = last_other_engine_index; i < engine_count; ++i) {
keyword_list.Append(CreateDictionaryForEngine(i, i == default_index));
}
web_ui()->CallJavascriptFunctionUnsafe(
"SearchEngineManager.updateSearchEngineList", defaults_list, others_list,
keyword_list);
}
void SearchEngineManagerHandler::OnItemsChanged(int start, int length) {
OnModelChanged();
}
void SearchEngineManagerHandler::OnItemsAdded(int start, int length) {
OnModelChanged();
}
void SearchEngineManagerHandler::OnItemsRemoved(int start, int length) {
OnModelChanged();
}
std::unique_ptr<base::DictionaryValue>
SearchEngineManagerHandler::CreateDictionaryForEngine(int index,
bool is_default) {
TemplateURLTableModel* table_model = list_controller_->table_model();
const TemplateURL* template_url = list_controller_->GetTemplateURL(index);
// The items which are to be written into |dict| are also described in
// chrome/browser/resources/options/search_engine_manager_engine_list.js
// in @typedef for SearchEngine. Please update it whenever you add or remove
// any keys here.
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetString("name", template_url->short_name());
dict->SetString("displayName", table_model->GetText(
index, IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_COLUMN));
dict->SetString("keyword", table_model->GetText(
index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN));
dict->SetString("url", template_url->url_ref().DisplayURL(
UIThreadSearchTermsData(Profile::FromWebUI(web_ui()))));
dict->SetBoolean("urlLocked", template_url->prepopulate_id() > 0);
GURL icon_url = template_url->favicon_url();
if (icon_url.is_valid())
dict->SetString("iconURL", icon_url.spec());
dict->SetString("modelIndex", base::IntToString(index));
dict->SetBoolean("canBeRemoved",
list_controller_->CanRemove(template_url));
dict->SetBoolean("canBeDefault",
list_controller_->CanMakeDefault(template_url));
dict->SetBoolean("default", is_default);
dict->SetBoolean("canBeEdited", list_controller_->CanEdit(template_url));
TemplateURL::Type type = template_url->GetType();
dict->SetBoolean("isOmniboxExtension",
type == TemplateURL::OMNIBOX_API_EXTENSION);
if (type == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION ||
type == TemplateURL::OMNIBOX_API_EXTENSION) {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))
->GetExtensionById(template_url->GetExtensionId(),
extensions::ExtensionRegistry::EVERYTHING);
if (extension) {
dict->Set("extension",
extensions::util::GetExtensionInfo(extension).release());
}
}
return dict;
}
void SearchEngineManagerHandler::SetDefaultSearchEngine(
const base::ListValue* args) {
int index;
if (!ExtractIntegerValue(args, &index)) {
NOTREACHED();
return;
}
if (index < 0 || index >= list_controller_->table_model()->RowCount())
return;
list_controller_->MakeDefaultTemplateURL(index);
content::RecordAction(
base::UserMetricsAction("Options_SearchEngineSetDefault"));
}
void SearchEngineManagerHandler::RemoveSearchEngine(
const base::ListValue* args) {
int index;
if (!ExtractIntegerValue(args, &index)) {
NOTREACHED();
return;
}
if (index < 0 || index >= list_controller_->table_model()->RowCount())
return;
if (list_controller_->CanRemove(list_controller_->GetTemplateURL(index))) {
list_controller_->RemoveTemplateURL(index);
content::RecordAction(
base::UserMetricsAction("Options_SearchEngineRemoved"));
}
}
void SearchEngineManagerHandler::EditSearchEngine(const base::ListValue* args) {
int index;
if (!ExtractIntegerValue(args, &index)) {
NOTREACHED();
return;
}
// Allow -1, which means we are adding a new engine.
if (index < -1 || index >= list_controller_->table_model()->RowCount())
return;
edit_controller_.reset(new EditSearchEngineController(
(index == -1) ? NULL : list_controller_->GetTemplateURL(index), this,
Profile::FromWebUI(web_ui())));
}
void SearchEngineManagerHandler::OnEditedKeyword(
TemplateURL* template_url,
const base::string16& title,
const base::string16& keyword,
const std::string& url) {
DCHECK(!url.empty());
if (template_url)
list_controller_->ModifyTemplateURL(template_url, title, keyword, url);
else
list_controller_->AddTemplateURL(title, keyword, url);
edit_controller_.reset();
}
void SearchEngineManagerHandler::CheckSearchEngineInfoValidity(
const base::ListValue* args) {
if (!edit_controller_.get())
return;
base::string16 name;
base::string16 keyword;
std::string url;
std::string modelIndex;
if (!args->GetString(ENGINE_NAME, &name) ||
!args->GetString(ENGINE_KEYWORD, &keyword) ||
!args->GetString(ENGINE_URL, &url) ||
!args->GetString(3, &modelIndex)) {
NOTREACHED();
return;
}
base::DictionaryValue validity;
validity.SetBoolean("name", edit_controller_->IsTitleValid(name));
validity.SetBoolean("keyword", edit_controller_->IsKeywordValid(keyword));
validity.SetBoolean("url", edit_controller_->IsURLValid(url));
base::StringValue indexValue(modelIndex);
web_ui()->CallJavascriptFunctionUnsafe(
"SearchEngineManager.validityCheckCallback", validity, indexValue);
}
void SearchEngineManagerHandler::EditCancelled(const base::ListValue* args) {
if (!edit_controller_.get())
return;
edit_controller_->CleanUpCancelledAdd();
edit_controller_.reset();
}
void SearchEngineManagerHandler::EditCompleted(const base::ListValue* args) {
if (!edit_controller_.get())
return;
base::string16 name;
base::string16 keyword;
std::string url;
if (!args->GetString(ENGINE_NAME, &name) ||
!args->GetString(ENGINE_KEYWORD, &keyword) ||
!args->GetString(ENGINE_URL, &url)) {
NOTREACHED();
return;
}
// Recheck validity. It's possible to get here with invalid input if e.g. the
// user calls the right JS functions directly from the web inspector.
if (edit_controller_->IsTitleValid(name) &&
edit_controller_->IsKeywordValid(keyword) &&
edit_controller_->IsURLValid(url))
edit_controller_->AcceptAddOrEdit(name, keyword, url);
}
} // namespace options
| 37.523952 | 80 | 0.740844 | Wzzzx |
c8473758cf0d4f5b12c9ebb54a5803c3298ffa57 | 3,672 | cpp | C++ | src/vcruntime/ehveccvb.cpp | avboy1337/ucxxrt | d72a1c02606475ac6c1528d7413efe9203009152 | [
"MIT"
] | 130 | 2020-02-29T09:12:43.000Z | 2022-03-19T23:33:57.000Z | src/vcruntime/ehveccvb.cpp | avboy1337/ucxxrt | d72a1c02606475ac6c1528d7413efe9203009152 | [
"MIT"
] | 7 | 2020-08-06T08:08:52.000Z | 2022-02-20T04:23:57.000Z | src/vcruntime/ehveccvb.cpp | avboy1337/ucxxrt | d72a1c02606475ac6c1528d7413efe9203009152 | [
"MIT"
] | 47 | 2020-03-01T01:35:53.000Z | 2022-03-24T12:15:03.000Z | /*
* PROJECT: Universal C++ RunTime (UCXXRT)
* FILE: ehveccvb.cpp
* DATA: 2021/05/27
*
* PURPOSE: Universal C++ RunTime
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (miro.kaku AT Outlook.com)
*/
/***
*ehveccvb.cpp - EH c-tor iterator helper function for class w/ virtual bases
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* EH-aware version of constructor iterator helper function for class
* with virtual bases
*
* These functions are called when constructing and destructing arrays of
* objects. Their purpose is to assure that constructed elements get
* destructed if the constructor for one of the elements throws.
*
* These functions are called when constructing and destructing arrays of
* objects. Their purpose is to assure that constructed elements get
* destructed if the constructor for one of the elements throws.
*
* Must be compiled using "-d1Binl" to be able to specify __thiscall
* at the user level
****/
#include <eh.h>
#if defined _M_CEE
#define CALLTYPE __clrcall
#define CALLEETYPE __clrcall
#define __RELIABILITY_CONTRACT \
[System::Runtime::ConstrainedExecution::ReliabilityContract( \
System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \
System::Runtime::ConstrainedExecution::Cer::Success \
)]
#else
#define CALLEETYPE __stdcall
#define __RELIABILITY_CONTRACT
#if defined _M_IX86
#define CALLTYPE __thiscall
#else
#define CALLTYPE __stdcall
#endif
#endif
using constructor_type = void (CALLTYPE*)(void*);
using destructor_type = void (CALLTYPE*)(void*);
__RELIABILITY_CONTRACT
void CALLEETYPE __ArrayUnwind(
void* ptr, // Pointer to array to destruct
size_t size, // Size of each element (including padding)
size_t count, // Number of elements in the array
destructor_type destructor // The destructor to call
);
__RELIABILITY_CONTRACT
void CALLEETYPE __ehvec_ctor_vb(
void* ptr, // Pointer to array to destruct
size_t size, // Size of each element (including padding)
size_t count, // Number of elements in the array
constructor_type constructor, // Constructor to call
destructor_type destructor // Destructor to call should exception be thrown
)
{
size_t i{0};
bool success{false};
__try
{
for (; i != count; ++i)
{
#pragma warning(push)
#pragma warning(disable: 4191) // unsafe conversion
reinterpret_cast<void (CALLTYPE*)(void*, int)>(constructor)(ptr, 1);
#pragma warning(pop)
ptr = static_cast<char*>(ptr) + size;
}
success = true;
}
__finally
{
if (!success)
{
__ArrayUnwind(ptr, size, i, destructor);
}
}
}
__RELIABILITY_CONTRACT
void CALLEETYPE __ehvec_ctor_vb(
void* ptr, // Pointer to array to destruct
size_t size, // Size of each element (including padding)
int count, // Number of elements in the array
constructor_type constructor, // Constructor to call
destructor_type destructor // Destructor to call should exception be thrown
)
{
__ehvec_ctor_vb(ptr, size, static_cast<size_t>(count), constructor, destructor);
}
| 32.785714 | 86 | 0.620643 | avboy1337 |
c848f87a61cf0dc10222a92e86d0f0a405a585e2 | 1,877 | cc | C++ | netlibcc/net/test/test_IOThreadPool.cc | kohakus/tiny-netlib | da9998ee06f4e2eb5ebcaf0e383196269dea1f33 | [
"MIT"
] | 1 | 2021-03-05T10:14:27.000Z | 2021-03-05T10:14:27.000Z | netlibcc/net/test/test_IOThreadPool.cc | kohakus/tiny-netlib | da9998ee06f4e2eb5ebcaf0e383196269dea1f33 | [
"MIT"
] | null | null | null | netlibcc/net/test/test_IOThreadPool.cc | kohakus/tiny-netlib | da9998ee06f4e2eb5ebcaf0e383196269dea1f33 | [
"MIT"
] | null | null | null | #include "netlibcc/net/IOThreadPool.h"
#include <unistd.h>
#include <cstdio>
#include "netlibcc/net/EventLoop.h"
#include "netlibcc/core/Thread.h"
using namespace netlibcc;
using namespace netlibcc::net;
void showId(EventLoop* loop = nullptr) {
printf("showId: pid = %d, tid = %d, loop = %p\n", getpid(), thisthread::tid(), loop);
}
void threadFunc(EventLoop* loop) {
printf("threadFunc: pid = %d, tid = %d, loop = %p\n", getpid(), thisthread::tid(), loop);
}
int main() {
showId();
EventLoop loop;
loop.runAfter(11, std::bind(&EventLoop::quit, &loop));
// only main thread
{
printf("Single thread %p:\n", &loop);
IOThreadPool pool(&loop, "single");
pool.setThreadNum(0);
pool.start(threadFunc);
assert(pool.getNextLoop() == &loop);
assert(pool.getNextLoop() == &loop);
assert(pool.getNextLoop() == &loop);
}
// main thread + another IOThread
{
printf("Another Thread:\n");
IOThreadPool pool(&loop, "another");
pool.setThreadNum(1);
pool.start(threadFunc);
EventLoop* next_loop = pool.getNextLoop();
next_loop->runAfter(2, std::bind(showId, next_loop));
assert(next_loop != &loop);
assert(next_loop == pool.getNextLoop());
assert(next_loop == pool.getNextLoop());
::sleep(3);
}
// main thread + 3 other threads
{
printf("Three other threads:\n");
IOThreadPool pool(&loop, "three");
pool.setThreadNum(3);
pool.start(threadFunc);
EventLoop* next_loop = pool.getNextLoop();
next_loop->runInLoop(std::bind(showId, next_loop));
assert(next_loop != &loop);
assert(next_loop != pool.getNextLoop());
assert(next_loop != pool.getNextLoop());
assert(next_loop == pool.getNextLoop());
}
loop.loop();
} | 28.439394 | 93 | 0.59723 | kohakus |
c84d5d91ddc5761d0aee4e3392dfe62c2d0223a6 | 826 | cpp | C++ | Regression_test/examples/fir/src/fir.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 46 | 2019-11-16T13:44:07.000Z | 2022-03-12T14:28:44.000Z | Regression_test/examples/fir/src/fir.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 11 | 2020-05-12T17:20:51.000Z | 2022-02-04T10:04:59.000Z | Regression_test/examples/fir/src/fir.cpp | minseongg/dynamatic | 268d97690f128569da46e4f39a99346e93ee9d4e | [
"MIT"
] | 22 | 2020-02-21T21:33:40.000Z | 2022-02-24T06:50:41.000Z | #include "fir.h"
//------------------------------------------------------------------------
// FIR
//------------------------------------------------------------------------
//SEPARATOR_FOR_MAIN
#include <stdlib.h>
#include "fir.h"
#define AMOUNT_OF_TEST 1
int fir (in_int_t d_i[1000], in_int_t idx[1000] ) {
int i;
int tmp=0;
For_Loop: for (i=0;i<1000;i++) {
tmp += idx [i] * d_i[999-i];
}
//out [0] = tmp;
return tmp;
}
int main(void){
in_int_t d_i[AMOUNT_OF_TEST][1000];
in_int_t idx[AMOUNT_OF_TEST][1000];
inout_int_t out[AMOUNT_OF_TEST][1000];
srand(13);
for(int i = 0; i < AMOUNT_OF_TEST; ++i){
for(int j = 0; j < 1000; ++j){
d_i[0][j] = rand() % 100;
idx[0][j] = rand() % 100;
}
}
for(int i = 0; i < 1; ++i){
fir(d_i[0], idx[0] );
}
}
//SEPARATOR_FOR_MAIN
| 17.574468 | 74 | 0.464891 | minseongg |
c84d7ff01803f6ae49544876486531a3c7ff4f53 | 3,388 | cc | C++ | test/vp9_denoiser_sse2_test.cc | golden1232004/libvpx | 61a8b8673411110823d31ffd9d3e28d5023c5e9f | [
"BSD-3-Clause"
] | 2 | 2020-04-26T02:42:56.000Z | 2021-01-15T00:25:16.000Z | test/vp9_denoiser_sse2_test.cc | golden1232004/libvpx | 61a8b8673411110823d31ffd9d3e28d5023c5e9f | [
"BSD-3-Clause"
] | null | null | null | test/vp9_denoiser_sse2_test.cc | golden1232004/libvpx | 61a8b8673411110823d31ffd9d3e28d5023c5e9f | [
"BSD-3-Clause"
] | 1 | 2017-01-19T10:33:37.000Z | 2017-01-19T10:33:37.000Z | /*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/util.h"
#include "vpx_scale/yv12config.h"
#include "vpx/vpx_integer.h"
#include "vp9/common/vp9_reconinter.h"
#include "vp9/encoder/vp9_context_tree.h"
#include "vp9/encoder/vp9_denoiser.h"
using libvpx_test::ACMRandom;
namespace {
const int kNumPixels = 64 * 64;
class VP9DenoiserTest : public ::testing::TestWithParam<BLOCK_SIZE> {
public:
virtual ~VP9DenoiserTest() {}
virtual void SetUp() {
bs_ = GetParam();
}
virtual void TearDown() { libvpx_test::ClearSystemState(); }
protected:
BLOCK_SIZE bs_;
};
TEST_P(VP9DenoiserTest, BitexactCheck) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 4000;
// Allocate the space for input and output,
// where sig_block is the block to be denoised,
// mc_avg_block is the denoised reference block,
// avg_block_c is the denoised result from C code,
// avg_block_sse2 is the denoised result from SSE2 code.
DECLARE_ALIGNED(16, uint8_t, sig_block[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, mc_avg_block[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, avg_block_c[kNumPixels]);
DECLARE_ALIGNED(16, uint8_t, avg_block_sse2[kNumPixels]);
for (int i = 0; i < count_test_block; ++i) {
// Generate random motion magnitude, 20% of which exceed the threshold.
const int motion_magnitude_random =
rnd.Rand8() % static_cast<int>(MOTION_MAGNITUDE_THRESHOLD * 1.2);
// Initialize a test block with random number in range [0, 255].
for (int j = 0; j < kNumPixels; ++j) {
int temp = 0;
sig_block[j] = rnd.Rand8();
// The pixels in mc_avg_block are generated by adding a random
// number in range [-19, 19] to corresponding pixels in sig_block.
temp = sig_block[j] + ((rnd.Rand8() % 2 == 0) ? -1 : 1) *
(rnd.Rand8() % 20);
// Clip.
mc_avg_block[j] = (temp < 0) ? 0 : ((temp > 255) ? 255 : temp);
}
ASM_REGISTER_STATE_CHECK(vp9_denoiser_filter_c(
sig_block, 64, mc_avg_block, 64, avg_block_c,
64, 0, bs_, motion_magnitude_random));
ASM_REGISTER_STATE_CHECK(vp9_denoiser_filter_sse2(
sig_block, 64, mc_avg_block, 64, avg_block_sse2,
64, 0, bs_, motion_magnitude_random));
// Test bitexactness.
for (int h = 0; h < (4 << b_height_log2_lookup[bs_]); ++h) {
for (int w = 0; w < (4 << b_width_log2_lookup[bs_]); ++w) {
EXPECT_EQ(avg_block_c[h * 64 + w], avg_block_sse2[h * 64 + w]);
}
}
}
}
// Test for all block size.
INSTANTIATE_TEST_CASE_P(
SSE2, VP9DenoiserTest,
::testing::Values(BLOCK_8X8, BLOCK_8X16, BLOCK_16X8, BLOCK_16X16,
BLOCK_16X32, BLOCK_32X16, BLOCK_32X32, BLOCK_32X64,
BLOCK_64X32, BLOCK_64X64));
} // namespace
| 33.544554 | 75 | 0.682113 | golden1232004 |
c8527afc64c8e8b9649e7a0cc4b36e40fac52203 | 3,244 | cpp | C++ | test/utils.cpp | chtimi59/isxcpp | fc90c1cf23ee519d28801d3912ba9e94665b5521 | [
"MIT"
] | 2 | 2019-04-30T18:32:43.000Z | 2022-03-04T07:12:01.000Z | test/utils.cpp | chtimi59/isxcpp | fc90c1cf23ee519d28801d3912ba9e94665b5521 | [
"MIT"
] | null | null | null | test/utils.cpp | chtimi59/isxcpp | fc90c1cf23ee519d28801d3912ba9e94665b5521 | [
"MIT"
] | null | null | null | #define INSTANCIATE_UTILS
#include "utils.h"
// System Header
#include <stdio.h>
#include <windows.h>
#include <string>
void initUtils()
{
std::string tmp;
TCHAR szModuleName[MAX_PATH];
GetCurrentDirectory(MAX_PATH, szCurPath); // rootdir/test/
GetModuleFileName(NULL, szModuleName, MAX_PATH); // rootdir/test/bin/text.exe
tmp = io::Dirname(szModuleName); // rootdir/test/bin
strcpy_s(szExePath, MAX_PATH, tmp.c_str()); // rootdir/test/bin
tmp = io::PathCombine(tmp, "tmp"); // rootdir/test/bin/tmp
strcpy_s(szTmpPath, MAX_PATH, tmp.c_str()); // rootdir/test/bin
io::DirectoryDelete(tmp);
CreateDirectory(szTmpPath, NULL);
tmp = io::Dirname(tmp); // rootdir/test/
tmp = io::Dirname(tmp); // rootdir/
tmp = io::PathCombine(tmp, "isx"); // rootdir/isx
tmp = io::PathCombine(tmp, "bin"); // rootdir/isx/bin
strcpy_s(szLibPath, MAX_PATH, tmp.c_str());
}
void DbgOutput(const char* szFormat, ...) {
char szBuff[MAX_PATH];
va_list arg;
va_start(arg, szFormat);
_vsnprintf_s(szBuff, sizeof(szBuff), szFormat, arg);
va_end(arg);
strcat_s(szBuff, MAX_PATH, "\n");
OutputDebugString("isx-test > ");
OutputDebugString(szBuff);
printf_s(szBuff, MAX_PATH);
}
void DbgPopLastError() {
char buff[MAX_PATH];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buff, (sizeof(buff) / sizeof(wchar_t)), NULL);
MessageBox(NULL, buff, "error", MB_OK);
}
bool DirectoryExists(const std::string& path) {
DWORD ftyp = GetFileAttributes(path.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
bool DirectoryDelete(const std::string& path) {
if (path.empty()) return TRUE;
if (!DirectoryExists(path)) return TRUE;
HANDLE hFind;
WIN32_FIND_DATA FindFileData;
std::string search = path + "\\*";
hFind = FindFirstFile(search.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) return FALSE;
while (TRUE)
{
/* end */
if (!FindNextFile(hFind, &FindFileData)) {
if (GetLastError() == ERROR_NO_MORE_FILES) break;
FindClose(hFind);
return FALSE;
}
/* skip '.' and '..' */
std::string item(FindFileData.cFileName);
if (item == "." || item == "..") continue;
std::string filename = path + "\\" + item;
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
/* item is a directory (recursive call) */
if (!DirectoryDelete(filename)) {
FindClose(hFind);
return FALSE;
}
}
else
{
/* item is a file, delete it */
if (!DeleteFile(filename.c_str())) {
FindClose(hFind);
return FALSE;
}
}
}
FindClose(hFind);
/* actual folder deletion */
if (!RemoveDirectory(path.c_str())) return FALSE;
return TRUE;
} | 30.603774 | 81 | 0.609433 | chtimi59 |
c856368ac2aac2b1d1cf133cdd0865a989fe64bb | 5,126 | cpp | C++ | inference-engine/src/inference_engine/builders/ie_lstm_sequence_layer.cpp | shinh/dldt | 693ab4e79a428e0801f17f4511b129a3fa8f4a62 | [
"Apache-2.0"
] | 1 | 2021-02-20T21:48:36.000Z | 2021-02-20T21:48:36.000Z | inference-engine/src/inference_engine/builders/ie_lstm_sequence_layer.cpp | erinpark33/dldt | edd86d090592f7779f4dbb2681546e1f4e81284f | [
"Apache-2.0"
] | null | null | null | inference-engine/src/inference_engine/builders/ie_lstm_sequence_layer.cpp | erinpark33/dldt | edd86d090592f7779f4dbb2681546e1f4e81284f | [
"Apache-2.0"
] | 1 | 2018-12-14T07:52:51.000Z | 2018-12-14T07:52:51.000Z | // Copyright (C) 2018-2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <builders/ie_lstm_sequence_layer.hpp>
#include <ie_cnn_layer_builder.h>
#include <vector>
#include <string>
using namespace InferenceEngine;
Builder::LSTMSequenceLayer::LSTMSequenceLayer(const std::string& name): LayerDecorator("LSTMSequence", name) {
getLayer()->getOutputPorts().resize(3);
getLayer()->getInputPorts().resize(7);
getLayer()->getInputPorts()[1].setParameter("type", "weights");
getLayer()->getInputPorts()[2].setParameter("type", "biases");
getLayer()->getInputPorts()[3].setParameter("type", "optional");
getLayer()->getInputPorts()[6].setParameter("type", "weights");
}
Builder::LSTMSequenceLayer::LSTMSequenceLayer(const Layer::Ptr& layer): LayerDecorator(layer) {
checkType("LSTMSequence");
}
Builder::LSTMSequenceLayer::LSTMSequenceLayer(const Layer::CPtr& layer): LayerDecorator(layer) {
checkType("LSTMSequence");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setName(const std::string& name) {
getLayer()->setName(name);
return *this;
}
const std::vector<Port>& Builder::LSTMSequenceLayer::getInputPorts() const {
return getLayer()->getInputPorts();
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setInputPorts(const std::vector<Port>& ports) {
getLayer()->getInputPorts() = ports;
return *this;
}
const std::vector<Port>& Builder::LSTMSequenceLayer::getOutputPorts() const {
return getLayer()->getOutputPorts();
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setOutputPorts(const std::vector<Port>& ports) {
getLayer()->getOutputPorts() = ports;
return *this;
}
int Builder::LSTMSequenceLayer::getHiddenSize() const {
return getLayer()->getParameters().at("hidden_size");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setHiddenSize(int size) {
getLayer()->getParameters()["hidden_size"] = size;
return *this;
}
bool Builder::LSTMSequenceLayer::getSequenceDim() const {
return getLayer()->getParameters().at("sequence_dim");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setSqquenceDim(bool flag) {
getLayer()->getParameters()["sequence_dim"] = flag;
return *this;
}
const std::vector<std::string>& Builder::LSTMSequenceLayer::getActivations() const {
return getLayer()->getParameters().at("activations");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setActivations(const std::vector<std::string>& activations) {
getLayer()->getParameters()["activations"] = activations;
return *this;
}
const std::vector<float>& Builder::LSTMSequenceLayer::getActivationsAlpha() const {
return getLayer()->getParameters().at("activations_alpha");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setActivationsAlpha(const std::vector<float>& activations) {
getLayer()->getParameters()["activations_alpha"] = activations;
return *this;
}
const std::vector<float>& Builder::LSTMSequenceLayer::getActivationsBeta() const {
return getLayer()->getParameters().at("activations_beta");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setActivationsBeta(const std::vector<float>& activations) {
getLayer()->getParameters()["activations_beta"] = activations;
return *this;
}
float Builder::LSTMSequenceLayer::getClip() const {
return getLayer()->getParameters().at("clip");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setClip(float clip) {
getLayer()->getParameters()["clip"] = clip;
return *this;
}
bool Builder::LSTMSequenceLayer::getInputForget() const {
return getLayer()->getParameters().at("input_forget");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setInputForget(bool flag) {
getLayer()->getParameters()["input_forget"] = flag;
return *this;
}
const std::string& Builder::LSTMSequenceLayer::getDirection() const {
return getLayer()->getParameters().at("direction");
}
Builder::LSTMSequenceLayer& Builder::LSTMSequenceLayer::setDirection(const std::string& direction) {
getLayer()->getParameters()["direction"] = direction;
return *this;
}
REG_CONVERTER_FOR(LSTMSequence, [](const CNNLayerPtr& cnnLayer, Builder::Layer& layer) {
layer.getParameters()["hidden_size"] = cnnLayer->GetParamAsInt("hidden_size");
layer.getParameters()["sequence_dim"] = cnnLayer->GetParamsAsBool("sequence_dim", true);
std::vector<std::string> activations;
std::istringstream stream(cnnLayer->GetParamAsString("activations"));
std::string str;
while (getline(stream, str, ',')) {
activations.push_back(str);
}
layer.getParameters()["activations"] = activations;
layer.getParameters()["activations_alpha"] = cnnLayer->GetParamAsFloats("activations_alpha");
layer.getParameters()["activations_beta"] = cnnLayer->GetParamAsFloats("activations_beta");
layer.getParameters()["clip"] = cnnLayer->GetParamAsFloat("clip");
layer.getParameters()["input_forget"] = cnnLayer->GetParamsAsBool("input_forget", true);
layer.getParameters()["direction"] = cnnLayer->GetParamAsString("direction", "");
});
| 40.046875 | 117 | 0.729809 | shinh |
c856bac5a77f7b09329edd58f1f713976aeac8dc | 7,714 | cpp | C++ | alvr/vulkan-layer/layer/private_data.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 1,562 | 2020-12-01T15:02:21.000Z | 2022-03-31T13:37:51.000Z | alvr/vulkan-layer/layer/private_data.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 562 | 2020-12-01T20:10:13.000Z | 2022-03-31T22:57:13.000Z | alvr/vulkan-layer/layer/private_data.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 184 | 2020-12-01T15:02:24.000Z | 2022-03-31T06:18:18.000Z | /*
* Copyright (c) 2018-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "private_data.hpp"
#include "wsi/wsi_factory.hpp"
#include <unordered_map>
namespace layer {
static std::mutex g_data_lock;
static std::unordered_map<void *, std::unique_ptr<instance_private_data>> g_instance_data;
static std::unordered_map<void *, std::unique_ptr<device_private_data>> g_device_data;
template <typename object_type, typename get_proc_type>
static PFN_vkVoidFunction get_proc_helper(object_type obj, get_proc_type get_proc,
const char *proc_name, bool required, bool &ok) {
PFN_vkVoidFunction ret = get_proc(obj, proc_name);
if (nullptr == ret && required) {
ok = false;
}
return ret;
}
VkResult instance_dispatch_table::populate(VkInstance instance,
PFN_vkGetInstanceProcAddr get_proc) {
bool ok = true;
#define REQUIRED(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(instance, get_proc, "vk" #x, true, ok));
#define OPTIONAL(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(instance, get_proc, "vk" #x, false, ok));
INSTANCE_ENTRYPOINTS_LIST(REQUIRED, OPTIONAL);
#undef REQUIRED
#undef OPTIONAL
return ok ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED;
}
VkResult device_dispatch_table::populate(VkDevice device, PFN_vkGetDeviceProcAddr get_proc) {
bool ok = true;
#define REQUIRED(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(device, get_proc, "vk" #x, true, ok));
#define OPTIONAL(x) \
x = reinterpret_cast<PFN_vk##x>(get_proc_helper(device, get_proc, "vk" #x, false, ok));
DEVICE_ENTRYPOINTS_LIST(REQUIRED, OPTIONAL);
#undef REQUIRED
#undef OPTIONAL
return ok ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED;
}
instance_private_data::instance_private_data(const instance_dispatch_table &table,
PFN_vkSetInstanceLoaderData set_loader_data,
util::wsi_platform_set enabled_layer_platforms)
: disp(table), SetInstanceLoaderData(set_loader_data),
enabled_layer_platforms(enabled_layer_platforms) {}
template <typename dispatchable_type>
static inline void *get_key(dispatchable_type dispatchable_object) {
return *reinterpret_cast<void **>(dispatchable_object);
}
void instance_private_data::set(VkInstance inst, std::unique_ptr<instance_private_data> inst_data) {
scoped_mutex lock(g_data_lock);
g_instance_data[get_key(inst)] = std::move(inst_data);
}
template <typename dispatchable_type>
static instance_private_data &get_instance_private_data(dispatchable_type dispatchable_object) {
scoped_mutex lock(g_data_lock);
return *g_instance_data[get_key(dispatchable_object)];
}
instance_private_data &instance_private_data::get(VkInstance instance) {
return get_instance_private_data(instance);
}
instance_private_data &instance_private_data::get(VkPhysicalDevice phys_dev) {
return get_instance_private_data(phys_dev);
}
static VkIcdWsiPlatform get_platform_of_surface(VkSurfaceKHR surface) {
VkIcdSurfaceBase *surface_base = reinterpret_cast<VkIcdSurfaceBase *>(surface);
return surface_base->platform;
}
bool instance_private_data::does_layer_support_surface(VkSurfaceKHR surface) {
return enabled_layer_platforms.contains(get_platform_of_surface(surface));
}
bool instance_private_data::do_icds_support_surface(VkPhysicalDevice, VkSurfaceKHR) {
/* For now assume ICDs do not support VK_KHR_surface. This means that the layer will handle all
* the surfaces it can handle (even if the ICDs can handle the surface) and only call down for
* surfaces it cannot handle. In the future we may allow system integrators to configure which
* ICDs have precedence handling which platforms.
*/
return false;
}
bool instance_private_data::should_layer_handle_surface(VkSurfaceKHR surface) {
return surfaces.find(surface) != surfaces.end();
}
void instance_private_data::destroy(VkInstance inst) {
scoped_mutex lock(g_data_lock);
g_instance_data.erase(get_key(inst));
}
void instance_private_data::add_surface(VkSurfaceKHR surface) {
scoped_mutex lock(g_data_lock);
surfaces.insert(surface);
}
device_private_data::device_private_data(instance_private_data &inst_data,
VkPhysicalDevice phys_dev, VkDevice dev,
const device_dispatch_table &table,
PFN_vkSetDeviceLoaderData set_loader_data)
: disp{table}, instance_data{inst_data}, SetDeviceLoaderData{set_loader_data},
physical_device{phys_dev}, device{dev} {}
void device_private_data::set(VkDevice dev, std::unique_ptr<device_private_data> dev_data) {
scoped_mutex lock(g_data_lock);
g_device_data[get_key(dev)] = std::move(dev_data);
}
template <typename dispatchable_type>
static device_private_data &get_device_private_data(dispatchable_type dispatchable_object) {
scoped_mutex lock(g_data_lock);
return *g_device_data[get_key(dispatchable_object)];
}
device_private_data &device_private_data::get(VkDevice device) {
return get_device_private_data(device);
}
device_private_data &device_private_data::get(VkQueue queue) {
return get_device_private_data(queue);
}
void device_private_data::add_layer_swapchain(VkSwapchainKHR swapchain) {
scoped_mutex lock(swapchains_lock);
swapchains.insert(swapchain);
}
bool device_private_data::layer_owns_all_swapchains(const VkSwapchainKHR *swapchain,
uint32_t swapchain_count) const {
scoped_mutex lock(swapchains_lock);
for (uint32_t i = 0; i < swapchain_count; i++) {
if (swapchains.find(swapchain[i]) == swapchains.end()) {
return false;
}
}
return true;
}
bool device_private_data::should_layer_create_swapchain(VkSurfaceKHR vk_surface) {
return instance_data.should_layer_handle_surface(vk_surface);
}
bool device_private_data::can_icds_create_swapchain(VkSurfaceKHR vk_surface) {
return disp.CreateSwapchainKHR != nullptr;
}
void device_private_data::destroy(VkDevice dev) {
scoped_mutex lock(g_data_lock);
g_device_data.erase(get_key(dev));
}
} /* namespace layer */
| 40.814815 | 100 | 0.709619 | Firepal |
c8572030f0afe37df2721cbb37af091608573616 | 8,204 | cc | C++ | ns-allinone-3.27/ns-3.27/src/internet/test/tcp-zero-window-test.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 93 | 2019-04-21T08:22:26.000Z | 2022-03-30T04:26:29.000Z | ns-allinone-3.27/ns-3.27/src/internet/test/tcp-zero-window-test.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 12 | 2019-04-19T16:39:58.000Z | 2021-06-22T13:18:32.000Z | ns-allinone-3.27/ns-3.27/src/internet/test/tcp-zero-window-test.cc | zack-braun/4607_NS | 43c8fb772e5552fb44bd7cd34173e73e3fb66537 | [
"MIT"
] | 21 | 2019-05-27T19:36:12.000Z | 2021-07-26T02:37:41.000Z | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2015 Natale Patriciello <natale.patriciello@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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
*
*/
#include "tcp-general-test.h"
#include "tcp-error-model.h"
#include "ns3/node.h"
#include "ns3/log.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("TcpZeroWindowTestSuite");
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief Testing the congestion avoidance increment on TCP ZeroWindow
*/
class TcpZeroWindowTest : public TcpGeneralTest
{
public:
/**
* \brief Constructor.
* \param desc Test description.
*/
TcpZeroWindowTest (const std::string &desc);
protected:
//virtual void ReceivePacket (Ptr<Socket> socket);
virtual Ptr<TcpSocketMsgBase> CreateReceiverSocket (Ptr<Node> node);
virtual void Tx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who);
virtual void Rx (const Ptr<const Packet> p, const TcpHeader&h, SocketWho who);
virtual void ProcessedAck (const Ptr<const TcpSocketState> tcb,
const TcpHeader& h, SocketWho who);
void NormalClose (SocketWho who);
void FinalChecks ();
virtual void ConfigureEnvironment ();
virtual void ConfigureProperties ();
/**
* \brief Increase the receiver buffer size.
*/
void IncreaseBufSize ();
protected:
EventId m_receivePktEvent; //!< Receive packet event.
bool m_zeroWindowProbe; //!< ZeroWindow probe.
bool m_windowUpdated; //!< Window updated.
bool m_senderFinished; //!< Send finished.
bool m_receiverFinished; //!< Receiver finished.
};
TcpZeroWindowTest::TcpZeroWindowTest (const std::string &desc)
: TcpGeneralTest (desc),
m_zeroWindowProbe (false),
m_windowUpdated (false),
m_senderFinished (false),
m_receiverFinished (false)
{
}
void
TcpZeroWindowTest::ConfigureEnvironment ()
{
TcpGeneralTest::ConfigureEnvironment ();
SetAppPktCount (20);
SetMTU (500);
SetTransmitStart (Seconds (2.0));
SetPropagationDelay (MilliSeconds (50));
}
void
TcpZeroWindowTest::ConfigureProperties ()
{
TcpGeneralTest::ConfigureProperties ();
SetInitialCwnd (SENDER, 10);
}
void
TcpZeroWindowTest::IncreaseBufSize ()
{
SetRcvBufSize (RECEIVER, 2500);
}
Ptr<TcpSocketMsgBase>
TcpZeroWindowTest::CreateReceiverSocket (Ptr<Node> node)
{
Ptr<TcpSocketMsgBase> socket = TcpGeneralTest::CreateReceiverSocket (node);
socket->SetAttribute ("RcvBufSize", UintegerValue (0));
Simulator::Schedule (Seconds (10.0),
&TcpZeroWindowTest::IncreaseBufSize, this);
return socket;
}
void
TcpZeroWindowTest::Tx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who)
{
if (who == SENDER)
{
NS_LOG_INFO ("\tSENDER TX " << h << " size " << p->GetSize ());
if (Simulator::Now ().GetSeconds () <= 6.0)
{
NS_TEST_ASSERT_MSG_EQ (p->GetSize (), 0,
"Data packet sent anyway");
}
else if (Simulator::Now ().GetSeconds () > 6.0
&& Simulator::Now ().GetSeconds () <= 7.0)
{
NS_TEST_ASSERT_MSG_EQ (m_zeroWindowProbe, false, "Sent another probe");
if (!m_zeroWindowProbe)
{
NS_TEST_ASSERT_MSG_EQ (p->GetSize (), 1,
"Data packet sent instead of window probe");
NS_TEST_ASSERT_MSG_EQ (h.GetSequenceNumber (), SequenceNumber32 (1),
"Data packet sent instead of window probe");
m_zeroWindowProbe = true;
}
}
else if (Simulator::Now ().GetSeconds () > 7.0
&& Simulator::Now ().GetSeconds () < 10.0)
{
NS_FATAL_ERROR ("No packets should be sent before the window update");
}
}
else if (who == RECEIVER)
{
NS_LOG_INFO ("\tRECEIVER TX " << h << " size " << p->GetSize ());
if (h.GetFlags () & TcpHeader::SYN)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 0,
"RECEIVER window size is not 0 in the SYN-ACK");
}
if (Simulator::Now ().GetSeconds () > 6.0
&& Simulator::Now ().GetSeconds () <= 7.0)
{
NS_TEST_ASSERT_MSG_EQ (h.GetSequenceNumber (), SequenceNumber32 (1),
"Data packet sent instead of window probe");
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 0,
"No zero window advertised by RECEIVER");
}
else if (Simulator::Now ().GetSeconds () > 7.0
&& Simulator::Now ().GetSeconds () < 10.0)
{
NS_FATAL_ERROR ("No packets should be sent before the window update");
}
else if (Simulator::Now ().GetSeconds () >= 10.0)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 2500,
"Receiver window not updated");
}
}
NS_TEST_ASSERT_MSG_EQ (GetCongStateFrom (GetTcb (SENDER)), TcpSocketState::CA_OPEN,
"Sender State is not OPEN");
NS_TEST_ASSERT_MSG_EQ (GetCongStateFrom (GetTcb (RECEIVER)), TcpSocketState::CA_OPEN,
"Receiver State is not OPEN");
}
void
TcpZeroWindowTest::Rx (const Ptr<const Packet> p, const TcpHeader &h, SocketWho who)
{
if (who == SENDER)
{
NS_LOG_INFO ("\tSENDER RX " << h << " size " << p->GetSize ());
if (h.GetFlags () & TcpHeader::SYN)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 0,
"RECEIVER window size is not 0 in the SYN-ACK");
}
if (Simulator::Now ().GetSeconds () >= 10.0)
{
NS_TEST_ASSERT_MSG_EQ (h.GetWindowSize (), 2500,
"Receiver window not updated");
m_windowUpdated = true;
}
}
else if (who == RECEIVER)
{
NS_LOG_INFO ("\tRECEIVER RX " << h << " size " << p->GetSize ());
}
}
void
TcpZeroWindowTest::NormalClose (SocketWho who)
{
if (who == SENDER)
{
m_senderFinished = true;
}
else if (who == RECEIVER)
{
m_receiverFinished = true;
}
}
void
TcpZeroWindowTest::FinalChecks ()
{
NS_TEST_ASSERT_MSG_EQ (m_zeroWindowProbe, true,
"Zero window probe not sent");
NS_TEST_ASSERT_MSG_EQ (m_windowUpdated, true,
"Window has not updated during the connection");
NS_TEST_ASSERT_MSG_EQ (m_senderFinished, true,
"Connection not closed successfully (SENDER)");
NS_TEST_ASSERT_MSG_EQ (m_receiverFinished, true,
"Connection not closed successfully (RECEIVER)");
}
void
TcpZeroWindowTest::ProcessedAck (const Ptr<const TcpSocketState> tcb,
const TcpHeader& h, SocketWho who)
{
if (who == SENDER)
{
if (h.GetFlags () & TcpHeader::SYN)
{
EventId persistentEvent = GetPersistentEvent (SENDER);
NS_TEST_ASSERT_MSG_EQ (persistentEvent.IsRunning (), true,
"Persistent event not started");
}
}
else if (who == RECEIVER)
{
}
}
/**
* \ingroup internet-test
* \ingroup tests
*
* \brief TCP ZeroWindow TestSuite
*/
class TcpZeroWindowTestSuite : public TestSuite
{
public:
TcpZeroWindowTestSuite () : TestSuite ("tcp-zero-window-test", UNIT)
{
AddTestCase (new TcpZeroWindowTest ("zero window test"),
TestCase::QUICK);
}
};
static TcpZeroWindowTestSuite g_tcpZeroWindowTestSuite; //!< Static variable for test initialization
| 29.941606 | 100 | 0.61275 | zack-braun |
c858d5b84f4a9b98a6d232225b1b98321a9060cf | 1,040 | cpp | C++ | graph-source-code/402-E/9925166.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/402-E/9925166.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/402-E/9925166.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <iostream>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#define max_nodes_size 100005
#define max_size 100005
#define ll long long int
#define mod 1000000007
#define sl(n) scanf("%lld", &n)
using namespace std;
ll grid[2005][2005];
ll vis[2005];
ll dfs(ll node, ll flag, ll n)
{
vis[node] = 1;
ll temp = 1;
for(ll i=0; i<n; i++)
{
if(i!=node && vis[i]==0)
{
if(flag)
{
if(grid[i][node]>0)
temp += dfs(i, flag, n);
}
else
{
if(grid[node][i]>0)
temp += dfs(i, flag, n);
}
}
}
//cout<<node<<" "<<temp<<endl;
return temp;
}
int main()
{
ll n, a;
cin>>n;
ll flag = 0;
for(ll i=0; i<n; i++)
{
for(ll j=0; j<n; j++)
{
sl(grid[i][j]);
}
}
for(ll i=1; i<=n; i++)
vis[i] = 0;
if(dfs(0, 0, n)==n)
flag++;
for(ll i=1; i<=n; i++)
vis[i] = 0;
if(dfs(0, 1, n)==n)
flag++;
if(flag==2)
cout<<"YES";
else
cout<<"NO";
return 0;
} | 12.682927 | 32 | 0.531731 | AmrARaouf |
c85a4fb57883f445ebda15b53c7daab3ee9b175a | 1,678 | cpp | C++ | searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | searchsummary/src/vespa/searchsummary/docsummary/textextractordfw.cpp | alexeyche/vespa | 7585981b32937d2b13da1a8f94b42c8a0833a4c2 | [
"Apache-2.0"
] | null | null | null | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "textextractordfw.h"
#include "tokenizer.h"
#include "docsumstate.h"
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.docsummary.textextractordfw");
namespace search::docsummary {
TextExtractorDFW::TextExtractorDFW() :
_inputFieldEnum(-1)
{
}
bool
TextExtractorDFW::init(const vespalib::string & fieldName, const vespalib::string & inputField, const ResultConfig & config)
{
_inputFieldEnum = config.GetFieldNameEnum().Lookup(inputField.c_str());
if (_inputFieldEnum == -1) {
LOG(warning, "Did not find input field '%s' as part of the docsum fields when initializing writer for field '%s'",
inputField.c_str(), fieldName.c_str());
return false;
}
return true;
}
void
TextExtractorDFW::insertField(uint32_t, GeneralResult *gres, GetDocsumsState *, ResType,
vespalib::slime::Inserter &target)
{
vespalib::string extracted;
ResEntry * entry = gres->GetEntryFromEnumValue(_inputFieldEnum);
if (entry != nullptr) {
const char * buf = nullptr;
uint32_t buflen = 0;
entry->_resolve_field(&buf, &buflen);
// extract the text
Tokenizer tokenizer(buf, buflen);
while (tokenizer.hasMoreTokens()) {
Tokenizer::Token token = tokenizer.getNextToken();
extracted.append(token.getText());
}
} else {
LOG(warning, "Did not find input entry using field enum %d. Write an empty field", _inputFieldEnum);
}
target.insertString(vespalib::Memory(extracted.c_str(), extracted.size()));
}
}
| 32.269231 | 124 | 0.669845 | alexeyche |
c85bb28c08356971479658838a517e22bf5cbf98 | 31,037 | cpp | C++ | examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | examples/tudat/satellite_propagation/shapeBasedTrajectoryDesign.cpp | kimonito98/tudat | c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <Eigen/Core>
#include <tudat/basics/testMacros.h>
#include <tudat/simulation/simulation.h>
#include <tudat/io/basicInputOutput.h>
#include <tudat/io/applicationOutput.h>
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/hodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/createBaseFunctionHodographicShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/baseFunctionsSphericalShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/compositeFunctionSphericalShaping.h"
#include "tudat/astro/LowThrustTrajectories/ShapeBasedMethods/sphericalShaping.h"
#include "tudat/astro/ephemerides/approximatePlanetPositions.h"
#include "tudat/simulation/simulation.h"
#include "tudat/interface/spice/spiceEphemeris.h"
using namespace tudat;
using namespace tudat::input_output;
using namespace tudat::simulation_setup;
using namespace tudat::shape_based_methods;
SystemOfBodies getBetBodyMap( )
{
// Create central, departure and arrival bodies.
std::vector< std::string > bodiesToCreate;
bodiesToCreate.push_back( "Sun" );
bodiesToCreate.push_back( "Earth" );
bodiesToCreate.push_back( "Mars" );
bodiesToCreate.push_back( "Jupiter" );
std::map< std::string, std::shared_ptr< simulation_setup::BodySettings > > bodySettings =
simulation_setup::getDefaultBodySettings( bodiesToCreate );
std::string frameOrigin = "SSB";
std::string frameOrientation = "ECLIPJ2000";
// Define central body ephemeris settings.
bodySettings[ "Sun" ]->ephemerisSettings = std::make_shared< simulation_setup::ConstantEphemerisSettings >(
( Eigen::Vector6d( ) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );
bodySettings[ "Sun" ]->ephemerisSettings->resetFrameOrientation( frameOrientation );
bodySettings[ "Sun" ]->rotationModelSettings->resetOriginalFrame( frameOrientation );
// Create system of bodies.
simulation_setup::SystemOfBodies bodies = createBodies( bodySettings );
bodies[ "Borzi" ] = std::make_shared< simulation_setup::Body >( );
bodies.at( "Borzi" )->setSuppressDependentOrientationCalculatorWarning( true );
bodies.at( "Borzi" )->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(
std::shared_ptr< interpolators::OneDimensionalInterpolator
< double, Eigen::Vector6d > >( ), frameOrigin, frameOrientation ) );
// Create radiation pressure settings
double referenceAreaRadiation = 4.0;
double radiationPressureCoefficient = 1.2;
std::vector< std::string > occultingBodies;
occultingBodies.push_back( "Earth" );
std::shared_ptr< RadiationPressureInterfaceSettings > asterixRadiationPressureSettings =
std::make_shared< CannonBallRadiationPressureInterfaceSettings >(
"Sun", referenceAreaRadiation, radiationPressureCoefficient, occultingBodies );
// Create and set radiation pressure settings
bodies[ "Borzi" ]->setRadiationPressureInterface(
"Sun", createRadiationPressureInterface(
asterixRadiationPressureSettings, "Borzi", bodies ) );
setGlobalFrameBodyEphemerides( bodies, frameOrigin, frameOrientation );
return bodies;
}
int main( )
{
std::string outputSubFolder = "ShapeBasedTrajectoriesExample/";
spice_interface::loadStandardSpiceKernels( );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// DEFINE TRAJECTORY GLOBAL PARAMETERS ////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int numberOfRevolutions = 1;
double julianDateAtDeparture = 8174.5 * physical_constants::JULIAN_DAY;
double timeOfFlight = 580.0 * physical_constants::JULIAN_DAY;
double vehicleInitialMass = 2000.0;
double specificImpulse = 3000.0;
std::function< double( const double ) > specificImpulseFunction = [ = ]( const double ){ return specificImpulse; };
// Retrieve cartesian state at departure and arrival.
ephemerides::EphemerisPointer pointerToDepartureBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions>(
ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter );
ephemerides::EphemerisPointer pointerToArrivalBodyEphemeris = std::make_shared< ephemerides::ApproximatePlanetPositions >(
ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mars );
Eigen::Vector6d cartesianStateAtDeparture = pointerToDepartureBodyEphemeris->getCartesianState( julianDateAtDeparture );
Eigen::Vector6d cartesianStateAtArrival = pointerToArrivalBodyEphemeris->getCartesianState( julianDateAtDeparture + timeOfFlight );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DEFINE HODOGRAPHIC SHAPING LEG ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
double frequency = 2.0 * mathematical_constants::PI / timeOfFlight;
double scaleFactor = 1.0 / timeOfFlight;
// Create base function settings for the components of the radial velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstRadialVelocityBaseFunctionSettings =
std::make_shared< BaseFunctionHodographicShapingSettings >( );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondRadialVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdRadialVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );
// Create components of the radial velocity composite function.
std::vector< std::shared_ptr< BaseFunctionHodographicShaping > > radialVelocityFunctionComponents;
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( constant, firstRadialVelocityBaseFunctionSettings ) );
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, secondRadialVelocityBaseFunctionSettings ) );
radialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, thirdRadialVelocityBaseFunctionSettings ) );
// Create base function settings for the components of the normal velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstNormalVelocityBaseFunctionSettings =
std::make_shared< BaseFunctionHodographicShapingSettings >( );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondNormalVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 1.0, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdNormalVelocityBaseFunctionSettings =
std::make_shared< PowerFunctionHodographicShapingSettings >( 2.0, scaleFactor );
// Create components of the normal velocity composite function.
std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > normalVelocityFunctionComponents;
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( constant, firstNormalVelocityBaseFunctionSettings ) );
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, secondNormalVelocityBaseFunctionSettings ) );
normalVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPower, thirdNormalVelocityBaseFunctionSettings ) );
// Create base function settings for the components of the axial velocity composite function.
std::shared_ptr< BaseFunctionHodographicShapingSettings > firstAxialVelocityBaseFunctionSettings =
std::make_shared< TrigonometricFunctionHodographicShapingSettings >( ( numberOfRevolutions + 0.5 ) * frequency );
std::shared_ptr< BaseFunctionHodographicShapingSettings > secondAxialVelocityBaseFunctionSettings =
std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >
( 3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );
std::shared_ptr< BaseFunctionHodographicShapingSettings > thirdAxialVelocityBaseFunctionSettings =
std::make_shared< PowerTimesTrigonometricFunctionHodographicShapingSettings >(
3.0, ( numberOfRevolutions + 0.5 ) * frequency, scaleFactor );
// Create components for the axial velocity composite function.
std::vector< std::shared_ptr< shape_based_methods::BaseFunctionHodographicShaping > > axialVelocityFunctionComponents;
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( cosine, firstAxialVelocityBaseFunctionSettings ) );
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPowerCosine, secondAxialVelocityBaseFunctionSettings ) );
axialVelocityFunctionComponents.push_back(
createBaseFunctionHodographicShaping( scaledPowerSine, thirdAxialVelocityBaseFunctionSettings ) );
// Initialize free coefficients vector for radial velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsRadialVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Initialize free coefficients vector for normal velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsNormalVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Initialize free coefficients vector for axial velocity function (empty here, only 3 base functions).
Eigen::VectorXd freeCoefficientsAxialVelocityFunction = Eigen::VectorXd::Zero( 0 );
// Create hodographic-shaping object with defined velocity functions and boundary conditions.
shape_based_methods::HodographicShaping hodographicShaping(
cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,
spice_interface::getBodyGravitationalParameter( "Sun" ), 1,
radialVelocityFunctionComponents, normalVelocityFunctionComponents, axialVelocityFunctionComponents,
freeCoefficientsRadialVelocityFunction, freeCoefficientsNormalVelocityFunction, freeCoefficientsAxialVelocityFunction,
vehicleInitialMass );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// DEFINE SPHERICAL SHAPING LEG ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define root finder settings (used to update the updated value of the free coefficient, so that it matches the required time of flight).
std::shared_ptr< root_finders::RootFinderSettings > rootFinderSettings =
std::make_shared< root_finders::RootFinderSettings >( root_finders::bisection_root_finder, 1.0e-6, 30 );
// Compute shaped trajectory.
shape_based_methods::SphericalShaping sphericalShaping = shape_based_methods::SphericalShaping(
cartesianStateAtDeparture, cartesianStateAtArrival, timeOfFlight,
spice_interface::getBodyGravitationalParameter( "Sun" ),
numberOfRevolutions, 0.000703,
rootFinderSettings, 1.0e-6, 1.0e-1, vehicleInitialMass );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// CREATE ENVIRONMENT /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set vehicle mass.
SystemOfBodies bodies = getBetBodyMap( );
bodies[ "Borzi" ]->setConstantBodyMass( vehicleInitialMass );
// Define body to propagate and central body.
std::vector< std::string > bodiesToPropagate;
std::vector< std::string > centralBodies;
bodiesToPropagate.push_back( "Borzi" );
centralBodies.push_back( "Sun" );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// DEFINE PROPAGATION SETTINGS /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define integrator settings.
double stepSize = timeOfFlight / static_cast< double >( 8000.0 );
std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =
std::make_shared< numerical_integrators::IntegratorSettings< double > > ( numerical_integrators::rungeKutta4, 0.0, stepSize );
// Define list of dependent variables to save.
std::vector< std::shared_ptr< propagators::SingleDependentVariableSaveSettings > > dependentVariablesList;
// Create object with list of dependent variables
std::shared_ptr< propagators::DependentVariableSaveSettings > dependentVariablesToSave =
std::make_shared< propagators::DependentVariableSaveSettings >( dependentVariablesList, false );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////// NUMERICALLY PROPAGATE THE SIMPLIFIED PROBLEM /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::map< double, Eigen::VectorXd > hodographicShapingPropagationUnperturbedCase;
std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResults;
std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistory;
// Create propagator settings for hodographic shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
hodographicShapingPropagatorSettings = hodographicShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
hodographicShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, hodographicShapingPropagatorSettings, hodographicShapingPropagationUnperturbedCase,
hodographicShapingAnalyticalResults, hodographicShapingDependentVariablesHistory );
std::map< double, Eigen::VectorXd > sphericalShapingPropagationUnperturbedCase;
std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResults;
std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistory;
// Create propagator settings for spherical shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
sphericalShapingPropagatorSettings = sphericalShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
basic_astrodynamics::AccelerationMap( ), integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
sphericalShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, sphericalShapingPropagatorSettings, sphericalShapingPropagationUnperturbedCase,
sphericalShapingAnalyticalResults, sphericalShapingDependentVariablesHistory );
input_output::writeDataMapToTextFile( hodographicShapingAnalyticalResults,
"hodographicShapingAnalyticalResults.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingAnalyticalResults,
"sphericalShapingAnalyticalResults.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingPropagationUnperturbedCase,
"hodographicShapingPropagationUnperturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingPropagationUnperturbedCase,
"sphericalShapingPropagationUnperturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// RETRIEVE TRAJECTORY, MASS, THRUST AND THRUST ACCELERATION PROFILES //////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hodographic shaping
std::vector< double > epochsVectorHodographicShaping;
for ( std::map< double, Eigen::Vector6d >::iterator itr = hodographicShapingAnalyticalResults.begin( ) ;
itr != hodographicShapingAnalyticalResults.end( ) ; itr++ )
{
epochsVectorHodographicShaping.push_back( itr->first );
}
std::map< double, Eigen::VectorXd > hodographicShapingMassProfile;
std::map< double, Eigen::VectorXd > hodographicShapingThrustProfile;
std::map< double, Eigen::VectorXd > hodographicShapingThrustAccelerationProfile;
hodographicShaping.getMassProfile(
epochsVectorHodographicShaping, hodographicShapingMassProfile, specificImpulseFunction, integratorSettings );
hodographicShaping.getThrustForceProfile(
epochsVectorHodographicShaping, hodographicShapingThrustProfile, specificImpulseFunction, integratorSettings );
hodographicShaping.getThrustAccelerationProfile(
epochsVectorHodographicShaping, hodographicShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );
// Spherical shaping
std::vector< double > epochsVectorSphericalShaping;
for ( std::map< double, Eigen::Vector6d >::iterator itr = sphericalShapingAnalyticalResults.begin( ) ;
itr != sphericalShapingAnalyticalResults.end( ) ; itr++ )
{
epochsVectorSphericalShaping.push_back( itr->first );
}
std::map< double, Eigen::VectorXd > sphericalShapingMassProfile;
std::map< double, Eigen::VectorXd > sphericalShapingThrustProfile;
std::map< double, Eigen::VectorXd > sphericalShapingThrustAccelerationProfile;
sphericalShaping.getMassProfile(
epochsVectorSphericalShaping, sphericalShapingMassProfile, specificImpulseFunction, integratorSettings );
sphericalShaping.getThrustForceProfile(
epochsVectorSphericalShaping, sphericalShapingThrustProfile, specificImpulseFunction, integratorSettings );
sphericalShaping.getThrustAccelerationProfile(
epochsVectorSphericalShaping, sphericalShapingThrustAccelerationProfile, specificImpulseFunction, integratorSettings );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// DEFINE PERTURBED DYNAMICAL ENVIRONMENT /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define propagation settings.
std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > accelerationSettingsPerturbedProblem;
accelerationSettingsPerturbedProblem[ "Earth" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Mars" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Jupiter" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::central_gravity ) );
accelerationSettingsPerturbedProblem[ "Sun" ].push_back( std::make_shared< AccelerationSettings >(
basic_astrodynamics::cannon_ball_radiation_pressure ) );
SelectedAccelerationMap accelerationMap;
accelerationMap[ "Borzi" ] = accelerationSettingsPerturbedProblem;
bodiesToPropagate.push_back( "Borzi" );
centralBodies.push_back( "Sun" );
basic_astrodynamics::AccelerationMap perturbingAccelerationsMapPertubedProblem = createAccelerationModelsMap(
bodies, accelerationMap, bodiesToPropagate, centralBodies );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// PROPAGATE THE FULLY PERTURBED PROBLEM /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::map< double, Eigen::VectorXd > hodographicShapingPropagationPerturbedCase;
std::map< double, Eigen::Vector6d > hodographicShapingAnalyticalResultsPerturbedCase;
std::map< double, Eigen::VectorXd > hodographicShapingDependentVariablesHistoryPerturbedCase;
std::map< double, Eigen::VectorXd > sphericalShapingPropagationPerturbedCase;
std::map< double, Eigen::Vector6d > sphericalShapingAnalyticalResultsPerturbedCase;
std::map< double, Eigen::VectorXd > sphericalShapingDependentVariablesHistoryPerturbedCase;
// Create propagator settings for hodographic shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
hodographicShapingPropagatorSettingsPerturbedCase = hodographicShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
hodographicShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, hodographicShapingPropagatorSettingsPerturbedCase, hodographicShapingPropagationPerturbedCase,
hodographicShapingAnalyticalResultsPerturbedCase, hodographicShapingDependentVariablesHistoryPerturbedCase );
// Create propagator settings for spherical shaping.
std::pair< std::shared_ptr< propagators::PropagatorSettings< double > >, std::shared_ptr< propagators::PropagatorSettings< double > > >
sphericalShapingPropagatorSettingsPerturbedCase = sphericalShaping.createLowThrustPropagatorSettings(
bodies, bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), specificImpulseFunction,
perturbingAccelerationsMapPertubedProblem, integratorSettings, dependentVariablesToSave );
// Compute shaped trajectory and propagated trajectory.
sphericalShaping.computeSemiAnalyticalAndFullPropagation(
bodies, integratorSettings, sphericalShapingPropagatorSettingsPerturbedCase, sphericalShapingPropagationPerturbedCase,
sphericalShapingAnalyticalResultsPerturbedCase, sphericalShapingDependentVariablesHistoryPerturbedCase );
input_output::writeDataMapToTextFile( hodographicShapingPropagationPerturbedCase,
"hodographicShapingPropagationPerturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingPropagationPerturbedCase,
"sphericalShapingPropagationPerturbedCase.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingMassProfile,
"hodographicShapingMassProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingThrustProfile,
"hodographicShapingThrustProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( hodographicShapingThrustAccelerationProfile,
"hodographicShapingThrustAccelerationProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingMassProfile,
"sphericalShapingMassProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingThrustProfile,
"sphericalShapingThrustProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
input_output::writeDataMapToTextFile( sphericalShapingThrustAccelerationProfile,
"sphericalShapingThrustAccelerationProfile.dat",
tudat_applications::getOutputPath( ) + outputSubFolder,
"",
std::numeric_limits< double >::digits10,
std::numeric_limits< double >::digits10,
"," );
std::cout << "deltaV hodographic shaping: " << hodographicShaping.computeDeltaV( ) << "\n\n";
std::cout << "deltaV spherical shaping: " << sphericalShaping.computeDeltaV( ) << "\n\n";
// Final statement.
// The exit code EXIT_SUCCESS indicates that the program was successfully executed.
return EXIT_SUCCESS;
}
| 63.470348 | 142 | 0.609949 | kimonito98 |
c85e4ec855416eb93759d2e634f17a74d0db0358 | 9,348 | cpp | C++ | src/vega/dicom/file_meta.cpp | project-eutopia/vega | c7b536c5e949094a908fa8f378729dbffc657f4a | [
"MIT"
] | 18 | 2018-01-23T12:28:13.000Z | 2022-02-13T12:23:21.000Z | src/vega/dicom/file_meta.cpp | project-eutopia/vega | c7b536c5e949094a908fa8f378729dbffc657f4a | [
"MIT"
] | 2 | 2018-11-29T01:51:25.000Z | 2022-03-22T14:14:22.000Z | src/vega/dicom/file_meta.cpp | project-eutopia/vega | c7b536c5e949094a908fa8f378729dbffc657f4a | [
"MIT"
] | 6 | 2019-02-01T09:54:44.000Z | 2022-01-09T22:13:54.000Z | #include "vega/dicom/file_meta.h"
#include "vega/dicom/writer.h"
#include "vega/dicom/data_element.h"
#include "vega/manipulator.h"
#include <cassert>
namespace vega {
namespace dicom {
const Tag FileMeta::FileMetaInformationGroupLength = Tag{0x2, 0x0};
const Tag FileMeta::TransferSyntaxUID = Tag{0x2, 0x10};
FileMeta::FileMeta()
: m_transfer_syntax(TransferSyntax::EXPLICIT_VR_LITTLE_ENDIAN)
{}
FileMeta::FileMeta(const SOPClass& sop_class)
: FileMeta(sop_class, UID::generate())
{}
FileMeta::FileMeta(const SOPClass& sop_class, const UID& media_storage_instance_uid)
: m_data_set(std::make_shared<DataSet>())
{
this->fill_defaults(sop_class, media_storage_instance_uid);
}
FileMeta::FileMeta(Reader& reader)
: m_data_set(std::make_shared<DataSet>())
{
// File meta information is written in little endian
const Endian original_endian = reader.dicom_endian();
reader.set_dicom_endianness(Endian::LITTLE);
const bool original_vr_explicit = reader.vr_explicit();
reader.set_vr_explicit(true);
this->read(reader);
reader.set_dicom_endianness(original_endian);
reader.set_vr_explicit(original_vr_explicit);
}
const TransferSyntax& FileMeta::transfer_syntax() const { return m_transfer_syntax; }
void FileMeta::set_transfer_syntax(const TransferSyntax& other) {
m_transfer_syntax = other;
}
Endian FileMeta::transfer_syntax_endian() const { return m_transfer_syntax.endianness(); }
bool FileMeta::transfer_syntax_vr_explicit() const { return m_transfer_syntax.is_explicit_vr(); }
std::shared_ptr<const DataSet> FileMeta::data_set() const { return std::const_pointer_cast<const DataSet>(m_data_set); }
const SOPClass& FileMeta::sop_class() const { return m_sop_class; }
const UID& FileMeta::media_storage_instance_uid() const { return m_media_storage_instance_uid; }
bool FileMeta::present() const { return bool(m_data_set); }
size_t FileMeta::write(std::shared_ptr<Writer> writer) {
if (!this->present()) return 0;
// File meta information is written in little endian
const Endian original_endian = writer->dicom_endian();
writer->set_dicom_endianness(Endian::LITTLE);
const bool original_vr_explicit = writer->vr_explicit();
writer->set_vr_explicit(true);
uint32_t length_of_file_meta_length_element = 0;
uint32_t file_meta_bytes = 0;
// Write each data element
bool first = true;
std::streampos file_meta_length_pos;
std::streampos end_of_file_meta_pos;
for (auto data_element : *m_data_set) {
if (first) {
first = false;
length_of_file_meta_length_element += writer->write_element(data_element);
assert(data_element->tag() == Tag(0x00020000));
file_meta_length_pos = writer->tell() - std::streampos(sizeof(file_meta_bytes));
assert(data_element->manipulator()->raw_value()->size() == sizeof(file_meta_bytes));
}
else {
file_meta_bytes += writer->write_element(data_element);
}
}
end_of_file_meta_pos = writer->tell();
writer->seek_pos(file_meta_length_pos);
writer->raw_writer().write_from(file_meta_bytes);
writer->seek_pos(end_of_file_meta_pos);
writer->set_dicom_endianness(original_endian);
writer->set_vr_explicit(original_vr_explicit);
return length_of_file_meta_length_element + file_meta_bytes;
}
void FileMeta::read(Reader& reader) {
// Expect first data_element to be File Meta Information Group Length
auto maybe_group_length = reader.read_data_element(m_data_set);
if (maybe_group_length->tag() == FileMetaInformationGroupLength) {
// Has group length
auto group_length = maybe_group_length;
auto manipulator = group_length->get_manipulator<UL_Manipulator>();
std::streampos end_of_file_meta = reader.tell() + (std::streampos)(*manipulator)[0];
m_data_set->add_data_element(group_length);
// Read in rest of file meta elements
while (reader.tell() < end_of_file_meta) {
auto data_element = reader.read_data_element(m_data_set);
if (!data_element) throw InvalidFileMeta("Unexpected error reading file meta");
if (!data_element->tag().is_file_meta()) {
throw InvalidFileMeta("Encountered non file-meta DataElement in file meta header");
}
m_data_set->add_data_element(data_element);
}
assert(reader.tell() == end_of_file_meta);
}
else {
// Group length not present, but we would like to have one anyway for compliance so create
auto actual_group_length = std::make_shared<dicom::DataElement>("FileMetaInformationGroupLength");
auto manipulator = actual_group_length->get_manipulator<UL_Manipulator>();
manipulator->push_back(0);
m_data_set->add_data_element(actual_group_length);
// Previously read in data_element still needs to be added
m_data_set->add_data_element(maybe_group_length);
// Read until no longer getting file meta elements
while (!reader.eof()) {
// Tentatively read in next tag
std::streampos cur_pos = reader.tell();
Tag temp_tag;
reader.raw_reader().read_into(&temp_tag);
reader.seek_pos(cur_pos);
if (!temp_tag.is_file_meta()) {
// Finished reading file meta
break;
}
auto data_element = reader.read_data_element(m_data_set);
if (!data_element) throw InvalidFileMeta("Unexpected error reading file meta");
m_data_set->add_data_element(data_element);
}
}
auto transfer_syntax_uid = m_data_set->data_element(TransferSyntaxUID);
if (!transfer_syntax_uid) {
throw InvalidFileMeta("Need TransferSyntaxUID element");
}
auto sop_class = m_data_set->data_element(SOPClass::TAG);
if (!sop_class) {
throw InvalidFileMeta("Need MediaStorageSOPClassUID element");
}
auto sop_class_manipulator = sop_class->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_sop_class = SOPClass(sop_class_manipulator->uid());
auto sop_instance = m_data_set->data_element("MediaStorageSOPInstanceUID");
if (!sop_instance) {
throw InvalidFileMeta("Need MediaStorageSOPInstanceUID element");
}
auto sop_instance_manipulator = sop_instance->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_media_storage_instance_uid = sop_instance_manipulator->uid();
this->set_transfer_syntax(TransferSyntax{UID{transfer_syntax_uid->str()}});
}
void FileMeta::fill_defaults(const SOPClass& sop_class, const UID& media_storage_instance_uid) {
// File meta group length
{
auto data_element = std::make_shared<dicom::DataElement>("FileMetaInformationGroupLength");
auto manipulator = data_element->get_manipulator<manipulators::UnsignedLongManipulator>();
// Store dummy value of zero here -- only need this value when writing to file
manipulator->push_back(0);
m_data_set->add_data_element(data_element);
}
// File meta information version (0x00, 0x01)
{
auto data_element = std::make_shared<dicom::DataElement>("FileMetaInformationVersion");
auto manipulator = data_element->get_manipulator<manipulators::OtherByteManipulator>();
manipulator->push_back(Byte{.u=0});
manipulator->push_back(Byte{.u=1});
m_data_set->add_data_element(data_element);
}
// SOP class uid
{
auto data_element = std::make_shared<dicom::DataElement>("MediaStorageSOPClassUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_sop_class = sop_class;
manipulator->uid() = m_sop_class.uid();
m_data_set->add_data_element(data_element);
}
// SOP instance uid
{
auto data_element = std::make_shared<dicom::DataElement>("MediaStorageSOPInstanceUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
m_media_storage_instance_uid = media_storage_instance_uid;
manipulator->uid() = m_media_storage_instance_uid;
m_data_set->add_data_element(data_element);
}
// Transfer syntax we default to implicit VR little endian
{
auto data_element = std::make_shared<dicom::DataElement>("TransferSyntaxUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
this->set_transfer_syntax(TransferSyntax::IMPLICIT_VR_LITTLE_ENDIAN);
manipulator->uid() = TransferSyntax::IMPLICIT_VR_LITTLE_ENDIAN.uid();
m_data_set->add_data_element(data_element);
}
// Implementation class UID
{
auto data_element = std::make_shared<dicom::DataElement>("ImplementationClassUID");
auto manipulator = data_element->get_manipulator<manipulators::UniqueIdentifierManipulator>();
manipulator->uid() = UID::IMPLEMENTATION_CLASS_UID;
m_data_set->add_data_element(data_element);
}
}
}
}
| 39.277311 | 124 | 0.692127 | project-eutopia |
c85f6da0b33128c18035b40f04cc9747cc81db0b | 33,753 | cc | C++ | test/syscalls/linux/splice.cc | Exhorder6/gvisor | add8bca5ba53b37096bc653900cb278e11681461 | [
"Apache-2.0"
] | 1 | 2021-05-04T06:49:23.000Z | 2021-05-04T06:49:23.000Z | test/syscalls/linux/splice.cc | Exhorder6/gvisor | add8bca5ba53b37096bc653900cb278e11681461 | [
"Apache-2.0"
] | 3 | 2021-10-12T21:46:14.000Z | 2022-03-31T01:53:21.000Z | test/syscalls/linux/splice.cc | Exhorder6/gvisor | add8bca5ba53b37096bc653900cb278e11681461 | [
"Apache-2.0"
] | 1 | 2021-05-04T06:49:18.000Z | 2021-05-04T06:49:18.000Z | // Copyright 2019 The gVisor 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.
#include <fcntl.h>
#include <linux/unistd.h>
#include <sys/eventfd.h>
#include <sys/resource.h>
#include <sys/sendfile.h>
#include <sys/time.h>
#include <unistd.h>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/util/file_descriptor.h"
#include "test/util/signal_util.h"
#include "test/util/temp_path.h"
#include "test/util/test_util.h"
#include "test/util/thread_util.h"
#include "test/util/timer_util.h"
namespace gvisor {
namespace testing {
namespace {
TEST(SpliceTest, TwoRegularFiles) {
// Create temp files.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
// Open the input file as read only.
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));
// Open the output file as write only.
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_WRONLY));
// Verify that it is rejected as expected; regardless of offsets.
loff_t in_offset = 0;
loff_t out_offset = 0;
EXPECT_THAT(splice(in_fd.get(), &in_offset, out_fd.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(splice(in_fd.get(), nullptr, out_fd.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(splice(in_fd.get(), &in_offset, out_fd.get(), nullptr, 1, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(splice(in_fd.get(), nullptr, out_fd.get(), nullptr, 1, 0),
SyscallFailsWithErrno(EINVAL));
}
int memfd_create(const std::string& name, unsigned int flags) {
return syscall(__NR_memfd_create, name.c_str(), flags);
}
TEST(SpliceTest, NegativeOffset) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the output file as write only.
int fd;
EXPECT_THAT(fd = memfd_create("negative", 0), SyscallSucceeds());
const FileDescriptor out_fd(fd);
loff_t out_offset = 0xffffffffffffffffull;
constexpr int kSize = 2;
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kSize, 0),
SyscallFailsWithErrno(EINVAL));
}
// Write offset + size overflows int64.
//
// This is a regression test for b/148041624.
TEST(SpliceTest, WriteOverflow) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the output file.
int fd;
EXPECT_THAT(fd = memfd_create("overflow", 0), SyscallSucceeds());
const FileDescriptor out_fd(fd);
// out_offset + kSize overflows INT64_MAX.
loff_t out_offset = 0x7ffffffffffffffeull;
constexpr int kSize = 3;
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(SpliceTest, SamePipe) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Attempt to splice to itself.
EXPECT_THAT(splice(rfd.get(), nullptr, wfd.get(), nullptr, kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(TeeTest, SamePipe) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill the pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Attempt to tee to itself.
EXPECT_THAT(tee(rfd.get(), wfd.get(), kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(TeeTest, RegularFile) {
// Open some file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Attempt to tee from the file.
EXPECT_THAT(tee(in_fd.get(), wfd.get(), kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(tee(rfd.get(), in_fd.get(), kPageSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(SpliceTest, PipeOffsets) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// All pipe offsets should be rejected.
loff_t in_offset = 0;
loff_t out_offset = 0;
EXPECT_THAT(splice(rfd1.get(), &in_offset, wfd2.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(ESPIPE));
EXPECT_THAT(splice(rfd1.get(), nullptr, wfd2.get(), &out_offset, 1, 0),
SyscallFailsWithErrno(ESPIPE));
EXPECT_THAT(splice(rfd1.get(), &in_offset, wfd2.get(), nullptr, 1, 0),
SyscallFailsWithErrno(ESPIPE));
}
// Event FDs may be used with splice without an offset.
TEST(SpliceTest, FromEventFD) {
// Open the input eventfd with an initial value so that it is readable.
constexpr uint64_t kEventFDValue = 1;
int efd;
ASSERT_THAT(efd = eventfd(kEventFDValue, 0), SyscallSucceeds());
const FileDescriptor in_fd(efd);
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice 8-byte eventfd value to pipe.
constexpr int kEventFDSize = 8;
EXPECT_THAT(splice(in_fd.get(), nullptr, wfd.get(), nullptr, kEventFDSize, 0),
SyscallSucceedsWithValue(kEventFDSize));
// Contents should be equal.
std::vector<char> rbuf(kEventFDSize);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kEventFDSize));
EXPECT_EQ(memcmp(rbuf.data(), &kEventFDValue, rbuf.size()), 0);
}
// Event FDs may not be used with splice with an offset.
TEST(SpliceTest, FromEventFDOffset) {
int efd;
ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());
const FileDescriptor in_fd(efd);
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Attempt to splice 8-byte eventfd value to pipe with offset.
//
// This is not allowed because eventfd doesn't support pread.
constexpr int kEventFDSize = 8;
loff_t in_off = 0;
EXPECT_THAT(splice(in_fd.get(), &in_off, wfd.get(), nullptr, kEventFDSize, 0),
SyscallFailsWithErrno(EINVAL));
}
// Event FDs may not be used with splice with an offset.
TEST(SpliceTest, ToEventFDOffset) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with a value.
constexpr int kEventFDSize = 8;
std::vector<char> buf(kEventFDSize);
buf[0] = 1;
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kEventFDSize));
int efd;
ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());
const FileDescriptor out_fd(efd);
// Attempt to splice 8-byte eventfd value to pipe with offset.
//
// This is not allowed because eventfd doesn't support pwrite.
loff_t out_off = 0;
EXPECT_THAT(
splice(rfd.get(), nullptr, out_fd.get(), &out_off, kEventFDSize, 0),
SyscallFailsWithErrno(EINVAL));
}
TEST(SpliceTest, ToPipe) {
// Open the input file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(in_fd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
ASSERT_THAT(lseek(in_fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice to the pipe.
EXPECT_THAT(splice(in_fd.get(), nullptr, wfd.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Contents should be equal.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), buf.size()), 0);
}
TEST(SpliceTest, ToPipeEOF) {
// Create and open an empty input file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice from the empty file to the pipe.
EXPECT_THAT(splice(in_fd.get(), nullptr, wfd.get(), nullptr, 123, 0),
SyscallSucceedsWithValue(0));
}
TEST(SpliceTest, ToPipeOffset) {
// Open the input file.
const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor in_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(in_fd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Splice to the pipe.
loff_t in_offset = kPageSize / 2;
EXPECT_THAT(
splice(in_fd.get(), &in_offset, wfd.get(), nullptr, kPageSize / 2, 0),
SyscallSucceedsWithValue(kPageSize / 2));
// Contents should be equal to only the second part.
std::vector<char> rbuf(kPageSize / 2);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize / 2));
EXPECT_EQ(memcmp(rbuf.data(), buf.data() + (kPageSize / 2), rbuf.size()), 0);
}
TEST(SpliceTest, FromPipe) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the output file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
// Splice to the output file.
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// The offset of the output should be equal to kPageSize. We assert that and
// reset to zero so that we can read the contents and ensure they match.
EXPECT_THAT(lseek(out_fd.get(), 0, SEEK_CUR),
SyscallSucceedsWithValue(kPageSize));
ASSERT_THAT(lseek(out_fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
// Contents should be equal.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(out_fd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), buf.size()), 0);
}
TEST(SpliceTest, FromPipeMultiple) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
std::string buf = "abcABC123";
ASSERT_THAT(write(wfd.get(), buf.c_str(), buf.size()),
SyscallSucceedsWithValue(buf.size()));
// Open the output file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
// Splice from the pipe to the output file over several calls.
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3, 0),
SyscallSucceedsWithValue(3));
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3, 0),
SyscallSucceedsWithValue(3));
EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3, 0),
SyscallSucceedsWithValue(3));
// Reset cursor to zero so that we can check the contents.
ASSERT_THAT(lseek(out_fd.get(), 0, SEEK_SET), SyscallSucceedsWithValue(0));
// Contents should be equal.
std::vector<char> rbuf(buf.size());
ASSERT_THAT(read(out_fd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(rbuf.size()));
EXPECT_EQ(memcmp(rbuf.data(), buf.c_str(), buf.size()), 0);
}
TEST(SpliceTest, FromPipeOffset) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the input file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
// Splice to the output file.
loff_t out_offset = kPageSize / 2;
EXPECT_THAT(
splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Content should reflect the splice. We write to a specific offset in the
// file, so the internals should now be allocated sparsely.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(out_fd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
std::vector<char> zbuf(kPageSize / 2);
memset(zbuf.data(), 0, zbuf.size());
EXPECT_EQ(memcmp(rbuf.data(), zbuf.data(), zbuf.size()), 0);
EXPECT_EQ(memcmp(rbuf.data() + kPageSize / 2, buf.data(), kPageSize / 2), 0);
}
TEST(SpliceTest, TwoPipes) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd1.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Splice to the second pipe, using two operations.
EXPECT_THAT(
splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize / 2, 0),
SyscallSucceedsWithValue(kPageSize / 2));
EXPECT_THAT(
splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize / 2, 0),
SyscallSucceedsWithValue(kPageSize / 2));
// Content should reflect the splice.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
}
TEST(SpliceTest, TwoPipesPartialRead) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write half a page of data to the first pipe.
std::vector<char> buf(kPageSize / 2);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize / 2));
// Attempt to splice one page from the first pipe to the second; it should
// immediately return after splicing the half-page previously written to the
// first pipe.
EXPECT_THAT(
splice(first_rfd.get(), nullptr, second_wfd.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize / 2));
}
TEST(SpliceTest, TwoPipesPartialWrite) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write two pages of data to the first pipe.
std::vector<char> buf(2 * kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(2 * kPageSize));
// Limit the second pipe to two pages, then write one page of data to it.
ASSERT_THAT(fcntl(second_wfd.get(), F_SETPIPE_SZ, 2 * kPageSize),
SyscallSucceeds());
ASSERT_THAT(write(second_wfd.get(), buf.data(), buf.size() / 2),
SyscallSucceedsWithValue(kPageSize));
// Attempt to splice two pages from the first pipe to the second; it should
// immediately return after splicing the first page previously written to the
// first pipe.
EXPECT_THAT(splice(first_rfd.get(), nullptr, second_wfd.get(), nullptr,
2 * kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
}
TEST(TeeTest, TwoPipesPartialRead) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write half a page of data to the first pipe.
std::vector<char> buf(kPageSize / 2);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize / 2));
// Attempt to tee one page from the first pipe to the second; it should
// immediately return after copying the half-page previously written to the
// first pipe.
EXPECT_THAT(tee(first_rfd.get(), second_wfd.get(), kPageSize, 0),
SyscallSucceedsWithValue(kPageSize / 2));
}
TEST(TeeTest, TwoPipesPartialWrite) {
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// Write two pages of data to the first pipe.
std::vector<char> buf(2 * kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(2 * kPageSize));
// Limit the second pipe to two pages, then write one page of data to it.
ASSERT_THAT(fcntl(second_wfd.get(), F_SETPIPE_SZ, 2 * kPageSize),
SyscallSucceeds());
ASSERT_THAT(write(second_wfd.get(), buf.data(), buf.size() / 2),
SyscallSucceedsWithValue(kPageSize));
// Attempt to tee two pages from the first pipe to the second; it should
// immediately return after copying the first page previously written to the
// first pipe.
EXPECT_THAT(tee(first_rfd.get(), second_wfd.get(), 2 * kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
}
TEST(SpliceTest, TwoPipesCircular) {
// This test deadlocks the sentry on VFS1 because VFS1 splice ordering is
// based on fs.File.UniqueID, which does not prevent circular ordering between
// e.g. inode-level locks taken by fs.FileOperations.
SKIP_IF(IsRunningWithVFS1());
// Create two pipes.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor first_rfd(fds[0]);
const FileDescriptor first_wfd(fds[1]);
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor second_rfd(fds[0]);
const FileDescriptor second_wfd(fds[1]);
// On Linux, each pipe is normally limited to
// include/linux/pipe_fs_i.h:PIPE_DEF_BUFFERS buffers worth of data.
constexpr size_t PIPE_DEF_BUFFERS = 16;
// Write some data to each pipe. Below we splice 1 byte at a time between
// pipes, which very quickly causes each byte to be stored in a separate
// buffer, so we must ensure that the total amount of data in the system is <=
// PIPE_DEF_BUFFERS bytes.
std::vector<char> buf(PIPE_DEF_BUFFERS / 2);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(first_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(buf.size()));
ASSERT_THAT(write(second_wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(buf.size()));
// Have another thread splice from the second pipe to the first, while we
// splice from the first to the second. The test passes if this does not
// deadlock.
const int kIterations = 1000;
DisableSave ds;
ScopedThread t([&]() {
for (int i = 0; i < kIterations; i++) {
ASSERT_THAT(
splice(second_rfd.get(), nullptr, first_wfd.get(), nullptr, 1, 0),
SyscallSucceedsWithValue(1));
}
});
for (int i = 0; i < kIterations; i++) {
ASSERT_THAT(
splice(first_rfd.get(), nullptr, second_wfd.get(), nullptr, 1, 0),
SyscallSucceedsWithValue(1));
}
}
TEST(SpliceTest, Blocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// This thread writes to the main pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ScopedThread t([&]() {
ASSERT_THAT(write(wfd1.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
});
// Attempt a splice immediately; it should block.
EXPECT_THAT(splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Thread should be joinable.
t.Join();
// Content should reflect the splice.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
}
TEST(TeeTest, Blocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// This thread writes to the main pipe.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ScopedThread t([&]() {
ASSERT_THAT(write(wfd1.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
});
// Attempt a tee immediately; it should block.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Thread should be joinable.
t.Join();
// Content should reflect the splice, in both pipes.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
ASSERT_THAT(read(rfd1.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), kPageSize), 0);
}
TEST(TeeTest, BlockingWrite) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Make some data available to be read.
std::vector<char> buf1(kPageSize);
RandomizeBuffer(buf1.data(), buf1.size());
ASSERT_THAT(write(wfd1.get(), buf1.data(), buf1.size()),
SyscallSucceedsWithValue(kPageSize));
// Fill up the write pipe's buffer.
int pipe_size = -1;
ASSERT_THAT(pipe_size = fcntl(wfd2.get(), F_GETPIPE_SZ), SyscallSucceeds());
std::vector<char> buf2(pipe_size);
ASSERT_THAT(write(wfd2.get(), buf2.data(), buf2.size()),
SyscallSucceedsWithValue(pipe_size));
ScopedThread t([&]() {
absl::SleepFor(absl::Milliseconds(100));
ASSERT_THAT(read(rfd2.get(), buf2.data(), buf2.size()),
SyscallSucceedsWithValue(pipe_size));
});
// Attempt a tee immediately; it should block.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), kPageSize, 0),
SyscallSucceedsWithValue(kPageSize));
// Thread should be joinable.
t.Join();
// Content should reflect the tee.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf1.data(), kPageSize), 0);
}
TEST(SpliceTest, NonBlocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Splice with no data to back it.
EXPECT_THAT(splice(rfd1.get(), nullptr, wfd2.get(), nullptr, kPageSize,
SPLICE_F_NONBLOCK),
SyscallFailsWithErrno(EAGAIN));
}
TEST(TeeTest, NonBlocking) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Splice with no data to back it.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), kPageSize, SPLICE_F_NONBLOCK),
SyscallFailsWithErrno(EAGAIN));
}
TEST(TeeTest, MultiPage) {
// Create two new pipes.
int first[2], second[2];
ASSERT_THAT(pipe(first), SyscallSucceeds());
const FileDescriptor rfd1(first[0]);
const FileDescriptor wfd1(first[1]);
ASSERT_THAT(pipe(second), SyscallSucceeds());
const FileDescriptor rfd2(second[0]);
const FileDescriptor wfd2(second[1]);
// Make some data available to be read.
std::vector<char> wbuf(8 * kPageSize);
RandomizeBuffer(wbuf.data(), wbuf.size());
ASSERT_THAT(write(wfd1.get(), wbuf.data(), wbuf.size()),
SyscallSucceedsWithValue(wbuf.size()));
// Attempt a tee immediately; it should complete.
EXPECT_THAT(tee(rfd1.get(), wfd2.get(), wbuf.size(), 0),
SyscallSucceedsWithValue(wbuf.size()));
// Content should reflect the tee.
std::vector<char> rbuf(wbuf.size());
ASSERT_THAT(read(rfd2.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(rbuf.size()));
EXPECT_EQ(memcmp(rbuf.data(), wbuf.data(), rbuf.size()), 0);
ASSERT_THAT(read(rfd1.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(rbuf.size()));
EXPECT_EQ(memcmp(rbuf.data(), wbuf.data(), rbuf.size()), 0);
}
TEST(SpliceTest, FromPipeMaxFileSize) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
const FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
// Open the input file.
const TempPath out_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
const FileDescriptor out_fd =
ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_RDWR));
EXPECT_THAT(ftruncate(out_fd.get(), 13 << 20), SyscallSucceeds());
EXPECT_THAT(lseek(out_fd.get(), 0, SEEK_END),
SyscallSucceedsWithValue(13 << 20));
// Set our file size limit.
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGXFSZ);
TEST_PCHECK(sigprocmask(SIG_BLOCK, &set, nullptr) == 0);
rlimit rlim = {};
rlim.rlim_cur = rlim.rlim_max = (13 << 20);
EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &rlim), SyscallSucceeds());
// Splice to the output file.
EXPECT_THAT(
splice(rfd.get(), nullptr, out_fd.get(), nullptr, 3 * kPageSize, 0),
SyscallFailsWithErrno(EFBIG));
// Contents should be equal.
std::vector<char> rbuf(kPageSize);
ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),
SyscallSucceedsWithValue(kPageSize));
EXPECT_EQ(memcmp(rbuf.data(), buf.data(), buf.size()), 0);
}
TEST(SpliceTest, FromPipeToDevZero) {
// Create a new pipe.
int fds[2];
ASSERT_THAT(pipe(fds), SyscallSucceeds());
const FileDescriptor rfd(fds[0]);
FileDescriptor wfd(fds[1]);
// Fill with some random data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),
SyscallSucceedsWithValue(kPageSize));
const FileDescriptor zero =
ASSERT_NO_ERRNO_AND_VALUE(Open("/dev/zero", O_WRONLY));
// Close the write end to prevent blocking below.
wfd.reset();
// Splice to /dev/zero. The first call should empty the pipe, and the return
// value should not exceed the number of bytes available for reading.
EXPECT_THAT(
splice(rfd.get(), nullptr, zero.get(), nullptr, kPageSize + 123, 0),
SyscallSucceedsWithValue(kPageSize));
EXPECT_THAT(splice(rfd.get(), nullptr, zero.get(), nullptr, 1, 0),
SyscallSucceedsWithValue(0));
}
static volatile int signaled = 0;
void SigUsr1Handler(int sig, siginfo_t* info, void* context) { signaled = 1; }
TEST(SpliceTest, ToPipeWithSmallCapacityDoesNotSpin) {
// Writes to a pipe that are less than PIPE_BUF must be atomic. This test
// creates a pipe with only 128 bytes of capacity (< PIPE_BUF) and checks that
// splicing to the pipe does not spin. See b/170743336.
// Create a file with one page of data.
std::vector<char> buf(kPageSize);
RandomizeBuffer(buf.data(), buf.size());
auto file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(
GetAbsoluteTestTmpdir(), absl::string_view(buf.data(), buf.size()),
TempPath::kDefaultFileMode));
auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));
// Create a pipe with size 4096, and fill all but 128 bytes of it.
int p[2];
ASSERT_THAT(pipe(p), SyscallSucceeds());
ASSERT_THAT(fcntl(p[1], F_SETPIPE_SZ, kPageSize), SyscallSucceeds());
const int kWriteSize = kPageSize - 128;
std::vector<char> writeBuf(kWriteSize);
RandomizeBuffer(writeBuf.data(), writeBuf.size());
ASSERT_THAT(write(p[1], writeBuf.data(), writeBuf.size()),
SyscallSucceedsWithValue(kWriteSize));
// Set up signal handler.
struct sigaction sa = {};
sa.sa_sigaction = SigUsr1Handler;
sa.sa_flags = SA_SIGINFO;
const auto cleanup_sigact =
ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGUSR1, sa));
// Send SIGUSR1 to this thread in 1 second.
struct sigevent sev = {};
sev.sigev_notify = SIGEV_THREAD_ID;
sev.sigev_signo = SIGUSR1;
sev.sigev_notify_thread_id = gettid();
auto timer = ASSERT_NO_ERRNO_AND_VALUE(TimerCreate(CLOCK_MONOTONIC, sev));
struct itimerspec its = {};
its.it_value = absl::ToTimespec(absl::Seconds(1));
DisableSave ds; // Asserting an EINTR.
ASSERT_NO_ERRNO(timer.Set(0, its));
// Now splice the file to the pipe. This should block, but not spin, and
// should return EINTR because it is interrupted by the signal.
EXPECT_THAT(splice(fd.get(), nullptr, p[1], nullptr, kPageSize, 0),
SyscallFailsWithErrno(EINTR));
// Alarm should have been handled.
EXPECT_EQ(signaled, 1);
}
} // namespace
} // namespace testing
} // namespace gvisor
| 35.907447 | 80 | 0.68785 | Exhorder6 |
c85fc4816b086d7a5792ebfbaf8e167c338ccd1c | 2,582 | cpp | C++ | CONTRIB/LLVM/src/lib/Tg/Mips/MCTargetDesc/MipsMCExpr.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 30 | 2016-09-06T06:58:43.000Z | 2021-12-23T11:59:38.000Z | CONTRIB/LLVM/src/lib/Tg/Mips/MCTargetDesc/MipsMCExpr.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | CONTRIB/LLVM/src/lib/Tg/Mips/MCTargetDesc/MipsMCExpr.cpp | Cwc-Test/CpcdosOS2.1 | d52c170be7f11cc50de38ef536d4355743d21706 | [
"Apache-2.0"
] | 17 | 2016-10-24T06:08:16.000Z | 2022-02-18T17:27:14.000Z | //===-- MipsMCExpr.cpp - Mips specific MC expression classes --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MipsMCExpr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectStreamer.h"
using namespace llvm;
#define DEBUG_TYPE "mipsmcexpr"
bool MipsMCExpr::isSupportedBinaryExpr(MCSymbolRefExpr::VariantKind VK,
const MCBinaryExpr *BE) {
switch (VK) {
case MCSymbolRefExpr::VK_Mips_ABS_LO:
case MCSymbolRefExpr::VK_Mips_ABS_HI:
case MCSymbolRefExpr::VK_Mips_HIGHER:
case MCSymbolRefExpr::VK_Mips_HIGHEST:
break;
default:
return false;
}
// We support expressions of the form "(sym1 binop1 sym2) binop2 const",
// where "binop2 const" is optional.
if (isa<MCBinaryExpr>(BE->getLHS())) {
if (!isa<MCConstantExpr>(BE->getRHS()))
return false;
BE = cast<MCBinaryExpr>(BE->getLHS());
}
return (isa<MCSymbolRefExpr>(BE->getLHS())
&& isa<MCSymbolRefExpr>(BE->getRHS()));
}
const MipsMCExpr*
MipsMCExpr::create(MCSymbolRefExpr::VariantKind VK, const MCExpr *Expr,
MCContext &Ctx) {
VariantKind Kind;
switch (VK) {
case MCSymbolRefExpr::VK_Mips_ABS_LO:
Kind = VK_Mips_LO;
break;
case MCSymbolRefExpr::VK_Mips_ABS_HI:
Kind = VK_Mips_HI;
break;
case MCSymbolRefExpr::VK_Mips_HIGHER:
Kind = VK_Mips_HIGHER;
break;
case MCSymbolRefExpr::VK_Mips_HIGHEST:
Kind = VK_Mips_HIGHEST;
break;
default:
llvm_unreachable("Invalid kind!");
}
return new (Ctx) MipsMCExpr(Kind, Expr);
}
void MipsMCExpr::printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const {
switch (Kind) {
default: llvm_unreachable("Invalid kind!");
case VK_Mips_LO: OS << "%lo"; break;
case VK_Mips_HI: OS << "%hi"; break;
case VK_Mips_HIGHER: OS << "%higher"; break;
case VK_Mips_HIGHEST: OS << "%highest"; break;
}
OS << '(';
Expr->print(OS, MAI);
OS << ')';
}
bool
MipsMCExpr::evaluateAsRelocatableImpl(MCValue &Res,
const MCAsmLayout *Layout,
const MCFixup *Fixup) const {
return getSubExpr()->evaluateAsRelocatable(Res, Layout, Fixup);
}
void MipsMCExpr::visitUsedExpr(MCStreamer &Streamer) const {
Streamer.visitUsedExpr(*getSubExpr());
}
| 28.373626 | 80 | 0.636716 | Cwc-Test |
c864540a4c498bfe9f36e73c874f7fb974c9e2b6 | 1,258 | cpp | C++ | src/engine/utils.cpp | FoxySeta/unibo-00819-programmazione-project | 4475a3a64b78222cbbdeda908f18cf93e4a210be | [
"MIT"
] | 3 | 2021-09-06T15:51:11.000Z | 2021-09-08T12:30:35.000Z | src/engine/utils.cpp | lucat1/unibo_00819_progetto | 4475a3a64b78222cbbdeda908f18cf93e4a210be | [
"MIT"
] | null | null | null | src/engine/utils.cpp | lucat1/unibo_00819_progetto | 4475a3a64b78222cbbdeda908f18cf93e4a210be | [
"MIT"
] | 2 | 2021-09-07T00:40:37.000Z | 2021-09-08T17:34:45.000Z | /*
University of Bologna
First cicle degree in Computer Science
00819 - Programmazione
Luca Tagliavini #971133
04/27/2021
screen.cpp: implements engine's utility functions mainly to manipulate
integers and strings, for the choice ui element and the results menu
*/
#include "utils.hpp"
int Engine::Utils::digits(int n) {
int k = 0;
while (n > 0) {
k++;
n /= 10;
}
return k;
}
char Engine::Utils::digitize(int n) {
if (n > 9)
return u'-'; // undefined behaviour
return u'0' + n;
}
void Engine::Utils::stringify(int n, Nostd::String &str) {
if (n == 0)
str.insert(str.length(), u'0');
else {
if (n < 0) {
str.insert(0, u'-');
n = -n; // make it positive
}
int last = str.length();
while (n > 0) {
str.insert(last, digitize(n % 10));
n /= 10;
}
}
}
void Engine::Utils::leftpad(size_t n, Nostd::String &str) {
size_t len = str.length();
if (len > n) {
str = str.substr(0, n - 1);
} else if (len != n) {
size_t amount = n - len;
char space[amount + 1];
// fill the space string with the right amount of spaces
for (size_t i = 0; i < amount; i++)
space[i] = u' ';
space[amount] = '\0';
str.insert(0, space, amount);
}
}
| 19.968254 | 72 | 0.572337 | FoxySeta |
c86489c7f75ba795436fbb5f3f7eb8ad84b1d0f9 | 11,186 | cpp | C++ | src/logonserver/Main.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | 1 | 2018-01-17T08:11:17.000Z | 2018-01-17T08:11:17.000Z | src/logonserver/Main.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | src/logonserver/Main.cpp | Subv/diamondcore | e11891587736b6308e554f71cb56e8df1a1812ad | [
"OpenSSL"
] | null | null | null | /*
* Copyright (C) 2010 DiamondCore <http://diamondcore.eu/>
*
* 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
*/
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "RealmList.h"
#include "Config/Config.h"
#include "Log.h"
#include "AuthSocket.h"
#include "SystemConfig.h"
#include "revision_nr.h"
#include "Util.h"
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <ace/Get_Opt.h>
#include <ace/Dev_Poll_Reactor.h>
#include <ace/ACE.h>
#include <ace/Acceptor.h>
#include <ace/SOCK_Acceptor.h>
#ifdef WIN32
#include "ServiceWin32.h"
char serviceName[] = "LogonServer";
char serviceLongName[] = "DiamondCore Realm service";
char serviceDescription[] = "Massive Network Game Object Server";
/*
* -1 - not in service mode
* 0 - stopped
* 1 - running
* 2 - paused
*/
int m_ServiceStatus = -1;
#endif
bool StartDB();
void UnhookSignals();
void HookSignals();
bool stopEvent = false; ///< Setting it to true stops the server
DatabaseType loginDatabase; ///< Accessor to the realm server database
/// Print out the usage string for this program on the console.
void usage(const char *prog)
{
sLog.outString("Usage: \n %s [<options>]\n"
" -v, --version print version and exist\n\r"
" -c config_file use config_file as configuration file\n\r"
#ifdef WIN32
" Running as service functions:\n\r"
" -s run run as service\n\r"
" -s install install service\n\r"
" -s uninstall uninstall service\n\r"
#endif
,prog);
}
/// Launch the realm server
extern int main(int argc, char **argv)
{
///- Command line parsing
char const* cfg_file = _LOGON_CONFIG;
#ifdef WIN32
char const *options = ":c:s:";
#else
char const *options = ":c:";
#endif
ACE_Get_Opt cmd_opts(argc, argv, options);
cmd_opts.long_option("version", 'v');
int option;
while ((option = cmd_opts()) != EOF)
{
switch (option)
{
case 'c':
cfg_file = cmd_opts.opt_arg();
break;
case 'v':
printf("%s\n", _FULLVERSION);
return 0;
#ifdef WIN32
case 's':
{
const char *mode = cmd_opts.opt_arg();
if (!strcmp(mode, "install"))
{
if (WinServiceInstall())
sLog.outString("Installing service");
return 1;
}
else if (!strcmp(mode, "uninstall"))
{
if (WinServiceUninstall())
sLog.outString("Uninstalling service");
return 1;
}
else if (!strcmp(mode, "run"))
WinServiceRun();
else
{
sLog.outError("Runtime-Error: -%c unsupported argument %s", cmd_opts.opt_opt(), mode);
usage(argv[0]);
Log::WaitBeforeContinueIfNeed();
return 1;
}
break;
}
#endif
case ':':
sLog.outError("Runtime-Error: -%c option requires an input argument", cmd_opts.opt_opt());
usage(argv[0]);
return 1;
default:
sLog.outError("Runtime-Error: bad format of commandline arguments");
usage(argv[0]);
return 1;
}
}
if (!sConfig.SetSource(cfg_file))
{
sLog.outError("Could not find configuration file %s.", cfg_file);
return 1;
}
sLog.Initialize();
sLog.outString( "%s [realm-daemon]", _FULLVERSION);
sLog.outString( "<Ctrl-C> to stop.\n" );
sLog.outString("Using configuration file %s.", cfg_file);
///- Check the version of the configuration file
uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
if (confVersion < _LOGONCONFVERSION)
{
sLog.outError("*****************************************************************************");
sLog.outError(" WARNING: Your LogonServer.conf version indicates your conf file is out of date!");
sLog.outError(" Please check for updates, as your current default values may cause");
sLog.outError(" strange behavior.");
sLog.outError("*****************************************************************************");
clock_t pause = 3000 + clock();
while (pause > clock())
{
}
}
sLog.outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
if (SSLeay() < 0x009080bfL)
{
sLog.outDetail("WARNING: Outdated version of OpenSSL lib. Logins to server may not work!");
sLog.outDetail("WARNING: Minimal required version [OpenSSL 0.9.8k]");
}
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
ACE_Reactor::instance(new ACE_Reactor(new ACE_Dev_Poll_Reactor(ACE::max_handles(), 1), 1), true);
#endif
sLog.outBasic("Max allowed open files is %d", ACE::max_handles());
/// LogonServer PID file creation
std::string pidfile = sConfig.GetStringDefault("PidFile", "");
if (!pidfile.empty())
{
uint32 pid = CreatePIDFile(pidfile);
if (!pid )
{
sLog.outError( "Cannot create PID file %s.\n", pidfile.c_str());
return 1;
}
sLog.outString("Daemon PID: %u\n", pid );
}
///- Initialize the database connection
if (!StartDB())
return 1;
///- Get the list of realms for the server
sRealmList.Initialize(sConfig.GetIntDefault("RealmsStateUpdateDelay", 20));
if (sRealmList.size() == 0)
{
sLog.outError("No valid realms specified.");
return 1;
}
// cleanup query
// set expired bans to inactive
loginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
///- Launch the listening network socket
ACE_Acceptor<AuthSocket, ACE_SOCK_Acceptor> acceptor;
uint16 rmport = sConfig.GetIntDefault("RealmServerPort", DEFAULT_REALMSERVER_PORT);
std::string bind_ip = sConfig.GetStringDefault("BindIP", "0.0.0.0");
ACE_INET_Addr bind_addr(rmport, bind_ip.c_str());
if(acceptor.open(bind_addr, ACE_Reactor::instance(), ACE_NONBLOCK) == -1)
{
sLog.outError("LogonServer can not bind to %s:%d", bind_ip.c_str(), rmport);
return 1;
}
///- Catch termination signals
HookSignals();
///- Handle affinity for multiple processors and process priority on Windows
#ifdef WIN32
{
HANDLE hProcess = GetCurrentProcess();
uint32 Aff = sConfig.GetIntDefault("UseProcessors", 0);
if (Aff > 0)
{
ULONG_PTR appAff;
ULONG_PTR sysAff;
if (GetProcessAffinityMask(hProcess, &appAff, &sysAff))
{
ULONG_PTR curAff = Aff & appAff; // remove non accessible processors
if (!curAff)
{
sLog.outError("Processors marked in UseProcessors bitmask (hex) %x not accessible for realmd. Accessible processors bitmask (hex): %x", Aff,appAff);
}
else
{
if (SetProcessAffinityMask(hProcess, curAff))
sLog.outString("Using processors (bitmask, hex): %x", curAff);
else
sLog.outError("Can't set used processors (hex): %x", curAff);
}
}
sLog.outString();
}
bool Prio = sConfig.GetBoolDefault("ProcessPriority", false);
if (Prio)
{
if (SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS))
sLog.outString("LogonServer process priority class set to HIGH");
else
sLog.outError("ERROR: Can't set LogonServer process priority class.");
}
}
#endif
// maximum counter for next ping
uint32 numLoops = (sConfig.GetIntDefault("MaxPingTime", 30) * (MINUTE * 1000000 / 100000));
uint32 loopCounter = 0;
///- Wait for termination signal
while (!stopEvent)
{
// dont move this outside the loop, the reactor will modify it
ACE_Time_Value interval(0, 100000);
if (ACE_Reactor::instance()->run_reactor_event_loop(interval) == -1)
break;
if ((++loopCounter) == numLoops)
{
loopCounter = 0;
sLog.outDetail("Ping MySQL to keep connection alive");
delete loginDatabase.Query("SELECT 1 FROM realmlist LIMIT 1");
}
#ifdef WIN32
if (m_ServiceStatus == 0)
stopEvent = true;
while (m_ServiceStatus == 2)
Sleep(1000);
#endif
}
///- Wait for the delay thread to exit
loginDatabase.HaltDelayThread();
///- Remove signal handling before leaving
UnhookSignals();
sLog.outString("Halting process...");
return 0;
}
/// Handle termination signals
/** Put the global variable stopEvent to 'true' if a termination signal is caught **/
void OnSignal(int s)
{
switch (s)
{
case SIGINT:
case SIGTERM:
stopEvent = true;
break;
#ifdef _WIN32
case SIGBREAK:
stopEvent = true;
break;
#endif
}
signal(s, OnSignal);
}
/// Initialize connection to the database
bool StartDB()
{
std::string dbstring = sConfig.GetStringDefault("LoginDatabaseInfo", "");
if (dbstring.empty())
{
sLog.outError("Database not specified");
return false;
}
sLog.outString("Database: %s", dbstring.c_str() );
if (!loginDatabase.Initialize(dbstring.c_str()))
{
sLog.outError("Cannot connect to database");
return false;
}
return true;
}
/// Define hook 'OnSignal' for all termination signals
void HookSignals()
{
signal(SIGINT, OnSignal);
signal(SIGTERM, OnSignal);
#ifdef _WIN32
signal(SIGBREAK, OnSignal);
#endif
}
/// Unhook the signals before leaving
void UnhookSignals()
{
signal(SIGINT, 0);
signal(SIGTERM, 0);
#ifdef _WIN32
signal(SIGBREAK, 0);
#endif
}
/// @}
| 30.150943 | 168 | 0.576792 | Subv |
c864fa14a7a0a0d8fd8499cfc392a48cb974c5c5 | 27,077 | cpp | C++ | fdk-aac/libFDK/src/mdct.cpp | Opendigitalradio/ODR-AudioEnc | f932f86ec601e250bbdcf2bcf87e4696b9431b50 | [
"Apache-2.0"
] | 15 | 2016-10-18T11:46:21.000Z | 2022-01-16T10:34:52.000Z | fdk-aac/libFDK/src/mdct.cpp | Opendigitalradio/ODR-AudioEnc | f932f86ec601e250bbdcf2bcf87e4696b9431b50 | [
"Apache-2.0"
] | 14 | 2016-11-15T21:14:50.000Z | 2020-09-15T10:13:23.000Z | fdk-aac/libFDK/src/mdct.cpp | Opendigitalradio/ODR-AudioEnc | f932f86ec601e250bbdcf2bcf87e4696b9431b50 | [
"Apache-2.0"
] | 21 | 2016-11-15T09:00:30.000Z | 2022-03-23T17:54:40.000Z | /* -----------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android
© Copyright 1995 - 2019 Fraunhofer-Gesellschaft zur Förderung der angewandten
Forschung e.V. All rights reserved.
1. INTRODUCTION
The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
scheme for digital audio. This FDK AAC Codec software is intended to be used on
a wide variety of Android devices.
AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
general perceptual audio codecs. AAC-ELD is considered the best-performing
full-bandwidth communications codec by independent studies and is widely
deployed. AAC has been standardized by ISO and IEC as part of the MPEG
specifications.
Patent licenses for necessary patent claims for the FDK AAC Codec (including
those of Fraunhofer) may be obtained through Via Licensing
(www.vialicensing.com) or through the respective patent owners individually for
the purpose of encoding or decoding bit streams in products that are compliant
with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
Android devices already license these patent claims through Via Licensing or
directly from the patent owners, and therefore FDK AAC Codec software may
already be covered under those patent licenses when it is used for those
licensed purposes only.
Commercially-licensed AAC software libraries, including floating-point versions
with enhanced sound quality, are also available from Fraunhofer. Users are
encouraged to check the Fraunhofer website for additional applications
information and documentation.
2. COPYRIGHT LICENSE
Redistribution and use in source and binary forms, with or without modification,
are permitted without payment of copyright license fees provided that you
satisfy the following conditions:
You must retain the complete text of this software license in redistributions of
the FDK AAC Codec or your modifications thereto in source code form.
You must retain the complete text of this software license in the documentation
and/or other materials provided with redistributions of the FDK AAC Codec or
your modifications thereto in binary form. You must make available free of
charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.
The name of Fraunhofer may not be used to endorse or promote products derived
from this library without prior written permission.
You may not charge copyright license fees for anyone to use, copy or distribute
the FDK AAC Codec software or your modifications thereto.
Your modified versions of the FDK AAC Codec must carry prominent notices stating
that you changed the software and the date of any change. For modified versions
of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
AAC Codec Library for Android."
3. NO PATENT LICENSE
NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
Fraunhofer provides no warranty of patent non-infringement with respect to this
software.
You may use this FDK AAC Codec software or modifications thereto only for
purposes that are authorized by appropriate patent licenses.
4. DISCLAIMER
This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
including but not limited to the implied warranties of merchantability and
fitness for a particular purpose. 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), arising in any way out of the use of
this software, even if advised of the possibility of such damage.
5. CONTACT INFORMATION
Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany
www.iis.fraunhofer.de/amm
amm-info@iis.fraunhofer.de
----------------------------------------------------------------------------- */
/******************* Library for basic calculation routines ********************
Author(s): Josef Hoepfl, Manuel Jander, Youliy Ninov, Daniel Hagel
Description: MDCT/MDST routines
*******************************************************************************/
#include "mdct.h"
#include "FDK_tools_rom.h"
#include "dct.h"
#include "fixpoint_math.h"
void mdct_init(H_MDCT hMdct, FIXP_DBL *overlap, INT overlapBufferSize) {
hMdct->overlap.freq = overlap;
// FDKmemclear(overlap, overlapBufferSize*sizeof(FIXP_DBL));
hMdct->prev_fr = 0;
hMdct->prev_nr = 0;
hMdct->prev_tl = 0;
hMdct->ov_size = overlapBufferSize;
hMdct->prevAliasSymmetry = 0;
hMdct->prevPrevAliasSymmetry = 0;
hMdct->pFacZir = NULL;
hMdct->pAsymOvlp = NULL;
}
/*
This program implements the forward MDCT transform on an input block of data.
The input block is in a form (A,B,C,D) where A,B,C and D are the respective
1/4th segments of the block. The program takes the input block and folds it in
the form:
(-D-Cr,A-Br). This block is twice shorter and here the 'r' suffix denotes
flipping of the sequence (reversing the order of the samples). While folding the
input block in the above mentioned shorter block the program windows the data.
Because the two operations (windowing and folding) are not implemented
sequentially, but together the program's structure is not easy to understand.
Once the output (already windowed) block (-D-Cr,A-Br) is ready it is passed to
the DCT IV for processing.
*/
INT mdct_block(H_MDCT hMdct, const INT_PCM *RESTRICT timeData,
const INT noInSamples, FIXP_DBL *RESTRICT mdctData,
const INT nSpec, const INT tl, const FIXP_WTP *pRightWindowPart,
const INT fr, SHORT *pMdctData_e) {
int i, n;
/* tl: transform length
fl: left window slope length
nl: left window slope offset
fr: right window slope length
nr: right window slope offset
See FDK_tools/doc/intern/mdct.tex for more detail. */
int fl, nl, nr;
const FIXP_WTP *wls, *wrs;
wrs = pRightWindowPart;
/* Detect FRprevious / FL mismatches and override parameters accordingly */
if (hMdct->prev_fr ==
0) { /* At start just initialize and pass parameters as they are */
hMdct->prev_fr = fr;
hMdct->prev_wrs = wrs;
hMdct->prev_tl = tl;
}
/* Derive NR */
nr = (tl - fr) >> 1;
/* Skip input samples if tl is smaller than block size */
timeData += (noInSamples - tl) >> 1;
/* windowing */
for (n = 0; n < nSpec; n++) {
/*
* MDCT scale:
* + 1: fMultDiv2() in windowing.
* + 1: Because of factor 1/2 in Princen-Bradley compliant windowed TDAC.
*/
INT mdctData_e = 1 + 1;
/* Derive left parameters */
wls = hMdct->prev_wrs;
fl = hMdct->prev_fr;
nl = (tl - fl) >> 1;
/* Here we implement a simplified version of what happens after the this
piece of code (see the comments below). We implement the folding of A and B
segments to (A-Br) but A is zero, because in this part of the MDCT sequence
the window coefficients with which A must be multiplied are zero. */
for (i = 0; i < nl; i++) {
#if SAMPLE_BITS == DFRACT_BITS /* SPC_BITS and DFRACT_BITS should be equal. */
mdctData[(tl / 2) + i] = -((FIXP_DBL)timeData[tl - i - 1] >> (1));
#else
mdctData[(tl / 2) + i] = -(FIXP_DBL)timeData[tl - i - 1]
<< (DFRACT_BITS - SAMPLE_BITS - 1); /* 0(A)-Br */
#endif
}
/* Implements the folding and windowing of the left part of the sequence,
that is segments A and B. The A segment is multiplied by the respective left
window coefficient and placed in a temporary variable.
tmp0 = fMultDiv2((FIXP_PCM)timeData[i+nl], pLeftWindowPart[i].v.im);
After this the B segment taken in reverse order is multiplied by the left
window and subtracted from the previously derived temporary variable, so
that finally we implement the A-Br operation. This output is written to the
right part of the MDCT output : (-D-Cr,A-Br).
mdctData[(tl/2)+i+nl] = fMultSubDiv2(tmp0, (FIXP_PCM)timeData[tl-nl-i-1],
pLeftWindowPart[i].v.re);//A*window-Br*window
The (A-Br) data is written to the output buffer (mdctData) without being
flipped. */
for (i = 0; i < fl / 2; i++) {
FIXP_DBL tmp0;
tmp0 = fMultDiv2((FIXP_PCM)timeData[i + nl], wls[i].v.im); /* a*window */
mdctData[(tl / 2) + i + nl] =
fMultSubDiv2(tmp0, (FIXP_PCM)timeData[tl - nl - i - 1],
wls[i].v.re); /* A*window-Br*window */
}
/* Right window slope offset */
/* Here we implement a simplified version of what happens after the this
piece of code (see the comments below). We implement the folding of C and D
segments to (-D-Cr) but D is zero, because in this part of the MDCT sequence
the window coefficients with which D must be multiplied are zero. */
for (i = 0; i < nr; i++) {
#if SAMPLE_BITS == \
DFRACT_BITS /* This should be SPC_BITS instead of DFRACT_BITS. */
mdctData[(tl / 2) - 1 - i] = -((FIXP_DBL)timeData[tl + i] >> (1));
#else
mdctData[(tl / 2) - 1 - i] =
-(FIXP_DBL)timeData[tl + i]
<< (DFRACT_BITS - SAMPLE_BITS - 1); /* -C flipped at placing */
#endif
}
/* Implements the folding and windowing of the right part of the sequence,
that is, segments C and D. The C segment is multiplied by the respective
right window coefficient and placed in a temporary variable.
tmp1 = fMultDiv2((FIXP_PCM)timeData[tl+nr+i], pRightWindowPart[i].v.re);
After this the D segment taken in reverse order is multiplied by the right
window and added from the previously derived temporary variable, so that we
get (C+Dr) operation. This output is negated to get (-C-Dr) and written to
the left part of the MDCT output while being reversed (flipped) at the same
time, so that from (-C-Dr) we get (-D-Cr)=> (-D-Cr,A-Br).
mdctData[(tl/2)-nr-i-1] = -fMultAddDiv2(tmp1,
(FIXP_PCM)timeData[(tl*2)-nr-i-1], pRightWindowPart[i].v.im);*/
for (i = 0; i < fr / 2; i++) {
FIXP_DBL tmp1;
tmp1 = fMultDiv2((FIXP_PCM)timeData[tl + nr + i],
wrs[i].v.re); /* C*window */
mdctData[(tl / 2) - nr - i - 1] =
-fMultAddDiv2(tmp1, (FIXP_PCM)timeData[(tl * 2) - nr - i - 1],
wrs[i].v.im); /* -(C*window+Dr*window) and flip before
placing -> -Cr - D */
}
/* We pass the shortened folded data (-D-Cr,A-Br) to the MDCT function */
dct_IV(mdctData, tl, &mdctData_e);
pMdctData_e[n] = (SHORT)mdctData_e;
timeData += tl;
mdctData += tl;
hMdct->prev_wrs = wrs;
hMdct->prev_fr = fr;
hMdct->prev_tl = tl;
}
return nSpec * tl;
}
void imdct_gain(FIXP_DBL *pGain_m, int *pGain_e, int tl) {
FIXP_DBL gain_m = *pGain_m;
int gain_e = *pGain_e;
int log2_tl;
gain_e += -MDCT_OUTPUT_GAIN - MDCT_OUT_HEADROOM + 1;
if (tl == 0) {
/* Dont regard the 2/N factor from the IDCT. It is compensated for somewhere
* else. */
*pGain_e = gain_e;
return;
}
log2_tl = DFRACT_BITS - 1 - fNormz((FIXP_DBL)tl);
gain_e += -log2_tl;
FDK_ASSERT(log2_tl - 2 >= 0);
FDK_ASSERT(log2_tl - 2 < 8*sizeof(int));
/* Detect non-radix 2 transform length and add amplitude compensation factor
which cannot be included into the exponent above */
switch ((tl) >> (log2_tl - 2)) {
case 0x7: /* 10 ms, 1/tl = 1.0/(FDKpow(2.0, -log2_tl) *
0.53333333333333333333) */
if (gain_m == (FIXP_DBL)0) {
gain_m = FL2FXCONST_DBL(0.53333333333333333333f);
} else {
gain_m = fMult(gain_m, FL2FXCONST_DBL(0.53333333333333333333f));
}
break;
case 0x6: /* 3/4 of radix 2, 1/tl = 1.0/(FDKpow(2.0, -log2_tl) * 2.0/3.0) */
if (gain_m == (FIXP_DBL)0) {
gain_m = FL2FXCONST_DBL(2.0 / 3.0f);
} else {
gain_m = fMult(gain_m, FL2FXCONST_DBL(2.0 / 3.0f));
}
break;
case 0x5: /* 0.8 of radix 2 (e.g. tl 160), 1/tl = 1.0/(FDKpow(2.0, -log2_tl)
* 0.8/1.5) */
if (gain_m == (FIXP_DBL)0) {
gain_m = FL2FXCONST_DBL(0.53333333333333333333f);
} else {
gain_m = fMult(gain_m, FL2FXCONST_DBL(0.53333333333333333333f));
}
break;
case 0x4:
/* radix 2, nothing to do. */
break;
default:
/* unsupported */
FDK_ASSERT(0);
break;
}
*pGain_m = gain_m;
*pGain_e = gain_e;
}
INT imdct_drain(H_MDCT hMdct, FIXP_DBL *output, INT nrSamplesRoom) {
int buffered_samples = 0;
if (nrSamplesRoom > 0) {
buffered_samples = hMdct->ov_offset;
FDK_ASSERT(buffered_samples <= nrSamplesRoom);
if (buffered_samples > 0) {
FDKmemcpy(output, hMdct->overlap.time,
buffered_samples * sizeof(FIXP_DBL));
hMdct->ov_offset = 0;
}
}
return buffered_samples;
}
INT imdct_copy_ov_and_nr(H_MDCT hMdct, FIXP_DBL *pTimeData, INT nrSamples) {
FIXP_DBL *pOvl;
int nt, nf, i;
nt = fMin(hMdct->ov_offset, nrSamples);
nrSamples -= nt;
nf = fMin(hMdct->prev_nr, nrSamples);
FDKmemcpy(pTimeData, hMdct->overlap.time, nt * sizeof(FIXP_DBL));
pTimeData += nt;
pOvl = hMdct->overlap.freq + hMdct->ov_size - 1;
if (hMdct->prevPrevAliasSymmetry == 0) {
for (i = 0; i < nf; i++) {
FIXP_DBL x = -(*pOvl--);
*pTimeData = IMDCT_SCALE_DBL(x);
pTimeData++;
}
} else {
for (i = 0; i < nf; i++) {
FIXP_DBL x = (*pOvl--);
*pTimeData = IMDCT_SCALE_DBL(x);
pTimeData++;
}
}
return (nt + nf);
}
void imdct_adapt_parameters(H_MDCT hMdct, int *pfl, int *pnl, int tl,
const FIXP_WTP *wls, int noOutSamples) {
int fl = *pfl, nl = *pnl;
int window_diff, use_current = 0, use_previous = 0;
if (hMdct->prev_tl == 0) {
hMdct->prev_wrs = wls;
hMdct->prev_fr = fl;
hMdct->prev_nr = (noOutSamples - fl) >> 1;
hMdct->prev_tl = noOutSamples;
hMdct->ov_offset = 0;
use_current = 1;
}
window_diff = (hMdct->prev_fr - fl) >> 1;
/* check if the previous window slope can be adjusted to match the current
* window slope */
if (hMdct->prev_nr + window_diff > 0) {
use_current = 1;
}
/* check if the current window slope can be adjusted to match the previous
* window slope */
if (nl - window_diff > 0) {
use_previous = 1;
}
/* if both is possible choose the larger of both window slope lengths */
if (use_current && use_previous) {
if (fl < hMdct->prev_fr) {
use_current = 0;
}
}
/*
* If the previous transform block is big enough, enlarge previous window
* overlap, if not, then shrink current window overlap.
*/
if (use_current) {
hMdct->prev_nr += window_diff;
hMdct->prev_fr = fl;
hMdct->prev_wrs = wls;
} else {
nl -= window_diff;
fl = hMdct->prev_fr;
}
*pfl = fl;
*pnl = nl;
}
/*
This program implements the inverse modulated lapped transform, a generalized
version of the inverse MDCT transform. Setting none of the MLT_*_ALIAS_FLAG
flags computes the IMDCT, setting all of them computes the IMDST. Other
combinations of these flags compute type III transforms used by the RSVD60
multichannel tool for transitions between MDCT/MDST. The following description
relates to the IMDCT only.
If we pass the data block (A,B,C,D,E,F) to the FORWARD MDCT it will produce two
outputs. The first one will be over the (A,B,C,D) part =>(-D-Cr,A-Br) and the
second one will be over the (C,D,E,F) part => (-F-Er,C-Dr), since there is a
overlap between consequtive passes of the algorithm. This overlap is over the
(C,D) segments. The two outputs will be given sequentially to the DCT IV
algorithm. At the INVERSE MDCT side we get two consecutive outputs from the IDCT
IV algorithm, namely the same blocks: (-D-Cr,A-Br) and (-F-Er,C-Dr). The first
of them lands in the Overlap buffer and the second is in the working one, which,
one algorithm pass later will substitute the one residing in the overlap
register. The IMDCT algorithm has to produce the C and D segments from the two
buffers. In order to do this we take the left part of the overlap
buffer(-D-Cr,A-Br), namely (-D-Cr) and add it appropriately to the right part of
the working buffer (-F-Er,C-Dr), namely (C-Dr), so that we get first the C
segment and later the D segment. We do this in the following way: From the right
part of the working buffer(C-Dr) we subtract the flipped left part of the
overlap buffer(-D-Cr):
Result = (C-Dr) - flipped(-D-Cr) = C -Dr + Dr + C = 2C
We divide by two and get the C segment. What we did is adding the right part of
the first frame to the left part of the second one. While applying these
operation we multiply the respective segments with the appropriate window
functions.
In order to get the D segment we do the following:
From the negated second part of the working buffer(C-Dr) we subtract the flipped
first part of the overlap buffer (-D-Cr):
Result= - (C -Dr) - flipped(-D-Cr)= -C +Dr +Dr +C = 2Dr.
After dividing by two and flipping we get the D segment.What we did is adding
the right part of the first frame to the left part of the second one. While
applying these operation we multiply the respective segments with the
appropriate window functions.
Once we have obtained the C and D segments the overlap buffer is emptied and the
current buffer is sent in it, so that the E and F segments are available for
decoding in the next algorithm pass.*/
INT imlt_block(H_MDCT hMdct, FIXP_DBL *output, FIXP_DBL *spectrum,
const SHORT scalefactor[], const INT nSpec,
const INT noOutSamples, const INT tl, const FIXP_WTP *wls,
INT fl, const FIXP_WTP *wrs, const INT fr, FIXP_DBL gain,
int flags) {
FIXP_DBL *pOvl;
FIXP_DBL *pOut0 = output, *pOut1;
INT nl, nr;
int w, i, nrSamples = 0, specShiftScale, transform_gain_e = 0;
int currAliasSymmetry = (flags & MLT_FLAG_CURR_ALIAS_SYMMETRY);
/* Derive NR and NL */
nr = (tl - fr) >> 1;
nl = (tl - fl) >> 1;
/* Include 2/N IMDCT gain into gain factor and exponent. */
imdct_gain(&gain, &transform_gain_e, tl);
/* Detect FRprevious / FL mismatches and override parameters accordingly */
if (hMdct->prev_fr != fl) {
imdct_adapt_parameters(hMdct, &fl, &nl, tl, wls, noOutSamples);
}
pOvl = hMdct->overlap.freq + hMdct->ov_size - 1;
if (noOutSamples > nrSamples) {
/* Purge buffered output. */
for (i = 0; i < hMdct->ov_offset; i++) {
*pOut0 = hMdct->overlap.time[i];
pOut0++;
}
nrSamples = hMdct->ov_offset;
hMdct->ov_offset = 0;
}
for (w = 0; w < nSpec; w++) {
FIXP_DBL *pSpec, *pCurr;
const FIXP_WTP *pWindow;
/* Detect FRprevious / FL mismatches and override parameters accordingly */
if (hMdct->prev_fr != fl) {
imdct_adapt_parameters(hMdct, &fl, &nl, tl, wls, noOutSamples);
}
specShiftScale = transform_gain_e;
/* Setup window pointers */
pWindow = hMdct->prev_wrs;
/* Current spectrum */
pSpec = spectrum + w * tl;
/* DCT IV of current spectrum. */
if (currAliasSymmetry == 0) {
if (hMdct->prevAliasSymmetry == 0) {
dct_IV(pSpec, tl, &specShiftScale);
} else {
FIXP_DBL _tmp[1024 + ALIGNMENT_DEFAULT / sizeof(FIXP_DBL)];
FIXP_DBL *tmp = (FIXP_DBL *)ALIGN_PTR(_tmp);
C_ALLOC_ALIGNED_REGISTER(tmp, sizeof(_tmp));
dct_III(pSpec, tmp, tl, &specShiftScale);
C_ALLOC_ALIGNED_UNREGISTER(tmp);
}
} else {
if (hMdct->prevAliasSymmetry == 0) {
FIXP_DBL _tmp[1024 + ALIGNMENT_DEFAULT / sizeof(FIXP_DBL)];
FIXP_DBL *tmp = (FIXP_DBL *)ALIGN_PTR(_tmp);
C_ALLOC_ALIGNED_REGISTER(tmp, sizeof(_tmp));
dst_III(pSpec, tmp, tl, &specShiftScale);
C_ALLOC_ALIGNED_UNREGISTER(tmp);
} else {
dst_IV(pSpec, tl, &specShiftScale);
}
}
/* Optional scaling of time domain - no yet windowed - of current spectrum
*/
/* and de-scale current spectrum signal (time domain, no yet windowed) */
if (gain != (FIXP_DBL)0) {
for (i = 0; i < tl; i++) {
pSpec[i] = fMult(pSpec[i], gain);
}
}
{
int loc_scale =
fixmin_I(scalefactor[w] + specShiftScale, (INT)DFRACT_BITS - 1);
DWORD_ALIGNED(pSpec);
scaleValuesSaturate(pSpec, tl, loc_scale);
}
if (noOutSamples <= nrSamples) {
/* Divert output first half to overlap buffer if we already got enough
* output samples. */
pOut0 = hMdct->overlap.time + hMdct->ov_offset;
hMdct->ov_offset += hMdct->prev_nr + fl / 2;
} else {
/* Account output samples */
nrSamples += hMdct->prev_nr + fl / 2;
}
/* NR output samples 0 .. NR. -overlap[TL/2..TL/2-NR] */
if ((hMdct->pFacZir != 0) && (hMdct->prev_nr == fl / 2)) {
/* In the case of ACELP -> TCX20 -> FD short add FAC ZIR on nr signal part
*/
for (i = 0; i < hMdct->prev_nr; i++) {
FIXP_DBL x = -(*pOvl--);
*pOut0 = fAddSaturate(x, IMDCT_SCALE_DBL(hMdct->pFacZir[i]));
pOut0++;
}
hMdct->pFacZir = NULL;
} else {
/* Here we implement a simplified version of what happens after the this
piece of code (see the comments below). We implement the folding of C and
D segments from (-D-Cr) but D is zero, because in this part of the MDCT
sequence the window coefficients with which D must be multiplied are zero.
"pOut0" writes sequentially the C block from left to right. */
if (hMdct->prevPrevAliasSymmetry == 0) {
for (i = 0; i < hMdct->prev_nr; i++) {
FIXP_DBL x = -(*pOvl--);
*pOut0 = IMDCT_SCALE_DBL(x);
pOut0++;
}
} else {
for (i = 0; i < hMdct->prev_nr; i++) {
FIXP_DBL x = *pOvl--;
*pOut0 = IMDCT_SCALE_DBL(x);
pOut0++;
}
}
}
if (noOutSamples <= nrSamples) {
/* Divert output second half to overlap buffer if we already got enough
* output samples. */
pOut1 = hMdct->overlap.time + hMdct->ov_offset + fl / 2 - 1;
hMdct->ov_offset += fl / 2 + nl;
} else {
pOut1 = pOut0 + (fl - 1);
nrSamples += fl / 2 + nl;
}
/* output samples before window crossing point NR .. TL/2.
* -overlap[TL/2-NR..TL/2-NR-FL/2] + current[NR..TL/2] */
/* output samples after window crossing point TL/2 .. TL/2+FL/2.
* -overlap[0..FL/2] - current[TL/2..FL/2] */
pCurr = pSpec + tl - fl / 2;
DWORD_ALIGNED(pCurr);
C_ALLOC_ALIGNED_REGISTER(pWindow, fl);
DWORD_ALIGNED(pWindow);
C_ALLOC_ALIGNED_UNREGISTER(pWindow);
if (hMdct->prevPrevAliasSymmetry == 0) {
if (hMdct->prevAliasSymmetry == 0) {
if (!hMdct->pAsymOvlp) {
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, -*pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(-x1);
pOut0++;
pOut1--;
}
} else {
FIXP_DBL *pAsymOvl = hMdct->pAsymOvlp + fl / 2 - 1;
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
x1 = -fMultDiv2(*pCurr, pWindow[i].v.re) +
fMultDiv2(*pAsymOvl, pWindow[i].v.im);
x0 = fMultDiv2(*pCurr, pWindow[i].v.im) -
fMultDiv2(*pOvl, pWindow[i].v.re);
pCurr++;
pOvl--;
pAsymOvl--;
*pOut0++ = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1-- = IMDCT_SCALE_DBL_LSH1(x1);
}
hMdct->pAsymOvlp = NULL;
}
} else { /* prevAliasingSymmetry == 1 */
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, -*pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(x1);
pOut0++;
pOut1--;
}
}
} else { /* prevPrevAliasingSymmetry == 1 */
if (hMdct->prevAliasSymmetry == 0) {
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, *pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(-x1);
pOut0++;
pOut1--;
}
} else { /* prevAliasingSymmetry == 1 */
for (i = 0; i < fl / 2; i++) {
FIXP_DBL x0, x1;
cplxMultDiv2(&x1, &x0, *pCurr++, *pOvl--, pWindow[i]);
*pOut0 = IMDCT_SCALE_DBL_LSH1(x0);
*pOut1 = IMDCT_SCALE_DBL_LSH1(x1);
pOut0++;
pOut1--;
}
}
}
if (hMdct->pFacZir != 0) {
/* add FAC ZIR of previous ACELP -> mdct transition */
FIXP_DBL *pOut = pOut0 - fl / 2;
FDK_ASSERT(fl / 2 <= 128);
for (i = 0; i < fl / 2; i++) {
pOut[i] = fAddSaturate(pOut[i], IMDCT_SCALE_DBL(hMdct->pFacZir[i]));
}
hMdct->pFacZir = NULL;
}
pOut0 += (fl / 2) + nl;
/* NL output samples TL/2+FL/2..TL. - current[FL/2..0] */
pOut1 += (fl / 2) + 1;
pCurr = pSpec + tl - fl / 2 - 1;
/* Here we implement a simplified version of what happens above the this
piece of code (see the comments above). We implement the folding of C and D
segments from (C-Dr) but C is zero, because in this part of the MDCT
sequence the window coefficients with which C must be multiplied are zero.
"pOut1" writes sequentially the D block from left to right. */
if (hMdct->prevAliasSymmetry == 0) {
for (i = 0; i < nl; i++) {
FIXP_DBL x = -(*pCurr--);
*pOut1++ = IMDCT_SCALE_DBL(x);
}
} else {
for (i = 0; i < nl; i++) {
FIXP_DBL x = *pCurr--;
*pOut1++ = IMDCT_SCALE_DBL(x);
}
}
/* Set overlap source pointer for next window pOvl = pSpec + tl/2 - 1; */
pOvl = pSpec + tl / 2 - 1;
/* Previous window values. */
hMdct->prev_nr = nr;
hMdct->prev_fr = fr;
hMdct->prev_tl = tl;
hMdct->prev_wrs = wrs;
/* Previous aliasing symmetry */
hMdct->prevPrevAliasSymmetry = hMdct->prevAliasSymmetry;
hMdct->prevAliasSymmetry = currAliasSymmetry;
}
/* Save overlap */
pOvl = hMdct->overlap.freq + hMdct->ov_size - tl / 2;
FDKmemcpy(pOvl, &spectrum[(nSpec - 1) * tl], (tl / 2) * sizeof(FIXP_DBL));
return nrSamples;
}
| 37.04104 | 80 | 0.639879 | Opendigitalradio |
c8660f5f73268d82e6872869b178203676ec77f5 | 31,827 | hpp | C++ | library/cgp/containers/matrix_stack/matrix_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | library/cgp/containers/matrix_stack/matrix_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | 2 | 2022-03-03T16:34:03.000Z | 2022-03-20T13:08:56.000Z | library/cgp/containers/matrix_stack/matrix_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | #pragma once
#include "cgp/base/base.hpp"
#include "cgp/containers/buffer_stack/buffer_stack.hpp"
#include "cgp/containers/offset_grid/offset_grid.hpp"
#include <sstream>
#include <iomanip>
/* ************************************************** */
/* Header */
/* ************************************************** */
namespace cgp
{
/** Container for 2D-matrix structure storing elements on stack (fixed size known at compile time)
*
* Elements of matrix_stack are stored contiguously in stack memory as array of array and remain fully compatible with std::array and pointers.
* Elements are stored along rows
* matrix[0] ( 0:[0,0] 1:[0,1] 2:[0,2] ... N2-1:[0,N2-1] )
* matrix[1] ( N2:[1,0] N2+1:[1,1] ... 2*N2-1:[1,N2-1] )
* ...
* matrix[k1] k1*N2+k2:[k1,k2]
* ...
* matrix[N1-1] ( (N1-1)*N2:[N1-1,0] ... N1*N2-1:[N1-1,N2-1] )
**/
template <typename T, int N1, int N2>
struct matrix_stack
{
/** Internal storage as a 1D buffer */
buffer_stack< buffer_stack<T, N2>, N1> data;
/** Constructors */
matrix_stack();
matrix_stack(buffer_stack< buffer_stack<T, N2>, N1> const& elements);
matrix_stack(buffer_stack<T, N1* N2> const& elements);
// Construct from a matrix with different size.
// Consider the min between (N1,N1_arg) and (N2,N2_arg)
template <int N1_arg, int N2_arg>
explicit matrix_stack(matrix_stack<T, N1_arg, N2_arg> const& M);
matrix_stack(std::initializer_list<T> const& arg);
matrix_stack(std::initializer_list<buffer_stack<T,N1> > const& arg);
static matrix_stack<T, N1, N2> build_identity();
static matrix_stack<T, N1, N2> diagonal(buffer_stack<T, std::min(N1,N2)> const& arg);
/** Total number of elements size = dimension[0] * dimension[1] */
int size() const;
/** Return {N1,N2} */
int2 dimension() const;
/** Fill all elements of the grid_2D with the same element*/
matrix_stack<T, N1, N2>& fill(T const& value);
/** Element access
* Bound checking is performed unless cgp_NO_DEBUG is defined. */
buffer_stack<T, N2> const& operator[](int k1) const;
buffer_stack<T, N2>& operator[](int k1);
buffer_stack<T, N2> const& operator()(int k1) const;
buffer_stack<T, N2>& operator()(int k1);
T const& operator()(int k1, int k2) const;
T& operator()(int k1, int k2);
T const& at_offset(int offset) const;
T& at_offset(int offset);
matrix_stack<T, N1 - 1, N2 - 1> remove_row_column(int k1, int k2) const;
/** Set a block within the matrix from a specific offset
* @block: the matrix to be copied in the current one
* @offset: the offsets where the block has to be writter. Default value are (0,0). The block is written on the top-left corner.
* Conditions:
* offset_1 + N1_arg < N1
* offset_2 + N2_arg < N2
*/
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>& set_block(matrix_stack<T, N1_arg, N2_arg> const& block, int offset_1 = 0, int offset_2 = 0);
/** Iterators
* Iterators compatible with STL syntax and std::array */
T* begin();
T* end();
T const* begin() const;
T const* end() const;
T const* cbegin() const;
T const* cend() const;
inline T const& at(int k1, int k2) const;
inline T& at(int k1, int k2);
T const& at_unsafe(int k1, int k2) const;
T& at_unsafe(int k1, int k2);
buffer_stack<T, N2> const& at_unsafe(int k1) const;
buffer_stack<T, N2>& at_unsafe(int k1);
T const& at_offset_unsafe(int offset) const;
T& at_offset_unsafe(int offset);
};
template <typename T, int N1, int N2> std::string type_str(matrix_stack<T, N1, N2> const&);
/** Display all elements of the buffer.*/
template <typename T, int N1, int N2> std::ostream& operator<<(std::ostream& s, matrix_stack<T, N1, N2> const& v);
/** Convert all elements of the matrix to a string.
* Default behavior: display all elements separated by a space as a 1D buffer
*
* [begin]
* [begin_line] v(0,0) [separator] v(0,1) [separator] ... v(0,N2-1) [end_line]
* [begin_line] v(1,0) [separator] v(1,1) [separator] ... v(1,N2-1) [end_line]
* ...
* [begin_line] v(N1-1,0) [separator] v(N1-1,1) [separator] ... v(N1-1,N2-1) [end_line]
* ...
* [end]
*/
template <typename T, int N1, int N2> std::string str(matrix_stack<T, N1, N2> const& v, std::string const& separator = " ", std::string const& begin = "", std::string const& end = "", std::string const& begin_line="", std::string const& end_line=" ");
/** Convert element of the matrix to a string. Default set for pretty 2D display. */
template <typename T, int N1, int N2> std::string str_pretty(matrix_stack<T, N1, N2> const& M, std::string const& separator=" ", std::string const& begin="", std::string const& end="", std::string const& begin_line="(", std::string const& end_line=")\n");
template <typename T, int N1, int N2> T const* ptr(matrix_stack<T,N1,N2> const& M);
template <typename T, int N1, int N2> int size_in_memory(matrix_stack<T,N1,N2> const& M);
/** Direct compiled-checked access to data */
template <int idx1, int idx2, typename T, int N1, int N2> T const& get(matrix_stack<T, N1, N2> const& data);
template <int idx1, int idx2, typename T, int N1, int N2> T& get(matrix_stack<T, N1, N2>& data);
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2> const& get(matrix_stack<T, N1, N2> const& data);
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2>& get(matrix_stack<T, N1, N2>& data);
template <int offset, typename T, int N1, int N2> T const& get_offset(matrix_stack<T, N1, N2> const& data);
template <int offset, typename T, int N1, int N2> T& get_offset(matrix_stack<T, N1, N2>& data);
/** Equality test between grid_2D */
template <typename Ta, typename Tb, int Na1, int Na2, int Nb1, int Nb2> bool is_equal(matrix_stack<Ta, Na1, Na2> const& a, matrix_stack<Tb, Nb1, Nb2> const& b);
/** Math operators
* Common mathematical operations between buffers, and scalar or element values. */
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(T const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, T const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(T const& a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N> matrix_stack<T, N, N>& operator*=(matrix_stack<T, N, N>& a, matrix_stack<T, N, N> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator*=(matrix_stack<T, N1, N2>& a, float b);
template <typename T, int N1, int N2, int N3> matrix_stack<T, N1, N3> operator*(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N2, N3> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(matrix_stack<T, N1, N2> const& a, float b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(float a, matrix_stack<T, N1, N2> const& b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator/=(matrix_stack<T, N1, N2>& a, float b);
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator/(matrix_stack<T, N1, N2> const& a, float b);
// Unary negation
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& m);
// Componentwise multiplication between two matrices with the same size
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> multiply_componentwise(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b);
// Matrix vector product
template <typename T, int N1, int N2> buffer_stack<T, N1> operator*(matrix_stack<T, N1, N2> const& a, buffer_stack<T, N2> const& b);
/** Transposition of matrix */
template <typename T, int N1, int N2> matrix_stack<T, N2, N1> transpose(matrix_stack<T, N1, N2> const& m);
/** Trace of a square matrix*/
template <typename T, int N> T trace(matrix_stack<T, N, N> const& m);
/** Componentwise norm : sqrt(sum_(i,j) a_ij^2) */
template <typename T, int N1, int N2> T norm(matrix_stack<T,N1,N2> const& m);
}
/* ************************************************** */
/* IMPLEMENTATION */
/* ************************************************** */
namespace cgp
{
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::at(int k1, int k2) const
{
return *(begin() + k2 + N2 * k1);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::at(int k1, int k2)
{
return *(begin() + k2 + N2 * k1);
}
template <typename T, int N1, int N2> T* matrix_stack<T, N1, N2>::begin() { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T* matrix_stack<T, N1, N2>::end() { return &at_unsafe(N1-1, N2-1)+1; }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::begin() const { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::end() const { return &at_unsafe(N1 - 1, N2 - 1) + 1; }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::cbegin() const { return &at_unsafe(0, 0); }
template <typename T, int N1, int N2> T const* matrix_stack<T, N1, N2>::cend() const { return &at_unsafe(N1 - 1, N2 - 1) + 1; }
template <typename T, int N1, int N2> T const& matrix_stack<T, N1, N2>::at_unsafe(int k1, int k2) const { return data.at_unsafe(k1).at_unsafe(k2); }
template <typename T, int N1, int N2> T& matrix_stack<T, N1, N2>::at_unsafe(int k1, int k2) { return data.at_unsafe(k1).at_unsafe(k2); }
template <typename T, int N1, int N2> buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::at_unsafe(int k1) const { return data.at_unsafe(k1); }
template <typename T, int N1, int N2> buffer_stack<T, N2>& matrix_stack<T, N1, N2>::at_unsafe(int k1) { return data.at_unsafe(k1); }
template <typename T, int N1, int N2> T const& matrix_stack<T, N1, N2>::at_offset_unsafe(int offset) const { return begin()[offset];}
template <typename T, int N1, int N2> T& matrix_stack<T, N1, N2>::at_offset_unsafe(int offset) { return begin()[offset]; }
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack()
: data()
{}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(buffer_stack< buffer_stack<T, N2>, N1> const& elements)
:data(elements)
{}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(buffer_stack<T, N1* N2> const& elements)
: data()
{
int counter = 0;
for (int k1 = 0; k1 < N1; ++k1)
for (int k2 = 0; k2 < N2; ++k2) {
at_unsafe(k1, k2) = elements.at_unsafe(counter);
counter++;
}
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(std::initializer_list<T> const& arg)
: data()
{
assert_cgp(arg.size() >= N1 * N2, "Insufficient size to initialize matrix_stack");
auto it_arg = arg.begin();
for (int k1 = 0; k1 < N1; ++k1) {
for (int k2 = 0; k2 < N2; ++k2) {
at_unsafe(k1, k2) = *it_arg;
++it_arg;
}
}
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2>::matrix_stack(std::initializer_list<buffer_stack<T, N1> > const& arg)
:data()
{
assert_cgp(arg.size() >= N1, "Insufficient size to initialize matrix_stack");
auto it_arg = arg.begin();
for (int k1 = 0; k1 < N1; ++k1) {
data.at_unsafe(k1) = *it_arg;
++it_arg;
}
}
template <typename T, int N1, int N2>
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>::matrix_stack(matrix_stack<T, N1_arg, N2_arg> const& M)
:data()
{
int const N1m = std::min(N1, N1_arg);
int const N2m = std::min(N2, N2_arg);
for (int k1 = 0; k1 < N1m; ++k1)
for (int k2 = 0; k2 < N2m; ++k2)
at_unsafe(k1, k2) = M.at_unsafe(k1, k2);
}
template <typename T, int N1, int N2> int matrix_stack<T, N1, N2>::size() const { return N1 * N2; }
template <typename T, int N1, int N2> int2 matrix_stack<T, N1, N2>::dimension() const { return { N1,N2 }; }
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& matrix_stack<T, N1, N2>::fill(T const& value)
{
auto it = begin();
auto const it_end = end();
for (; it != it_end; ++it)
*it = value;
return *this;
}
template <typename T, int N1, int N2>
void check_index_bounds(int index1, int index2, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (index1 < 0 || index2 < 0 || index1 >= N1 || index2 >= N2)
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack(" + str(index1) + "," + str(index2) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (index1 < 0 || index2 < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (N1 == 0 || N2 == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (index1 == N1 || index2 == N2)
{
msg += "\t> Index reached the maximal size of the buffer \n";
msg += "\t> The maximal possible indexes should be (" + str(N1 - 1) + "," + str(N2 - 1) + ") \n";
}
else if (index1 >= N1 || index2 >= N2)
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
void check_index_bounds(int index2, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (index2 < 0 || index2 >= N2)
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack(" + str(index2) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - maximal first index is = (" + str(N2-1) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (index2 < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (N2 == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (index2 == N2)
{
msg += "\t> Index reached the maximal size of the buffer \n";
msg += "\t> The maximal possible indexes should be (" + str(N1 - 1) + "," + str(N2 - 1) + ") \n";
}
else if (index2 >= N2)
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
void check_offset_bounds(int offset, matrix_stack<T, N1, N2> const& data)
{
#ifndef cgp_NO_DEBUG
if (offset < 0 || offset >= N1*N2 )
{
std::string msg = "\n";
msg += "\t> Try to access matrix_stack.at_offset(" + str(offset) + ")\n";
msg += "\t> - matrix_stack has dimension = (" + str(N1) + "," + str(N2) + ")\n";
msg += "\t> - the maximal offset is = (" + str(N1*N2) + ")\n";
msg += "\t> - Type of matrix_stack: " + type_str(data) + "\n";
if (offset < 0)
{
msg += "\t> Buffer cannot be access with negative index.\n";
}
else if (offset == 0)
{
msg += "\t> The buffer is empty, its elements cannot be accessed.\n";
}
else if (offset == N1*N2)
{
msg += "\t> Offset reached the maximal size of the buffer \n";
msg += "\t> The maximal possible offset should be (" + str( N1*N2 - 1) + ") \n";
}
else if (offset >= N1*N2 )
{
msg += "\t> Exceeded buffer dimension \n";
}
msg += "\n\t The function and variable that generated this error can be found in analysis the Call Stack.\n";
error_cgp(msg);
}
#endif
}
template <typename T, int N1, int N2>
buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::operator[](int k1) const {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2>& matrix_stack<T, N1, N2>::operator[](int k1) {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2> const& matrix_stack<T, N1, N2>::operator()(int k1) const {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
buffer_stack<T, N2>& matrix_stack<T, N1, N2>::operator()(int k1) {
check_index_bounds(k1, *this);
return at_unsafe(k1);
}
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::operator()(int k1, int k2) const {
check_index_bounds(k1, k2, *this);
return at_unsafe(k1,k2);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::operator()(int k1, int k2) {
check_index_bounds(k1, k2, *this);
return at_unsafe(k1, k2);
}
template <typename T, int N1, int N2>
T const& matrix_stack<T, N1, N2>::at_offset(int offset) const {
check_offset_bounds(offset, *this);
return at_offset_unsafe(offset);
}
template <typename T, int N1, int N2>
T& matrix_stack<T, N1, N2>::at_offset(int offset) {
check_offset_bounds(offset, *this);
return at_offset_unsafe(offset);
}
template <typename T, int N1, int N2>
template <int N1_arg, int N2_arg>
matrix_stack<T, N1, N2>& matrix_stack<T, N1, N2>::set_block(matrix_stack<T, N1_arg, N2_arg> const& block, int offset_1, int offset_2)
{
static_assert(N1_arg < N1, "Block size is too large for the current matrix");
static_assert(N2_arg < N2, "Block size is too large for the current matrix");
assert_cgp(N1_arg + offset_1 < N1, "Block size exceed current matrix size");
assert_cgp(N2_arg + offset_2 < N2, "Block size exceed current matrix size");
for (int k1 = 0; k1 < N1_arg; ++k1) {
int const idx_1 = k1 + offset_1;
for (int k2 = 0; k2 < N2_arg; ++k2) {
int const idx_2 = k2 + offset_2;
at_unsafe(idx_1, idx_2) = block.at_unsafe(k1, k2);
}
}
return *this;
}
}
namespace cgp
{
template <typename T, int N1, int N2> std::string type_str(matrix_stack<T, N1, N2> const&)
{
return "matrix_stack<" + type_str(T()) + "," + str(N1) + "," + str(N2) + ">";
}
template <typename Ta, typename Tb, int Na1, int Na2, int Nb1, int Nb2> bool is_equal(matrix_stack<Ta, Na1, Na2> const& a, matrix_stack<Tb, Nb1, Nb2> const& b)
{
if (Na1 != Nb1 || Na2 != Nb2)
return false;
return is_equal(a.data, b.data);
}
template <typename T, int N1, int N2> T const* ptr(matrix_stack<T, N1, N2> const& M)
{
return &get<0,0>(M);
}
template <typename T, int N1, int N2> int size_in_memory(matrix_stack<T, N1, N2> const& )
{
return size_in_memory(T{})*N1*N2;
}
template <int idx1, int idx2, typename T, int N1, int N2> T const& get(matrix_stack<T, N1, N2> const& data)
{
static_assert( (idx1 < N1) && (idx2 < N2), "Index too large for matrix_stack access");
return data.at(idx1, idx2);
}
template <int idx1, int idx2, typename T, int N1, int N2> T& get(matrix_stack<T, N1, N2>& data)
{
static_assert((idx1 < N1) && (idx2 < N2), "Index too large for matrix_stack access");
return data.at(idx1, idx2);
}
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2> const& get(matrix_stack<T, N1, N2> const& data)
{
static_assert(idx1<N1, "Index too large for matrix_stack access");
return get<idx1>(data.data);
}
template <int idx1, typename T, int N1, int N2> buffer_stack<T, N2>& get(matrix_stack<T, N1, N2>& data)
{
static_assert(idx1 < N1, "Index too large for matrix_stack access");
return get<idx1>(data.data);
}
template <int offset, typename T, int N1, int N2> T const& get_offset(matrix_stack<T, N1, N2> const& data)
{
static_assert(offset<N1*N2, "Index too large for matrix_stack access");
return data.at_offset_unsafe(offset);
}
template <int offset, typename T, int N1, int N2> T& get_offset(matrix_stack<T, N1, N2>& data)
{
static_assert(offset < N1* N2, "Index too large for matrix_stack access");
return data.at_offset_unsafe(offset);
}
template <typename T, int N1, int N2> std::ostream& operator<<(std::ostream& s, matrix_stack<T, N1, N2> const& v)
{
return s << v.data;
}
template <typename T, int N1, int N2> std::string str(matrix_stack<T, N1, N2> const& v, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
std::string s;
s += begin;
for (int k1 = 0; k1 < N1; ++k1) {
s += begin_line;
for (int k2 = 0; k2 < N2; ++k2) {
s += str(v.at_unsafe(k1, k2));
if ( k2 != N2 - 1)
s += separator;
}
s += end_line;
}
s += end;
return s;
}
template <typename T,int N1, int N2> std::string str_pretty(matrix_stack<T, N1, N2> const& M, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
std::string s;
std::stringstream ss;
ss << begin;
for (int k1 = 0; k1 < N1; ++k1) {
ss << begin_line;
for (int k2 = 0; k2 < N2; ++k2) {
ss <<std::fixed<<std::setprecision(2) << std::setw(7) << M.at(k1,k2);
if ( k2 != N2 - 1 )
ss << separator;
}
ss << end_line;
}
ss << end;
return ss.str();
}
template <typename T, int N1, int N2> std::string str_2D(matrix_stack<T, N1, N2> const& v, std::string const& separator, std::string const& begin, std::string const& end, std::string const& begin_line, std::string const& end_line)
{
return str(v, separator, begin, end, begin_line, end_line);
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b)
{
a.data += b.data;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator+=(matrix_stack<T, N1, N2>& a, T const& b)
{
a.data += b;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data + b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(matrix_stack<T, N1, N2> const& a, T const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data + b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator+(T const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a + b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, matrix_stack<T, N1, N2> const& b)
{
a.data += b.data;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator-=(matrix_stack<T, N1, N2>& a, T const& b)
{
a.data -= b;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data - b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& a, T const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data - b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(T const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a - b.data;
return res;
}
template <typename T, int N> matrix_stack<T, N, N>& operator*=(matrix_stack<T, N, N>& a, matrix_stack<T, N, N> const& b)
{
matrix_stack<T, N, N> res = a * b;
a = res;
return a;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator*=(matrix_stack<T, N1, N2>& a, float b)
{
a.data *= b;
return a;
}
template <typename T, int N1, int N2, int N3> matrix_stack<T, N1, N3> operator*(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N2, N3> const& b)
{
matrix_stack<T, N1, N3> res;
for (int k1 = 0; k1 < N1; ++k1)
{
for (int k3 = 0; k3 < N3; ++k3)
{
T s {};
for (int k2 = 0; k2 < N2; ++k2)
s += a.at(k1, k2) * b.at(k2, k3);
res(k1, k3) = s;
}
}
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(matrix_stack<T, N1, N2> const& a, float b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data * b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator*(float a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a * b.data;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2>& operator/=(matrix_stack<T, N1, N2>& a, float b)
{
a.data /= b;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator/(matrix_stack<T, N1, N2> const& a, float b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data / b;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> operator-(matrix_stack<T, N1, N2> const& m)
{
matrix_stack<T, N1, N2> res = m;
res *= -1.0f;
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N1, N2> multiply_componentwise(matrix_stack<T, N1, N2> const& a, matrix_stack<T, N1, N2> const& b)
{
matrix_stack<T, N1, N2> res;
res.data = a.data * b.data;
return res;
}
template <typename T, int N1, int N2> buffer_stack<T, N1> operator*(matrix_stack<T, N1, N2> const& a, buffer_stack<T, N2> const& b)
{
buffer_stack<T, N1> res = {};
for (int k1 = 0; k1 < N1; ++k1) {
auto& current = res.at_unsafe(k1);
for (int k2 = 0; k2 < N2; ++k2)
current += a.at(k1,k2) * b.at(k2);
res.at_unsafe(k1) = current;
}
return res;
}
template <typename T, int N1, int N2> matrix_stack<T, N2, N1> transpose(matrix_stack<T, N1, N2> const& m)
{
matrix_stack<T, N2, N1> res;
for (int k1 = 0; k1 < N1; ++k1)
for (int k2 = 0; k2 < N2; ++k2)
res(k2, k1) = m(k1, k2);
return res;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1 - 1, N2 - 1> matrix_stack<T, N1, N2>::remove_row_column(int idx1, int idx2) const
{
assert_cgp( (idx1 < N1) && (idx2 < N2), "Incorrect index for removing row and column to matrix");
matrix_stack<T, N1 - 1, N2 - 1> res;
int k1_res = 0;
for (int k1 = 0; k1 < N1; ++k1) {
if (k1 != idx1) {
int k2_res = 0;
for (int k2 = 0; k2 < N2; ++k2) {
if (k2 != idx2){
res.at_unsafe(k1_res, k2_res) = at_unsafe(k1, k2);
++k2_res;
}
}
++k1_res;
}
}
return res;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2> matrix_stack<T, N1, N2>::build_identity()
{
int const N = std::min(N1, N2);
matrix_stack<T, N1, N2> id = {};
for (int k = 0; k < N; ++k)
id.at_unsafe(k, k) = cgp_trait<T>::one();
return id;
}
template <typename T, int N1, int N2>
matrix_stack<T, N1, N2> matrix_stack<T, N1, N2>::diagonal(buffer_stack<T, std::min(N1, N2)> const& arg)
{
int const N = std::min(N1, N2);
matrix_stack<T, N1, N2> m = {};
for (int k = 0; k < N; ++k)
m.at_unsafe(k, k) = arg[k];
return m;
}
template <typename T, int N1, int N2> T norm(matrix_stack<T, N1, N2> const& m)
{
using std::sqrt;
T s{};
for(int k1=0; k1<N1; ++k1)
for(int k2=0; k2<N2; ++k2)
s += m.at_unsafe(k1,k2);
return sqrt(s);
}
template <typename T, int N> T trace(matrix_stack<T, N, N> const& m)
{
T s = {};
for (int k = 0; k < N; ++k)
s += m(k, k);
return s;
}
}
#include "special_types/special_types.hpp" | 39.003676 | 259 | 0.555786 | drohmer |
c8673e69b1470516e7cba61fb507fb0b9ab9d0c6 | 11,923 | cc | C++ | dcmdata/libsrc/dcvrfl.cc | henkdemarie/dicom-dimse-native | a2a5042de8c5de04831baf3de7182ea2eb7b78f8 | [
"MIT"
] | 29 | 2020-02-13T17:40:16.000Z | 2022-03-12T14:58:22.000Z | dcmdata/libsrc/dcvrfl.cc | henkdemarie/dicom-dimse-native | a2a5042de8c5de04831baf3de7182ea2eb7b78f8 | [
"MIT"
] | 20 | 2020-03-20T18:06:31.000Z | 2022-02-25T08:38:08.000Z | dcmdata/libsrc/dcvrfl.cc | henkdemarie/dicom-dimse-native | a2a5042de8c5de04831baf3de7182ea2eb7b78f8 | [
"MIT"
] | 9 | 2020-03-20T17:29:55.000Z | 2022-02-14T10:15:33.000Z | /*
*
* Copyright (C) 1994-2019, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Gerd Ehlers, Andreas Barth
*
* Purpose: Implementation of class DcmFloatingPointSingle
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/dcmdata/dcvrfl.h"
#define INCLUDE_CSTDIO
#define INCLUDE_CSTRING
#include "dcmtk/ofstd/ofstdinc.h"
// ********************************
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmTag &tag)
: DcmElement(tag, 0)
{
}
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmTag &tag,
const Uint32 len)
: DcmElement(tag, len)
{
}
DcmFloatingPointSingle::DcmFloatingPointSingle(const DcmFloatingPointSingle &old)
: DcmElement(old)
{
}
DcmFloatingPointSingle::~DcmFloatingPointSingle()
{
}
DcmFloatingPointSingle &DcmFloatingPointSingle::operator=(const DcmFloatingPointSingle &obj)
{
DcmElement::operator=(obj);
return *this;
}
int DcmFloatingPointSingle::compare(const DcmElement& rhs) const
{
int result = DcmElement::compare(rhs);
if (result != 0)
{
return result;
}
/* cast away constness (dcmdata is not const correct...) */
DcmFloatingPointSingle* myThis = NULL;
DcmFloatingPointSingle* myRhs = NULL;
myThis = OFconst_cast(DcmFloatingPointSingle*, this);
myRhs = OFstatic_cast(DcmFloatingPointSingle*, OFconst_cast(DcmElement*, &rhs));
/* compare number of values */
unsigned long thisNumValues = myThis->getNumberOfValues();
unsigned long rhsNumValues = myRhs->getNumberOfValues();
if (thisNumValues < rhsNumValues)
{
return -1;
}
else if (thisNumValues > rhsNumValues)
{
return 1;
}
// iterate over all components and test equality */
for (unsigned long count = 0; count < thisNumValues; count++)
{
Float32 val = 0;
if (myThis->getFloat32(val, count).good())
{
Float32 rhsVal = 0;
if (myRhs->getFloat32(rhsVal, count).good())
{
if (val > rhsVal)
{
return 1;
}
else if (val < rhsVal)
{
return -1;
}
}
}
}
/* all values as well as VM equal: objects are equal */
return 0;
}
OFCondition DcmFloatingPointSingle::copyFrom(const DcmObject& rhs)
{
if (this != &rhs)
{
if (rhs.ident() != ident()) return EC_IllegalCall;
*this = OFstatic_cast(const DcmFloatingPointSingle &, rhs);
}
return EC_Normal;
}
// ********************************
DcmEVR DcmFloatingPointSingle::ident() const
{
return EVR_FL;
}
OFCondition DcmFloatingPointSingle::checkValue(const OFString &vm,
const OFBool /*oldFormat*/)
{
/* check VM only, further checks on the floating point values could be added later */
return DcmElement::checkVM(getVM(), vm);
}
unsigned long DcmFloatingPointSingle::getVM()
{
return getNumberOfValues();
}
unsigned long DcmFloatingPointSingle::getNumberOfValues()
{
return OFstatic_cast(unsigned long, getLengthField() / sizeof(Float32));
}
// ********************************
void DcmFloatingPointSingle::print(STD_NAMESPACE ostream &out,
const size_t flags,
const int level,
const char * /*pixelFileName*/,
size_t * /*pixelCounter*/)
{
if (valueLoaded())
{
/* get float data */
Float32 *floatVals;
errorFlag = getFloat32Array(floatVals);
if (floatVals != NULL)
{
/* do not use getVM() because derived classes might always return 1 */
const unsigned long count = getNumberOfValues();
/* double-check length field for valid value */
if (count > 0)
{
const unsigned long maxLength = (flags & DCMTypes::PF_shortenLongTagValues) ?
DCM_OptPrintLineLength : OFstatic_cast(unsigned long, -1) /*unlimited*/;
unsigned long printedLength = 0;
unsigned long newLength = 0;
char buffer[64];
/* print line start with tag and VR */
printInfoLineStart(out, flags, level);
/* print multiple values */
for (unsigned int i = 0; i < count; i++, floatVals++)
{
/* check whether first value is printed (omit delimiter) */
if (i == 0)
OFStandard::ftoa(buffer, sizeof(buffer), *floatVals, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
else
{
buffer[0] = '\\';
OFStandard::ftoa(buffer + 1, sizeof(buffer) - 1, *floatVals, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
}
/* check whether current value sticks to the length limit */
newLength = printedLength + OFstatic_cast(unsigned long, strlen(buffer));
if ((newLength <= maxLength) && ((i + 1 == count) || (newLength + 3 <= maxLength)))
{
out << buffer;
printedLength = newLength;
} else {
/* check whether output has been truncated */
if (i + 1 < count)
{
out << "...";
printedLength += 3;
}
break;
}
}
/* print line end with length, VM and tag name */
printInfoLineEnd(out, flags, printedLength);
} else {
/* count can be zero if we have an invalid element with less than four bytes length */
printInfoLine(out, flags, level, "(invalid value)");
}
} else
printInfoLine(out, flags, level, "(no value available)" );
} else
printInfoLine(out, flags, level, "(not loaded)" );
}
// ********************************
OFCondition DcmFloatingPointSingle::getFloat32(Float32 &floatVal,
const unsigned long pos)
{
/* get float data */
Float32 *floatValues = NULL;
errorFlag = getFloat32Array(floatValues);
/* check data before returning */
if (errorFlag.good())
{
if (floatValues == NULL)
errorFlag = EC_IllegalCall;
/* do not use getVM() because derived classes might always return 1 */
else if (pos >= getNumberOfValues())
errorFlag = EC_IllegalParameter;
else
floatVal = floatValues[pos];
}
/* clear value in case of error */
if (errorFlag.bad())
floatVal = 0;
return errorFlag;
}
OFCondition DcmFloatingPointSingle::getFloat32Array(Float32 *&floatVals)
{
floatVals = OFstatic_cast(Float32 *, getValue());
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::getOFString(OFString &value,
const unsigned long pos,
OFBool /*normalize*/)
{
Float32 floatVal;
/* get the specified numeric value */
errorFlag = getFloat32(floatVal, pos);
if (errorFlag.good())
{
/* ... and convert it to a character string */
char buffer[64];
OFStandard::ftoa(buffer, sizeof(buffer), floatVal, 0, 0, 8 /* FLT_DIG + 2 for DICOM FL */);
/* assign result */
value = buffer;
}
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::putFloat32(const Float32 floatVal,
const unsigned long pos)
{
Float32 val = floatVal;
errorFlag = changeValue(&val, OFstatic_cast(Uint32, sizeof(Float32) * pos), OFstatic_cast(Uint32, sizeof(Float32)));
return errorFlag;
}
OFCondition DcmFloatingPointSingle::putFloat32Array(const Float32 *floatVals,
const unsigned long numFloats)
{
errorFlag = EC_Normal;
if (numFloats > 0)
{
/* check for valid float data */
if (floatVals != NULL)
errorFlag = putValue(floatVals, OFstatic_cast(Uint32, sizeof(Float32) * OFstatic_cast(size_t, numFloats)));
else
errorFlag = EC_CorruptedData;
} else
putValue(NULL, 0);
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::putString(const char *stringVal)
{
/* determine length of the string value */
const size_t stringLen = (stringVal != NULL) ? strlen(stringVal) : 0;
/* call the real function */
return putString(stringVal, OFstatic_cast(Uint32, stringLen));
}
OFCondition DcmFloatingPointSingle::putString(const char *stringVal,
const Uint32 stringLen)
{
errorFlag = EC_Normal;
/* determine VM of the string */
const unsigned long vm = DcmElement::determineVM(stringVal, stringLen);
if (vm > 0)
{
Float32 *field = new Float32[vm];
OFBool success = OFFalse;
OFString value;
size_t pos = 0;
/* retrieve float data from character string */
for (unsigned long i = 0; (i < vm) && errorFlag.good(); i++)
{
/* get specified value from multi-valued string */
pos = DcmElement::getValueFromString(stringVal, pos, stringLen, value);
if (!value.empty())
{
field[i] = OFstatic_cast(Float32, OFStandard::atof(value.c_str(), &success));
if (!success)
errorFlag = EC_CorruptedData;
} else
errorFlag = EC_CorruptedData;
}
/* set binary data as the element value */
if (errorFlag.good())
errorFlag = putFloat32Array(field, vm);
/* delete temporary buffer */
delete[] field;
} else
errorFlag = putValue(NULL, 0);
return errorFlag;
}
// ********************************
OFCondition DcmFloatingPointSingle::verify(const OFBool autocorrect)
{
/* check for valid value length */
if (getLengthField() % (sizeof(Float32)) != 0)
{
errorFlag = EC_CorruptedData;
if (autocorrect)
{
/* strip to valid length */
setLengthField(getLengthField() - (getLengthField() % OFstatic_cast(Uint32, sizeof(Float32))));
}
} else
errorFlag = EC_Normal;
return errorFlag;
}
OFBool DcmFloatingPointSingle::matches(const DcmElement& candidate,
const OFBool enableWildCardMatching) const
{
OFstatic_cast(void,enableWildCardMatching);
if (ident() == candidate.ident())
{
// some const casts to call the getter functions, I do not modify the values, I promise!
DcmFloatingPointSingle& key = OFconst_cast(DcmFloatingPointSingle&,*this);
DcmElement& can = OFconst_cast(DcmElement&,candidate);
Float32 a, b;
for( unsigned long ui = 0; ui < key.getVM(); ++ui )
for( unsigned long uj = 0; uj < can.getVM(); ++uj )
if( key.getFloat32( a, ui ).good() && can.getFloat32( b, uj ).good() && a == b )
return OFTrue;
return key.getVM() == 0;
}
return OFFalse;
}
| 29.8075 | 125 | 0.551875 | henkdemarie |
c8685f738a8597338659385fc01ab15ffc2ee898 | 4,561 | cpp | C++ | Types/DateTime/GpDateTimeOps.cpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | null | null | null | Types/DateTime/GpDateTimeOps.cpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 1 | 2020-06-19T18:38:40.000Z | 2020-06-19T18:38:40.000Z | Types/DateTime/GpDateTimeOps.cpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 6 | 2020-06-04T07:32:59.000Z | 2021-05-17T15:41:30.000Z | #include "GpDateTimeOps.hpp"
#if defined(GP_USE_DATE_TIME)
#include <date/date.h> //TODO: remove with c++20
namespace GPlatform {
const microseconds_t GpDateTimeOps::sStartSteadyTS = GpDateTimeOps::SSteadyTS_us();
const GpArray<std::string, GpDateTimeFormat::SCount().As<size_t>()> GpDateTimeOps::sFormats =
{
"%FT%X+00:00", //ISO_8601: 2021-01-11T20:15:31+00:00
"%a, %d %b %Y %X +0000", //RFC_2822: Mon, 11 Jan 2021 20:15:31 +0000
"%F %X", //STD_DATE_TIME: 2021-01-11 20:15:31
"%FT%X", //STD_DATE_TIME_T,//2021-01-11T20:15:31
"%F", //STD_DATE: 2021-01-11
"%X" //STD_TIME: 20:15:31
};
unix_ts_ms_t GpDateTimeOps::SUnixTS_ms (void) noexcept
{
const auto val = std::chrono::system_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return unix_ts_ms_t::SMake(cnt);
}
unix_ts_s_t GpDateTimeOps::SUnixTS_s (void) noexcept
{
return SUnixTS_ms();
}
unix_ts_ms_t GpDateTimeOps::SUnixTsFromStr_ms
(
GpRawPtrCharR aStr,
std::string_view aFormat
)
{
std::istringstream in{std::string(aStr.AsStringView())};
date::sys_time<std::chrono::milliseconds> tp;
in >> date::parse(std::string(aFormat), tp);
const auto val = tp.time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return unix_ts_ms_t::SMake(cnt);
}
unix_ts_s_t GpDateTimeOps::SUnixTsFromStr_s
(
GpRawPtrCharR aStr,
std::string_view aFormat
)
{
return SUnixTsFromStr_ms(aStr, aFormat);
}
unix_ts_ms_t GpDateTimeOps::SUnixTsFromStr_ms
(
GpRawPtrCharR aStr,
FormatTE aFormat
)
{
return SUnixTsFromStr_ms(aStr, sFormats.at(aFormat));
}
unix_ts_s_t GpDateTimeOps::SUnixTsFromStr_s
(
GpRawPtrCharR aStr,
FormatTE aFormat
)
{
return SUnixTsFromStr_ms(aStr, sFormats.at(aFormat));
}
/*std::chrono::hh_mm_ss GpDateTimeOps::SUnixTsToHH_MM_SS (const unix_ts_ms_t aTs) noexcept
{
?
}*/
/*hours_t GpDateTimeOps::SUnixTsToHH (const unix_ts_ms_t aTs) noexcept
{
date::sys_time<std::chrono::milliseconds> tp(std::chrono::milliseconds(aTs.Value()));
date::hh_mm_ss h(tp.time_since_epoch());
return hours_t::SMake(h.hours().count());
}*/
microseconds_t GpDateTimeOps::SSteadyTS_us (void) noexcept
{
const auto val = std::chrono::steady_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::microseconds>(val).count();
return microseconds_t::SMake(microseconds_t::value_type(cnt));
}
milliseconds_t GpDateTimeOps::SSteadyTS_ms (void) noexcept
{
const auto val = std::chrono::steady_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::milliseconds>(val).count();
return milliseconds_t::SMake(milliseconds_t::value_type(cnt));
}
seconds_t GpDateTimeOps::SSteadyTS_s (void) noexcept
{
return SSteadyTS_ms();
}
microseconds_t GpDateTimeOps::SHighResTS_us (void) noexcept
{
const auto val = std::chrono::high_resolution_clock::now().time_since_epoch();
const auto cnt = std::chrono::duration_cast<std::chrono::microseconds>(val).count();
return microseconds_t::SMake(microseconds_t::value_type(cnt));
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_ms_t aTs,
std::string_view aFormat
)
{
std::ostringstream out;
//https://howardhinnant.github.io/date/date.html
//https://gitter.im/HowardHinnant/date?at=5e404b1fb612cc7bb1588132
date::sys_time<std::chrono::milliseconds> tp(std::chrono::milliseconds(aTs.Value()));
out << date::format(std::string(aFormat), tp);
return out.str();
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_s_t aTs,
std::string_view aFormat
)
{
return SUnixTsToStr(aTs.As<unix_ts_ms_t>(), aFormat);
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_ms_t aTs,
const FormatTE aFormat
)
{
return SUnixTsToStr(aTs, sFormats.at(aFormat));
}
std::string GpDateTimeOps::SUnixTsToStr
(
const unix_ts_s_t aTs,
const FormatTE aFormat
)
{
return SUnixTsToStr(aTs.As<unix_ts_ms_t>(), sFormats.at(aFormat));
}
}//GPlatform
#endif//#if defined(GP_USE_DATE_TIME)
| 27.14881 | 94 | 0.653804 | ITBear |
c86b31acbddd68eea5aa5ebc1869399eeee3936a | 8,337 | cpp | C++ | SpaceShooter/src/Game/IA_Behavior/Behaviors.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/IA_Behavior/Behaviors.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | SpaceShooter/src/Game/IA_Behavior/Behaviors.cpp | tomasmartinsantos/SpaceShooter | 2d930cd9061ca7dbb8f00386cb26ead902f69eff | [
"Apache-2.0"
] | null | null | null | #include "../World.h"
#include "../../Engine/Math.h"
#include "../Components/CBrain.h"
#include "../Entities/HeadersEntities.h"
#include "../Components/CWeapon.h"
#include "../UI/WLifebar.h"
#include "../Components/CAnimation.h"
#include "../../Engine/Audio/Audiosource.h"
#include "../Scene.h"
#include "Behaviors.h"
/* BEHAVIORS */
// ATTACK
Ptr<Attack> Attack::Create(Ptr<CBrain> BrainComponent)
{
return new Attack(BrainComponent);
}
Attack::Attack(Ptr<CBrain> BrainComponent)
{
mOwnerBrain = BrainComponent;
mStatus = eInvalid;
}
Attack::~Attack()
{
mOwnerBrain = nullptr;
}
Status Attack::Update(float Step)
{
// Try to attack with the secondary weapon (more powerful)
// If not, then try to attack with the primary weapon
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr)
{
if (mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp() != nullptr && !mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp()->IsWeaponInCooldown())
{
mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetSecondaryWeaponComp()->Fire(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetProjectileSpawnPos(), mOwnerBrain->GetMyEntity()->GetRotation());
return eSuccess;
}
else if(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp() != nullptr && !mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp()->IsWeaponInCooldown())
{
mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetPrimaryWeaponComp()->Fire(mOwnerBrain->GetMyEntity().DownCast<EShip>()->GetProjectileSpawnPos(), mOwnerBrain->GetMyEntity()->GetRotation());
return eSuccess;
}
else
return eFail;
}
else
{
// Weapon in Cooldown
return eFail;
}
return eInvalid;
}
// MOVEMENT
Ptr<WantToMove> WantToMove::Create(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
return new WantToMove(BrainComponent, TargetReachedRadius);
}
WantToMove::WantToMove(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
mOwnerBrain = BrainComponent;
mTargetReachedRadius = TargetReachedRadius;
mStatus = eInvalid;
}
WantToMove::~WantToMove()
{
mOwnerBrain = nullptr;
}
Status WantToMove::Update(float Step)
{
// Only move if not inside the acceptance radius
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
if (SqrDistance(mOwnerBrain->GetMyEntity()->GetPosition(), mOwnerBrain->GetTargetPosition(false)) <= powf(mTargetReachedRadius, 2))
return eFail;
else
return eSuccess;
}
return eInvalid;
}
Ptr<MoveToTarget> MoveToTarget::Create(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
return new MoveToTarget(BrainComponent, TargetReachedRadius);
}
MoveToTarget::MoveToTarget(Ptr<CBrain> BrainComponent, float TargetReachedRadius)
{
mOwnerBrain = BrainComponent;
mTargetReachedRadius = TargetReachedRadius;
mStatus = eInvalid;
mAbortBehaviorTimer = 10.0f;
}
MoveToTarget::~MoveToTarget()
{
mOwnerBrain = nullptr;
}
Status MoveToTarget::Update(float Step)
{
if (mOwnerBrain != nullptr)
{
// In case the MoveTo behavior went wrong, abort it
if (mContAbortBehaviorTimer >= mAbortBehaviorTimer)
{
mOwnerBrain->SelectNewTargetPosition();
return eInvalid;
}
else if (World::IsEntityValid(mOwnerBrain->GetMyEntity()) && mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
// Check if entity is inside the acceptance radius
if (SqrDistance(mOwnerBrain->GetMyEntity()->GetPosition(), mOwnerBrain->GetTargetPosition(false)) <= powf(mTargetReachedRadius, 2))
{
// If inside acceptance radius, activate the linear inertia to decelerate
if (!mOwnerBrain->GetAILinearInertiaActivated())
{
mOwnerBrain->SetAILinearInertiaActivated(true);
mOwnerBrain->GetMyEntity()->ActivateLinearInertia();
}
return eSuccess;
}
else
{
// Set a linear steering on forward vector
mOwnerBrain->SetAILinearInertiaActivated(false);
mOwnerBrain->GetMyEntity()->DeactivateLinearInertia();
mOwnerBrain->GetMyEntity()->SetLinearSteering(vec2(mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetMyEntity()->GetMaxLinearAcc(), mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetMyEntity()->GetMaxLinearAcc()));
return eRunning;
}
}
}
return eInvalid;
}
// TARGETING
Ptr<RotateToTarget> RotateToTarget::Create(Ptr<CBrain> BrainComponent, bool TargetingOpponent, float TargetReachedValue)
{
return new RotateToTarget(BrainComponent, TargetingOpponent, TargetReachedValue);
}
RotateToTarget::RotateToTarget(Ptr<CBrain> BrainComponent, bool TargetingOpponent, float TargetReachedValue)
{
mOwnerBrain = BrainComponent;
mTargetReachedValue = TargetReachedValue;
mStatus = eInvalid;
mTargetingOpponent = TargetingOpponent;
}
RotateToTarget::~RotateToTarget()
{
mOwnerBrain = nullptr;
}
Status RotateToTarget::Update(float Step)
{
if (mTargetingOpponent && !World::IsEntityValid(mOwnerBrain->GetMyOpponent().UpCast<Entity>()))
{
return eInvalid;
}
if (mOwnerBrain != nullptr && World::IsEntityValid(mOwnerBrain->GetMyEntity()))
{
if (mOwnerBrain->GetMyEntity().DownCast<EShip>() != nullptr && mOwnerBrain->GetMyEntity().DownCast<EShip>()->IsMovementControllerActivated())
{
if (mOwnerBrain->GetNormDirectionToTarget(mTargetingOpponent) > 0)
{
// Calculate the angle from entity to target
float NewAngle = DegACos(mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).x + mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).y);
if (NewAngle < mTargetReachedValue)
{
// If angle is minor acceptance value, activate angular inertia
mOwnerBrain->GetMyEntity()->SetAngularSteering(0.0f);
if (!mOwnerBrain->GetAIAngularInertiaActivated())
{
mOwnerBrain->SetAIAngularInertiaActivated(true);
mOwnerBrain->GetMyEntity()->ActivateAngularInertia();
}
return eSuccess;
}
else
{
// In case the entity has to turn, first get the turn direction (left/right) and then set an angular steering
float CrossProd = mOwnerBrain->GetMyEntity()->GetForwardVector().x * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).y - mOwnerBrain->GetMyEntity()->GetForwardVector().y * mOwnerBrain->GetDirectionToTarget(mTargetingOpponent).x;
int8 TurnDirection = 1;
if (CrossProd > 0)
TurnDirection = -1;
mOwnerBrain->GetMyEntity()->SetTurnDirection(TurnDirection);
mOwnerBrain->GetMyEntity()->DeactivateAngularInertia();
mOwnerBrain->SetAIAngularInertiaActivated(false);
mOwnerBrain->GetMyEntity()->SetAngularSteering(TurnDirection * mOwnerBrain->GetMyEntity()->GetMaxAngularAcc());
return eRunning;
}
}
}
}
return eInvalid;
}
// IDLE
Ptr<Idle> Idle::Create(Ptr<CBrain> BrainComponent)
{
return new Idle(BrainComponent);
}
Idle::Idle(Ptr<CBrain> BrainComponent)
{
mOwnerBrain = BrainComponent;
mStatus = eInvalid;
}
Idle::~Idle()
{
mOwnerBrain = nullptr;
}
Status Idle::Update(float Step)
{
return eSuccess;
} | 36.565789 | 264 | 0.652993 | tomasmartinsantos |
c86f426648f07506a6a67907139bdbc0b35cc4de | 2,242 | cpp | C++ | add-ons/LoadAddon/effectpal.cpp | return/BeOSSampleCode | ca5a319fecf425a69e944f3c928a85011563a932 | [
"BSD-3-Clause"
] | 5 | 2018-09-09T21:01:57.000Z | 2022-03-27T10:01:27.000Z | add-ons/LoadAddon/effectpal.cpp | return/BeOSSampleCode | ca5a319fecf425a69e944f3c928a85011563a932 | [
"BSD-3-Clause"
] | null | null | null | add-ons/LoadAddon/effectpal.cpp | return/BeOSSampleCode | ca5a319fecf425a69e944f3c928a85011563a932 | [
"BSD-3-Clause"
] | 5 | 2018-04-03T01:45:23.000Z | 2021-05-14T08:23:01.000Z | //****************************************
//effectpal.cpp
//****************************************
/*
Copyright 1999, Be Incorporated. All Rights Reserved.
This file may be used under the terms of the Be Sample Code License.
*/
#include <image.h>
#include "effectpal.h"
#include "effect.h"
#include <Application.h>
#include <Roster.h>
#include <Path.h>
#include <Directory.h>
#include <stdio.h>
//****************************************
//EffectPal class functions
//constructor
EffectPal::EffectPal( BRect frame, const char *title, window_type type, uint32 flags,
uint32 workspaces )
: BWindow( frame, title, type, flags, workspaces )
{
}
//destructor
EffectPal::~EffectPal()
{
}
//Init
void EffectPal::Init( void )
{
image_id addonId;
status_t err = B_NO_ERROR;
Effect* peffect = NULL;
BPoint point(0,0), apoint;
Effect* (*NewEffect)( image_id ); //addon function prototype
app_info info;
BPath path;
//look in app directory for effects
be_app->GetAppInfo(&info);
BEntry entry(&info.ref);
entry.GetPath(&path);
path.GetParent(&path);
path.Append("Effects");
BDirectory dir( path.Path() );
//load all effects
while( err == B_NO_ERROR ){
err = dir.GetNextEntry( (BEntry*)&entry, TRUE );
if( entry.InitCheck() != B_NO_ERROR ){
break;
}
if( entry.GetPath(&path) != B_NO_ERROR ){
printf( "entry.GetPath failed\n" );
}else{
addonId = load_add_on( path.Path() );
if( addonId < 0 ){
printf( "load_add_on( %s ) failed\n", path.Path() );
}else{
printf( "load_add_on( %s ) successful!\n", path.Path() );
if( get_image_symbol( addonId,
"NewEffect",
B_SYMBOL_TYPE_TEXT,
(void **)&NewEffect) ){
printf( "get_image_symbol( NewEffect ) failed\n" );
unload_add_on( addonId );
}else{
peffect = (*NewEffect)( addonId );
if( !peffect ){
printf( "failed to create new effect\n" );
}else{
peffect->Init( this, point );
peffect->GetButtonSize( (BPoint*) &apoint );
point.y += apoint.y;
}
}
}
}
}
}
bool EffectPal::QuitRequested()
{
be_app->PostMessage(B_QUIT_REQUESTED);
return(true);
}
//**************************************** | 23.6 | 86 | 0.580285 | return |
c87018479ea0e7ad5f24d2419ea20054944c83ca | 13,270 | cpp | C++ | accera/transforms/src/value/ValueFuncToTargetPass.cpp | lisaong/Accera | 56967249356ab2fefd80baebf5ac259e958a7dbd | [
"MIT"
] | null | null | null | accera/transforms/src/value/ValueFuncToTargetPass.cpp | lisaong/Accera | 56967249356ab2fefd80baebf5ac259e958a7dbd | [
"MIT"
] | null | null | null | accera/transforms/src/value/ValueFuncToTargetPass.cpp | lisaong/Accera | 56967249356ab2fefd80baebf5ac259e958a7dbd | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
// Authors: Kern Handa
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "AcceraPasses.h"
#include <ir/include/IRUtil.h>
#include <ir/include/value/ValueDialect.h>
#include <mlir/IR/Location.h>
#include <value/include/MLIREmitterContext.h>
#include <mlir/Analysis/LoopAnalysis.h>
#include <mlir/Dialect/Affine/IR/AffineOps.h>
#include <mlir/Dialect/GPU/GPUDialect.h>
#include <mlir/Dialect/Linalg/IR/LinalgOps.h>
#include <mlir/Dialect/SPIRV/IR/SPIRVDialect.h>
#include <mlir/Dialect/SPIRV/IR/SPIRVOps.h>
#include <mlir/Dialect/SPIRV/IR/TargetAndABI.h>
#include <mlir/Dialect/StandardOps/IR/Ops.h>
#include <mlir/Pass/Pass.h>
#include <mlir/Pass/PassManager.h>
#include <mlir/Transforms/GreedyPatternRewriteDriver.h>
#include <mlir/Transforms/LoopUtils.h>
#include <mlir/Transforms/RegionUtils.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/SetVector.h>
#include <llvm/ADT/TypeSwitch.h>
#include <llvm/Support/FormatVariadic.h>
#include <cassert>
#include <memory>
using namespace mlir;
namespace ir = accera::ir;
namespace utilir = accera::ir::util;
namespace vir = accera::ir::value;
namespace tr = accera::transforms;
namespace vtr = accera::transforms::value;
namespace
{
void HoistOpToParentAffineScope(Operation* op)
{
Operation* parentOp = op->getParentOp();
assert(parentOp != nullptr && "Can only hoist an op that has a parent op");
if (!parentOp->hasTrait<OpTrait::AffineScope>())
{
auto affineScopeParent = op->getParentWithTrait<OpTrait::AffineScope>();
auto& firstRegion = affineScopeParent->getRegion(0);
auto& firstBlock = firstRegion.front();
op->moveBefore(&firstBlock, firstBlock.begin());
}
}
void HoistGPUBlockThreadIds(vir::ValueModuleOp vModule)
{
// Hoist GPU block and thread ID ops to the top of the parent AffineScope (e.g. a mlir::FuncOp or a value::LambdaOp)
// this enables the block and thread ID's to be used with Affine ops, as they
// are index types that are defined in the top level of an AffineScope.
// This is safe because the value of the block and thread IDs don't change based
// on their position in the graph within an AffineScope
vModule.walk([](mlir::gpu::ThreadIdOp op) {
HoistOpToParentAffineScope(op.getOperation());
});
vModule.walk([](mlir::gpu::BlockIdOp op) {
HoistOpToParentAffineScope(op.getOperation());
});
}
constexpr auto kDefaultExecutionTarget = vir::ExecutionTarget::CPU;
constexpr size_t kLaunchConfigNumDims = 6;
struct ValueFuncToTargetPass : public tr::ValueFuncToTargetBase<ValueFuncToTargetPass>
{
void runOnOperation() final
{
auto module = getOperation();
auto context = module.getContext();
for (auto vModule : make_early_inc_range(module.getOps<vir::ValueModuleOp>()))
{
{
OwningRewritePatternList patterns(context);
vtr::populateValueLambdaToFuncPatterns(context, patterns);
(void)applyPatternsAndFoldGreedily(vModule, std::move(patterns));
}
{
OwningRewritePatternList patterns(context);
vtr::populateValueLaunchFuncInlinerPatterns(context, patterns);
(void)applyPatternsAndFoldGreedily(vModule, std::move(patterns));
}
{
OwningRewritePatternList patterns(context);
vtr::populateValueFuncToTargetPatterns(context, patterns);
(void)applyPatternsAndFoldGreedily(vModule, std::move(patterns));
}
HoistGPUBlockThreadIds(vModule);
}
module.walk([&](AffineForOp op) {
if (op->getAttrOfType<UnitAttr>("accv_unrolled"))
{
auto tripCount = mlir::getConstantTripCount(op);
if (tripCount && *tripCount >= 1)
(void)mlir::loopUnrollFull(op);
}
else if (auto jammed = op->getAttrOfType<IntegerAttr>("accv_unroll_jam"))
{
(void)mlir::loopUnrollJamByFactor(op, (uint64_t)jammed.getInt());
}
else
{
(void)mlir::promoteIfSingleIteration(op);
}
});
}
};
struct ValueReturnOpConversion : OpRewritePattern<vir::ReturnOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(
vir::ReturnOp returnOp,
PatternRewriter& rewriter) const override
{
auto operands = returnOp.operands();
rewriter.replaceOpWithNewOp<mlir::ReturnOp>(returnOp, operands);
return success();
}
};
struct ValueFuncToTargetPattern : OpRewritePattern<vir::ValueFuncOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(
vir::ValueFuncOp funcOp,
PatternRewriter& rewriter) const override
{
auto loc = rewriter.getFusedLoc({ funcOp.getLoc(), accera::ir::util::GetLocation(rewriter, __FILE__, __LINE__) });
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPoint(funcOp);
[[maybe_unused]] auto target = funcOp.exec_target();
auto newFuncName = funcOp.sym_name().str();
auto newFuncOp = rewriter.create<mlir::FuncOp>(
loc, newFuncName, funcOp.getType());
newFuncOp.setVisibility(funcOp.getVisibility());
if (!funcOp->getAttr("external"))
{
Region& newBody = newFuncOp.getBody();
rewriter.inlineRegionBefore(funcOp.getBody(), newBody, newBody.begin());
}
// Carry forward attributes
newFuncOp->setAttrs(funcOp->getAttrs());
if (funcOp->getAttr(accera::ir::NoInlineAttrName))
{
newFuncOp->setAttr("passthrough", rewriter.getArrayAttr({ rewriter.getStringAttr("noinline") }));
}
rewriter.eraseOp(funcOp);
return success();
}
};
struct ValueLambdaRewritePattern : mlir::OpRewritePattern<vir::ValueLambdaOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult match(vir::ValueLambdaOp op) const final
{
auto lambdaFound = false;
op.body().walk([&](vir::ValueLambdaOp) { lambdaFound = true; return WalkResult::interrupt(); });
return success(!lambdaFound);
}
void rewrite(vir::ValueLambdaOp op, PatternRewriter& rewriter) const final
{
// get a list of all values used in the lambda that come from above
llvm::SetVector<Value> valuesDefinedAbove;
getUsedValuesDefinedAbove(op.body(), valuesDefinedAbove);
llvm::SmallVector<Operation*, 8> constants;
llvm::SmallVector<Value, 4> capturedValues;
// This could be a std::partition, but mlir::Value doesn't have swap defined and idk how to work with their
// non-owning lists yet
for (const Value& v : valuesDefinedAbove)
{
if (auto constantOp = v.getDefiningOp(); constantOp && constantOp->hasTrait<mlir::OpTrait::ConstantLike>())
{
constants.push_back(constantOp);
}
else
{
capturedValues.push_back(v);
}
}
// the new function will take all the args that the lambda took, plus all the implicitly captured values
auto argTypes = llvm::to_vector<4>(op.getArgumentTypes());
auto capturedValueTypes = mlir::ValueRange{ capturedValues }.getTypes();
argTypes.append(capturedValueTypes.begin(), capturedValueTypes.end());
// TODO: maybe support return types with lambdas
auto fnType = rewriter.getFunctionType(argTypes, llvm::None);
auto vFuncOp = [&] {
auto vModuleOp = utilir::CastOrGetParentOfType<vir::ValueModuleOp>(op);
assert(vModuleOp);
OpBuilder::InsertionGuard guard(rewriter);
rewriter.restoreInsertionPoint(utilir::GetTerminalInsertPoint<vir::ValueModuleOp, vir::ModuleTerminatorOp>(vModuleOp));
auto loc = accera::ir::util::GetLocation(rewriter, __FILE__, __LINE__);
vir::ValueFuncOp vFuncOp = rewriter.create<vir::ValueFuncOp>(loc, op.sym_name(), fnType, op.exec_target());
vFuncOp.setPrivate();
return vFuncOp;
}();
auto& bodyBlock = vFuncOp.front();
auto funcArgs = ValueRange{ vFuncOp.getArguments() };
{
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPoint(&bodyBlock, bodyBlock.end());
BlockAndValueMapping valueMapper;
for (auto [fromValue, toValue] : llvm::zip(op.args(), funcArgs.take_front(op.args().size())))
{
if (!valueMapper.contains(fromValue))
valueMapper.map(fromValue, toValue);
}
for (auto [fromValue, toValue] : llvm::zip(capturedValues, funcArgs.drop_front(op.args().size())))
{
if (!valueMapper.contains(fromValue))
valueMapper.map(fromValue, toValue);
}
for (Operation* constant : constants)
{
rewriter.clone(*constant, valueMapper);
}
rewriter.cloneRegionBefore(op.body(), vFuncOp.body(), vFuncOp.body().end(), valueMapper);
rewriter.mergeBlocks(&vFuncOp.back(), &vFuncOp.front(), vFuncOp.front().getArguments().take_front(vFuncOp.back().getNumArguments()));
}
vFuncOp.setType(rewriter.getFunctionType(vFuncOp.front().getArgumentTypes(), llvm::None));
auto args = llvm::to_vector<4>(op.args());
args.append(capturedValues.begin(), capturedValues.end());
[[maybe_unused]] auto launchFuncOp = rewriter.create<vir::LaunchFuncOp>(accera::ir::util::GetLocation(rewriter, __FILE__, __LINE__), vFuncOp, args);
if (auto launchAttr = op->getAttr(vir::ValueFuncOp::getGPULaunchAttrName()))
{
launchFuncOp->setAttr(vir::ValueFuncOp::getGPULaunchAttrName(), launchAttr);
vFuncOp->setAttr(vir::ValueFuncOp::getGPULaunchAttrName(), launchAttr);
}
rewriter.eraseOp(op);
}
};
struct ValueLaunchFuncOpInlinerPattern : OpRewritePattern<vir::LaunchFuncOp>
{
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(vir::LaunchFuncOp op, PatternRewriter& rewriter) const final
{
auto target = op.exec_targetAttr();
auto callee = op.callee().getLeafReference();
auto parentFnOp = op->getParentWithTrait<mlir::OpTrait::FunctionLike>();
if (parentFnOp->getAttr(ir::RawPointerAPIAttrName))
{
// Don't inline calls from RawPointerAPI functions
return failure();
}
if (auto attr = parentFnOp->getAttrOfType<vir::ExecutionTargetAttr>(vir::ValueFuncOp::getExecTargetAttrName());
attr && target == attr)
{
auto callInterface = mlir::dyn_cast<mlir::CallOpInterface>(op.getOperation());
auto callable = callInterface.resolveCallable();
if (!callable)
{
callable = mlir::SymbolTable::lookupNearestSymbolFrom(parentFnOp->getParentOp(), callee);
}
assert(llvm::isa<vir::ValueFuncOp>(callable) || llvm::isa<vir::ValueLambdaOp>(callable));
if (callable->getAttr("external"))
{
return failure();
}
if (callable->getAttr(ir::NoInlineAttrName))
{
return failure();
}
auto& body = callable->getRegion(0);
mlir::BlockAndValueMapping mapping;
for (auto [src, dst] : llvm::zip(body.front().getArguments(), op.getOperands()))
{
mapping.map(src, dst);
}
for (auto& bodyOp : body.front().without_terminator())
{
rewriter.clone(bodyOp, mapping);
}
rewriter.eraseOp(op);
return success();
}
return failure();
}
};
} // namespace
namespace accera::transforms::value
{
void populateValueFuncToTargetPatterns(mlir::MLIRContext* context, mlir::OwningRewritePatternList& patterns)
{
uint16_t benefit = 1;
patterns.insert<ValueReturnOpConversion>(context, benefit++);
patterns.insert<ValueFuncToTargetPattern>(context, benefit++);
}
void populateValueLambdaToFuncPatterns(mlir::MLIRContext* context, mlir::OwningRewritePatternList& patterns)
{
uint16_t benefit = 1;
patterns.insert<ValueLambdaRewritePattern>(context, benefit++);
}
void populateValueLaunchFuncInlinerPatterns(mlir::MLIRContext* context, mlir::OwningRewritePatternList& patterns)
{
uint16_t benefit = 1;
patterns.insert<ValueLaunchFuncOpInlinerPattern>(context, benefit++);
}
std::unique_ptr<mlir::OperationPass<mlir::ModuleOp>> createValueFuncToTargetPass()
{
return std::make_unique<ValueFuncToTargetPass>();
}
} // namespace accera::transforms::value
| 37.485876 | 156 | 0.634514 | lisaong |
c870b77356794e2faacd3ee5e6fb9dec8a4080d0 | 302 | cpp | C++ | Image Processing/imageProcessingLab/read image.cpp | himansurathi/labCourseWork | d0a5afb4445bcfe11865fab6370fab8ce74d54d5 | [
"MIT"
] | null | null | null | Image Processing/imageProcessingLab/read image.cpp | himansurathi/labCourseWork | d0a5afb4445bcfe11865fab6370fab8ce74d54d5 | [
"MIT"
] | null | null | null | Image Processing/imageProcessingLab/read image.cpp | himansurathi/labCourseWork | d0a5afb4445bcfe11865fab6370fab8ce74d54d5 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <opencv2/opencv.hpp>
#include "headerfile.h"
using namespace cv;
bool readImage(char *img,Mat &image){
image = imread(img, CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
printf( "Could not open or find the image\n" );
return false;
}
return true;
}
| 18.875 | 51 | 0.649007 | himansurathi |
c872e430fe26113b027e010d5cedda4416119a14 | 492 | cpp | C++ | src/zxing/zxing/oned/rss/expanded/decoders/AI01320xDecoder.cpp | spompelio/qzxing | cfc728583b867e157bd27e8b7c239c05a081e562 | [
"Apache-2.0"
] | 608 | 2015-02-21T22:31:37.000Z | 2022-03-31T05:05:36.000Z | src/zxing/zxing/oned/rss/expanded/decoders/AI01320xDecoder.cpp | wqsemc/qzxing | f0a78867d697fd271528007c7b4c67e8fce75f90 | [
"Apache-2.0"
] | 512 | 2015-01-06T17:59:31.000Z | 2022-03-31T13:21:49.000Z | src/zxing/zxing/oned/rss/expanded/decoders/AI01320xDecoder.cpp | wqsemc/qzxing | f0a78867d697fd271528007c7b4c67e8fce75f90 | [
"Apache-2.0"
] | 114 | 2015-01-17T14:32:52.000Z | 2022-03-20T13:14:07.000Z | #include "AI01320xDecoder.h"
namespace zxing {
namespace oned {
namespace rss {
AI01320xDecoder::AI01320xDecoder(Ref<BitArray> information)
: AI013x0xDecoder(information)
{
}
void AI01320xDecoder::addWeightCode(String &buf, int weight)
{
if (weight < 10000) {
buf.append("(3202)");
} else {
buf.append("(3203)");
}
}
int AI01320xDecoder::checkWeight(int weight)
{
if (weight < 10000) {
return weight;
}
return weight - 10000;
}
}
}
}
| 14.909091 | 60 | 0.636179 | spompelio |
c873c2e80b0db915cdd2a7e51e677fe35ea12e47 | 532 | cpp | C++ | algorithm-challenges/baekjoon-online-judge/challenges/1000/1292.cpp | nbsp1221/algorithm | a227bbc7cf43dbf2cadc8d47052b9a92875dfa77 | [
"MIT"
] | null | null | null | algorithm-challenges/baekjoon-online-judge/challenges/1000/1292.cpp | nbsp1221/algorithm | a227bbc7cf43dbf2cadc8d47052b9a92875dfa77 | [
"MIT"
] | null | null | null | algorithm-challenges/baekjoon-online-judge/challenges/1000/1292.cpp | nbsp1221/algorithm | a227bbc7cf43dbf2cadc8d47052b9a92875dfa77 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int a, b;
cin >> a >> b;
vector<int> sequence(1, 1);
int sumRange = 0;
while (sequence.size() < 1000) {
int lastNumber = sequence.back();
for (int i = 0; i <= lastNumber; i++) {
sequence.push_back(lastNumber + 1);
}
}
for (int i = a - 1; i < b; i++) {
sumRange += sequence[i];
}
cout << sumRange << "\n";
return 0;
} | 17.16129 | 47 | 0.505639 | nbsp1221 |
c873dc9ad6f04c9892a6abc76f0accfd783c77d0 | 945 | cpp | C++ | Competitive Programming/Hashing/CountDistinctElementInEveryWindow.cpp | shreejitverma/GeeksforGeeks | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-18T05:14:28.000Z | 2022-03-08T07:00:08.000Z | Competitive Programming/Hashing/CountDistinctElementInEveryWindow.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 6 | 2022-01-13T04:31:04.000Z | 2022-03-12T01:06:16.000Z | Competitive Programming/Hashing/CountDistinctElementInEveryWindow.cpp | shivaniverma1/Competitive-Programming-1 | d7bcb166369fffa9a031a258e925b6aff8d44e6c | [
"MIT"
] | 2 | 2022-02-14T19:53:53.000Z | 2022-02-18T05:14:30.000Z | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector <int> countDistinct(int[], int, int);
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];
vector <int> result = countDistinct(a, n, k);
for (int i : result)
cout << i << " ";
cout << endl;
}
return 0;
}// } Driver Code Ends
vector <int> countDistinct (int A[], int n, int k)
{
//code here.
unordered_map<int, int> m;
for(int i = 0; i < k; i++)
{
m[A[i]]++;
}
vector<int> v;
v.push_back(m.size());
for(int i = k; i < n; i++)
{
m[A[i - k]]--;
if(m[A[i - k]] == 0)
{
m.erase(A[i - k]);
}
m[A[i]]++;
v.push_back(m.size());
}
return v;
} | 16.578947 | 53 | 0.38836 | shreejitverma |
c875e2ac5342ece0efb934a1c9c3f23ea48e638c | 1,303 | cpp | C++ | Mathematical Algorithms/Statistical Algorithms/Measures of Variation.cpp | praharshjain/Algorithms | ea63a2654453f129076ee7d0041f6af3046e4dfc | [
"MIT"
] | null | null | null | Mathematical Algorithms/Statistical Algorithms/Measures of Variation.cpp | praharshjain/Algorithms | ea63a2654453f129076ee7d0041f6af3046e4dfc | [
"MIT"
] | null | null | null | Mathematical Algorithms/Statistical Algorithms/Measures of Variation.cpp | praharshjain/Algorithms | ea63a2654453f129076ee7d0041f6af3046e4dfc | [
"MIT"
] | 2 | 2020-11-28T05:59:16.000Z | 2021-03-26T14:10:58.000Z | #include <bits/stdc++.h>
using namespace std;
//function to calculate range for given set of numeric data
template <typename T>
double range(T arr[], int start, int end)
{
double max = arr[start], min = arr[start];
for (int i = start; i < end; i++)
{
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
return max - min;
}
//function to calculate variance with respect to given mean for given range of numeric data types
template <typename T>
double variance(T arr[], int start, int end, double mean)
{
double temp, sum = 0;
for (int i = start; i < end; i++)
{
temp = mean - arr[i];
sum += (temp * temp);
}
return sum / (end - start);
}
//function to calculate standard deviation with respect to given mean for given range of numeric data types
template <typename T>
double standard_deviation(T arr[], int start, int end, double mean)
{
return sqrt(variance(arr, start, end, mean));
}
int main()
{
int i, n = 10;
int arr[] = {1, 2, 3, 4, 4, 6, 7, 8, 8, 10};
cout << "Range = " << range(arr, 0, n) << "\n";
cout << "Variance with respect to 5 = " << variance(arr, 0, n, 5) << "\n";
cout << "Standard Deviation with respect to 5 = " << standard_deviation(arr, 0, n, 5);
} | 31.02381 | 107 | 0.589409 | praharshjain |
c87848c053c4500710e561eb507ba511c009e983 | 18,565 | cpp | C++ | isis/src/control/apps/mat2cnet/mat2cnet.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/control/apps/mat2cnet/mat2cnet.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/control/apps/mat2cnet/mat2cnet.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | 1 | 2021-07-12T06:05:03.000Z | 2021-07-12T06:05:03.000Z | #include "Isis.h"
#include <map>
#include "Application.h"
#include "ControlMeasure.h"
#include "ControlNet.h"
#include "ControlPoint.h"
#include "FileList.h"
#include "IException.h"
#include "IString.h"
#include "Latitude.h"
#include "Longitude.h"
#include "Preference.h"
#include "Progress.h"
#include "Pvl.h"
#include "PvlGroup.h"
#include "PvlObject.h"
#include "SerialNumberList.h"
#include "SpecialPixel.h"
#include "SurfacePoint.h"
#include "TextFile.h"
#include "UserInterface.h"
using namespace std;
using namespace Isis;
std::map <int, QString> snMap;
//std::map <string,int> fscMap;
void IsisMain() {
// The following steps can take a significant amount of time, so
// set up a progress object, incrementing at 1%, to keep the user informed
PvlGroup &uip = Preference::Preferences().findGroup("UserInterface");
uip["ProgressBarPercent"] = "1";
UserInterface &ui = Application::GetUserInterface();
Progress progress;
// Prepare the ISIS2 list of file names
FileList list2(ui.GetFileName("LIST2"));
// Prepare the ISIS3 SNs, pass the progress object to SerialNumberList
SerialNumberList snl(ui.GetFileName("LIST3"), true, &progress);
progress.CheckStatus();
if (list2.size() != snl.size()) {
QString msg = "Invalid input file number of lines. The ISIS2 file list [";
msg += ui.GetAsString("LIST2") + "] must contain the same number of lines ";
msg += "as the ISIS3 file list [" + ui.GetAsString("LIST3") + "]";
throw IException(IException::User, msg, _FILEINFO_);
}
progress.SetText("Mapping ISIS2 fsc numbers to ISIS3 serial numbers.");
progress.SetMaximumSteps(list2.size());
// Setup a map between ISIS2 image number (fsc) and ISIS3 sn
// **NOTE:
// The order of the ISIS2 and ISIS3 lists MUST correspond so that we can map
// each ISIS2 FSC to the proper ISIS3 Serial Number.
// Otherwise, we would be required to write a separate routine for each
// mission to determine the corresponding serial number for a given FSC.
// Jeannie Backer 2011-06-30
for (int f = 0; f < list2.size(); f++) {
progress.CheckStatus();
QString currFile(list2[f].toString());
Pvl lab(currFile);
PvlObject qube(lab.findObject("QUBE"));
IString fsc;
if (qube.hasKeyword("IMAGE_NUMBER")) {
fsc = qube.findKeyword("IMAGE_NUMBER")[0];
}
else if (qube.hasKeyword("IMAGE_ID")) {
fsc = qube.findKeyword("IMAGE_ID")[0];
}
else {
throw IException(IException::Unknown,
"Can not find required keyword IMAGE_NUMBER or IMAGE_ID "
"in [" + currFile + "]",
_FILEINFO_);
}
QString sn(snl.serialNumber(f));
snMap.insert(std::pair<int, QString>((int)fsc, sn));
}
progress.CheckStatus();
// Create a new control network
ControlNet cnet;
cnet.SetNetworkId(ui.GetString("NETWORKID"));
// first try to set target from user entered TargetName
cnet.SetTarget(ui.GetString("TARGET"));
// if that fails, look in a cube label for the info
if ( !cnet.GetTargetRadii()[0].isValid() ) {
Pvl isis3Lab(snl.fileName(0));
cnet.SetTarget(isis3Lab);
}
cnet.SetUserName(Application::UserName());
cnet.SetCreatedDate(Application::DateTime());
cnet.SetDescription(ui.GetString("DESCRIPTION"));
// Open the match point file
TextFile mpFile(ui.GetFileName("MATCH"));
QString currLine;
int inTotalMeas = 0;
// Read the first line with the number of measurments
mpFile.GetLine(currLine);
currLine = currLine.simplified();
currLine.remove(0, currLine.indexOf("="));
currLine.remove(0, currLine.indexOf(" "));
try {
inTotalMeas = toInt(currLine);
}
catch (IException &e) {
throw IException(e,
IException::User, "Invalid match point file "
"header for [" + ui.GetAsString("MATCH")
+ "]. First line does not contain number of "
"measurements.",
_FILEINFO_);
}
// Read line 2, the column header line
mpFile.GetLine(currLine);
currLine = currLine.simplified();
QStringList tokens = currLine.split(" ", QString::SkipEmptyParts);
while (!tokens.isEmpty()) {
QString label = tokens.takeFirst();
// this line should contain only text labels,
double error = 0;
try {
error = toDouble(label);
// if we are able to convert label to a double, we have an error
throw IException(IException::User, "Invalid match point file "
"header for [" + ui.GetAsString("MATCH")
+ "]. Second line does not contain proper "
"non-numerical column labels.",
_FILEINFO_);
}
catch (IException &e) {
// if this line does not contain a double, continue
if (error == 0) {
continue;
}
// if this line contains numeric data, throw an error
else {
throw;
}
}
}
// Reset the progress object for feedback about conversion processing
progress.SetText("Converting match point file");
progress.SetMaximumSteps(inTotalMeas);
int line = 2;
while (mpFile.GetLine(currLine)) {
line ++;
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "\"Matchpoint total\" keyword at the top of the match point "
"file [";
msg += ui.GetAsString("MATCH") + "] equals [" + toString(inTotalMeas);
msg += "] and is likely incorrect. Number of measures in match point file"
" exceeds this value at line [";
msg += toString(line) + "].";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// Declare the Point and Measure
ControlPoint *cpoint = NULL;
ControlMeasure *cmeasure = new ControlMeasure;
// Section the match point line into the important pieces
currLine = currLine.simplified();
QString pid = "";
QString fsc = "";
double lineNum, sampNum, diam;
QString matClass = "";
try {
QStringList tokens = currLine.split(" ");
if (tokens.count() < 6)
throw IException();
pid = tokens.takeFirst(); // ID of the point
fsc = tokens.takeFirst(); // FSC of the ISIS2 cube
lineNum = toDouble(tokens.takeFirst()); // line number
sampNum = toDouble(tokens.takeFirst()); // sample number
matClass = tokens.takeFirst(); // Match Point Class
diam = toDouble(tokens.takeFirst()); // Diameter, in case of a crater
}
catch (IException &e) {
QString msg = "Invalid value(s) in match point file [";
msg += ui.GetAsString("MATCH") + "] at line [" + toString(line);
msg += "]. Verify line, sample, diameter values are doubles.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// Set the coordinate and serial number for this measure
cmeasure->SetCoordinate(sampNum, lineNum);
cmeasure->SetCubeSerialNumber(snMap[toInt(fsc)]);
if (snMap[toInt(fsc)].isEmpty()) {
QString msg = "None of the images specified in the ISIS2 file list [";
msg += ui.GetAsString("LIST2");
msg += "] have an IMAGE_NUMBER or IMAGE_ID that matches the FSC [" + fsc;
msg += "], from the match point file [" + ui.GetAsString("MATCH");
msg += "] at line [" + toString(line) + "]";
throw IException(IException::User, msg, _FILEINFO_);
}
bool isReferenceMeasure = false;
//Set the Measure Type
if (matClass.toUpper() == "U") {//Unmeasured -these are ignored in isis2
cmeasure->SetType(ControlMeasure::Candidate);
cmeasure->SetIgnored(true);
}
else if (matClass.toUpper() == "T") {
// Truth type, aka reference measure, is no longer a measure type
// what this means is it has to be handled by the control point.
// So, further down the boolean set here will be used.
isReferenceMeasure = true;
}
else if (matClass.toUpper() == "S") { //SubPixel
cmeasure->SetType(ControlMeasure::RegisteredSubPixel);
}
else if (matClass.toUpper() == "M") { //Measured
cmeasure->SetType(ControlMeasure::RegisteredPixel);
}
else if (matClass.toUpper() == "A") { //Approximate
cmeasure->SetType(ControlMeasure::Candidate);
}
else {
QString msg = "Unknown measurment type [" + matClass + "] ";
msg += "in match point file [" + ui.GetAsString("MATCH") + "] ";
msg += "at line [" + toString(line) + "]";
throw IException(IException::User, msg, _FILEINFO_);
}
//Set Diameter
try {
//Check to see if the column was, in fact, a double
if ((double)IString(diam) != 0.0)
cmeasure->SetDiameter(diam);
}
catch (IException &) {
//If we get here, diam was not a double,
// but the error is not important otherwise
}
// Check whether we should lock all measures
cmeasure->SetEditLock(ui.GetBoolean("MEASURELOCK"));
//Find the point that matches the PointID, create point if it does not exist
if (cnet.ContainsPoint(pid)) {
cpoint = cnet.GetPoint((QString) pid);
}
else {
cpoint = new ControlPoint(pid);
cnet.AddPoint(cpoint);
}
//Add the measure
try {
cpoint->Add(cmeasure);
// Equivalent to (IString::Equal(matClass, "T")), as seen above
if (isReferenceMeasure) {
cpoint->SetRefMeasure(cmeasure);
}
}
catch (IException &e) {
QString msg = "Invalid match point file [" + ui.GetAsString("MATCH") +"]";
msg += ". Repeated PointID/FSC combination [" + pid + ", " + fsc;
msg += "] in match point file at line [" + toString(line) + "].";
throw IException(e, IException::User, msg, _FILEINFO_);
}
}
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "\"Matchpoint total\" keyword at the top of the match point "
"file [";
msg += ui.GetAsString("MATCH") + "] equals [" + toString(inTotalMeas);
msg += "] and is likely incorrect. Number of measures in match point file "
"exceeds this value at line [";
msg += toString(line) + "].";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// 10/5/2009 Jeannie Walldren - Added RAND PPP file as input
// 7/12/2011 Jeannie Backer - Added option to lock all points in RAND PPP file
// Open the RAND PPP file
if (ui.GetBoolean("INPUTPPP")) {
int numRandOnly = 0;
vector<QString> randOnlyIDs;
TextFile randFile(ui.GetFileName("PPP"));
progress.SetText("Converting RAND PPP file");
randFile.GetLine(currLine);
int inTotalLine = (int)(randFile.Size() / (currLine.size()));
progress.SetMaximumSteps(inTotalLine);
randFile.Rewind();
line = 0;
while (randFile.GetLine(currLine)) {
line ++;
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "RAND PPP file may not be valid. Line count calculated [";
msg += toString(inTotalLine) + "] for RAND PPP file [";
msg += ui.GetAsString("PPP") + "] appears invalid at line [";
msg += toString(line) + "].";
throw IException(e, IException::Programmer, msg, _FILEINFO_);
}
// Declare the Point
ControlPoint *cpoint = NULL;
// if end of valid data, break, stop processing
if (currLine.contains("JULIAN")) {
// Since Progress MaximumSteps was approximated using the number of
// lines in the RAND PPP file, we need to subtract the number of lines
// left from the Progress steps since the following lines are not going
// to be processed
progress.AddSteps(line - inTotalLine); // line < inTotalLine,
//so this is negative
break;
}
// break columns into substrings since some files have colunms that can't
// be tokenized easily. This is because some files have columns running
// into each other without spaces separating them
// column 1 = latitude, begins the line and is 24 characters
double lat;
QString col1 = currLine.mid(0, 24);
// remove any white space from beginning of string
//col1.ConvertWhiteSpace();
//col1.TrimHead(" ");
try {
// convert to double
lat = toDouble(col1);
}
catch (IException &e) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Verify latitude value is a double.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// column 2 = longitude, begins at 25th char and is 24 characters
double lon;
QString col2 = currLine.mid(24, 24);
// remove any white space from beginning of string
//col2.TrimHead(" ");
try {
// convert to double
lon = toDouble(col2);
}
catch (IException &e) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Verify longitude value is a double.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// column 3 = radius, begins at 49th char and is 24 characters
double rad;
QString col3 = currLine.mid(48, 24);
// remove any white space from beginning of string
//col3.TrimHead(" ");
try {
// convert to double and convert km to meters
rad = toDouble(col3);
rad = rad * 1000;
}
catch (IException &e) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Verify radius value is a double.";
throw IException(e, IException::User, msg, _FILEINFO_);
}
// column 4 = point id, begins at 73rd char and is 7 characters
QString pid = currLine.mid(72);
// remove any white space from beginning of string
pid = pid.remove(QRegExp("^ *"));
if (pid.length() > 7) {
QString msg = "Invalid value(s) in RAND PPP file [";
msg += ui.GetAsString("PPP") + "] at line [" + toString(line);
msg += "]. Point ID [" + pid + "] has more than 7 characters.";
throw IException(IException::User, msg, _FILEINFO_);
}
//Find the point that matches the PointID, if it does not exist alert the
//user
if (!cnet.ContainsPoint(pid)) {
numRandOnly++;
randOnlyIDs.push_back(currLine);
}
else {
cpoint = cnet.GetPoint((QString) pid);
// if the point is already added to the control net, it was found in
// the match point file also.
if (ui.GetString("POINTTYPE") == "FIXED") {
// If the POINTTYPE parameter is set to fixed, change point type
// of points in rand file
cpoint->SetType(ControlPoint::Fixed);
}
cpoint->SetAprioriSurfacePointSource(
ControlPoint::SurfacePointSource::BundleSolution);
cpoint->SetAprioriSurfacePointSourceFile(ui.GetAsString("PPP"));
cpoint->SetAprioriRadiusSource(
ControlPoint::RadiusSource::BundleSolution);
cpoint->SetAprioriRadiusSourceFile(ui.GetAsString("PPP"));
}
if (cpoint != NULL) {
//Add the lat,lon,rad to point
try {
SurfacePoint surfacePt(Latitude(lat, Angle::Degrees),
Longitude(lon, Angle::Degrees),
Distance(rad, Distance::Meters));
cpoint->SetAprioriSurfacePoint(surfacePt);
cpoint->SetEditLock(ui.GetBoolean("POINTLOCK"));
}
catch (IException &e) {
QString msg = "Unable to set universal ground point to control "
"network from line [";
msg += toString(line) + "] of RAND PPP file [";
msg += ui.GetAsString("PPP") + "]";
throw IException(e, IException::User, msg, _FILEINFO_);
}
}
}
// Update the Progress object
try {
progress.CheckStatus();
}
catch (IException &e) {
QString msg = "RAND PPP file may not be valid. Line count calculated [";
msg += toString(inTotalLine) + "] for RAND PPP file [";
msg += ui.GetAsString("PPP");
msg += "] appears invalid at line [" + toString(line) + "].";
throw IException(e, IException::Programmer, msg, _FILEINFO_);
}
// Write results to Logs
// Summary group is created with the counts of RAND PPP only points
PvlGroup summaryGroup = PvlGroup("Summary");
summaryGroup.addKeyword(PvlKeyword("RandOnlyPoints", toString(numRandOnly)));
bool log;
FileName logFile;
// if a filename was entered, use it to create the log
if (ui.WasEntered("LOG")) {
log = true;
logFile = ui.GetFileName("LOG");
}
// if no filename was entered, but there were some RAND PPP only points,
// create an log named "pppOnlyPoints" in the current directory
else if (numRandOnly > 0) {
log = true;
logFile = "pppOnlyPoints.log";
}
// if all RAND PPP points are found in the MATCH file and no log file is
// named, only output summary to application log
else {
log = false;
}
if (log) {
// Write details in error log
Pvl results;
results.setName("Results");
results.addGroup(summaryGroup);
if (numRandOnly > 0) {
// if there are any RAND PPP only points,
// add comment to the summary log to alert user
summaryGroup.addComment("Some Point IDs in the RAND PPP file have no "
"measures in the MATCH file.");
summaryGroup.addComment("These Point IDs are contained "
"in [" + logFile.name() + "].");
TextFile outlog(logFile.expanded(), "overwrite", randOnlyIDs);
}
else {
// if there are no RAND PPP only points and user wanted to create a log,
// add comment to the summary log to alert user
summaryGroup.addComment("All Point IDs in the RAND PPP file have "
"measures in the MATCH file.");
summaryGroup.addComment("No RAND PPP log was created.");
}
}
// Write summary to application log
Application::Log(summaryGroup);
}
// Write the control network out
cnet.Write(ui.GetFileName("ONET"));
}
| 35.633397 | 81 | 0.611689 | ihumphrey-usgs |
c87be2746ba9c7e42f8dbd9b3a6818b5d9d6fca1 | 847 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/quest/TimeDilation_Player.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/quest/TimeDilation_Player.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/quest/TimeDilation_Player.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Handle.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/ETimeDilationOverride.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/TimeDilation_NodeTypeParam.hpp>
namespace RED4ext
{
namespace quest { struct TimeDilation_Operation; }
namespace quest {
struct TimeDilation_Player : quest::TimeDilation_NodeTypeParam
{
static constexpr const char* NAME = "questTimeDilation_Player";
static constexpr const char* ALIAS = NAME;
Handle<quest::TimeDilation_Operation> operation; // 30
quest::ETimeDilationOverride globalTimeDilationOverride; // 40
uint8_t unk44[0x48 - 0x44]; // 44
};
RED4EXT_ASSERT_SIZE(TimeDilation_Player, 0x48);
} // namespace quest
} // namespace RED4ext
| 30.25 | 83 | 0.780401 | jackhumbert |
c87c33e1e2775720bd69091add608f6e4ec6ce87 | 17,342 | cpp | C++ | src/mt/token_type.cpp | nfagan/mtype | a745271d366df64e1b4692cc90f0685ea4084ba6 | [
"MIT"
] | null | null | null | src/mt/token_type.cpp | nfagan/mtype | a745271d366df64e1b4692cc90f0685ea4084ba6 | [
"MIT"
] | null | null | null | src/mt/token_type.cpp | nfagan/mtype | a745271d366df64e1b4692cc90f0685ea4084ba6 | [
"MIT"
] | null | null | null | #include "token_type.hpp"
#include <string>
#include <unordered_map>
#include <cassert>
#include <cstring>
namespace mt {
TokenType from_symbol(std::string_view s) {
static std::unordered_map<std::string, TokenType> symbol_map{
{"(", TokenType::left_parens},
{")", TokenType::right_parens},
{"[", TokenType::left_bracket},
{"]", TokenType::right_bracket},
{"{", TokenType::left_brace},
{"}", TokenType::right_brace},
{"=", TokenType::equal},
{"==", TokenType::equal_equal},
{"~=", TokenType::not_equal},
{"<", TokenType::less},
{">", TokenType::greater},
{"<=", TokenType::less_equal},
{">=", TokenType::greater_equal},
{"~", TokenType::tilde},
{":", TokenType::colon},
{";", TokenType::semicolon},
{".", TokenType::period},
{",", TokenType::comma},
{"+", TokenType::plus},
{"-", TokenType::minus},
{"*", TokenType::asterisk},
{"/", TokenType::forward_slash},
{"\\", TokenType::back_slash},
{"^", TokenType::carat},
{".*", TokenType::dot_asterisk},
{"./", TokenType::dot_forward_slash},
{".\\", TokenType::dot_back_slash},
{".^", TokenType::dot_carat},
{"@", TokenType::at},
{"\n", TokenType::new_line},
{"?", TokenType::question},
{"'", TokenType::apostrophe},
{"\"", TokenType::quote},
{"|", TokenType::vertical_bar},
{"&", TokenType::ampersand},
{"||", TokenType::double_vertical_bar},
{"&&", TokenType::double_ampersand},
{"break", TokenType::keyword_break},
{"case", TokenType::keyword_case},
{"catch", TokenType::keyword_catch},
{"classdef", TokenType::keyword_classdef},
{"continue", TokenType::keyword_continue},
{"else", TokenType::keyword_else},
{"elseif", TokenType::keyword_elseif},
{"end", TokenType::keyword_end},
{"for", TokenType::keyword_for},
{"function", TokenType::keyword_function},
{"fun", TokenType::keyword_fun_type},
{"global", TokenType::keyword_global},
{"if", TokenType::keyword_if},
{"otherwise", TokenType::keyword_otherwise},
{"parfor", TokenType::keyword_parfor},
{"persistent", TokenType::keyword_persistent},
{"return", TokenType::keyword_return},
{"spmd", TokenType::keyword_spmd},
{"switch", TokenType::keyword_switch},
{"try", TokenType::keyword_try},
{"while", TokenType::keyword_while},
{"enumeration", TokenType::keyword_enumeration},
{"events", TokenType::keyword_events},
{"methods", TokenType::keyword_methods},
{"properties", TokenType::keyword_properties},
{"import", TokenType::keyword_import},
{"begin", TokenType::keyword_begin},
{"export", TokenType::keyword_export},
{"given", TokenType::keyword_given},
{"let", TokenType::keyword_let},
{"namespace", TokenType::keyword_namespace},
{"struct", TokenType::keyword_struct},
{"record", TokenType::keyword_record},
{"@T", TokenType::type_annotation_macro},
{"::", TokenType::double_colon},
{"declare", TokenType::keyword_declare},
{"constructor", TokenType::keyword_constructor},
{"list", TokenType::keyword_list},
{"cast", TokenType::keyword_cast},
{"presume", TokenType::keyword_presume}
};
const auto it = symbol_map.find(std::string(s));
if (it == symbol_map.end()) {
return TokenType::null;
} else {
return it->second;
}
}
const char* to_symbol(TokenType type) {
switch (type) {
case TokenType::left_parens:
return "(";
case TokenType::right_parens:
return ")";
case TokenType::left_brace:
return "{";
case TokenType::right_brace:
return "}";
case TokenType::left_bracket:
return "[";
case TokenType::right_bracket:
return "]";
// Punct
case TokenType::ellipsis:
return "...";
case TokenType::equal:
return "=";
case TokenType::equal_equal:
return "==";
case TokenType::not_equal:
return "~=";
case TokenType::less:
return "<";
case TokenType::greater:
return ">";
case TokenType::less_equal:
return "<=";
case TokenType::greater_equal:
return ">=";
case TokenType::tilde:
return "~";
case TokenType::colon:
return ":";
case TokenType::double_colon:
return "::";
case TokenType::semicolon:
return ";";
case TokenType::period:
return ".";
case TokenType::comma:
return ",";
case TokenType::plus:
return "+";
case TokenType::minus:
return "-";
case TokenType::asterisk:
return "*";
case TokenType::forward_slash:
return "/";
case TokenType::back_slash:
return "\\";
case TokenType::carat:
return "^";
case TokenType::dot_asterisk:
return ".*";
case TokenType::dot_forward_slash:
return "./";
case TokenType::dot_back_slash:
return ".\\";
case TokenType::dot_carat:
return ".^";
case TokenType::dot_apostrophe:
return ".'";
case TokenType::at:
return "@";
case TokenType::new_line:
return "\n";
case TokenType::question:
return "?";
case TokenType::apostrophe:
return "'";
case TokenType::quote:
return "\"";
case TokenType::vertical_bar:
return "|";
case TokenType::ampersand:
return "&";
case TokenType::double_vertical_bar:
return "||";
case TokenType::double_ampersand:
return "&&";
case TokenType::op_end:
return "end";
// Ident + literals
case TokenType::identifier:
return "<identifier>";
case TokenType::char_literal:
return "<char_literal>";
case TokenType::string_literal:
return "<string_literal>";
case TokenType::number_literal:
return "<number_literal>";
// Keywords
case TokenType::keyword_break:
return "break";
case TokenType::keyword_case:
return "case";
case TokenType::keyword_catch:
return "catch";
case TokenType::keyword_classdef:
return "classdef";
case TokenType::keyword_continue:
return "continue";
case TokenType::keyword_else:
return "else";
case TokenType::keyword_elseif:
return "elseif";
case TokenType::keyword_end:
return "end";
case TokenType::keyword_for:
return "for";
case TokenType::keyword_function:
return "function";
case TokenType::keyword_global:
return "global";
case TokenType::keyword_if:
return "if";
case TokenType::keyword_otherwise:
return "otherwise";
case TokenType::keyword_parfor:
return "parfor";
case TokenType::keyword_persistent:
return "persistent";
case TokenType::keyword_return:
return "return";
case TokenType::keyword_spmd:
return "spmd";
case TokenType::keyword_switch:
return "switch";
case TokenType::keyword_try:
return "try";
case TokenType::keyword_while:
return "while";
// Class keywords
case TokenType::keyword_enumeration:
return "enumeration";
case TokenType::keyword_events:
return "events";
case TokenType::keyword_methods:
return "methods";
case TokenType::keyword_properties:
return "properties";
case TokenType::keyword_import:
return "import";
// Typing keywords
case TokenType::keyword_begin:
return "begin";
case TokenType::keyword_export:
return "export";
case TokenType::keyword_given:
return "given";
case TokenType::keyword_let:
return "let";
case TokenType::keyword_namespace:
return "namespace";
case TokenType::keyword_struct:
return "struct";
case TokenType::keyword_record:
return "record";
case TokenType::keyword_function_type:
return "function";
case TokenType::keyword_fun_type:
return "fun";
case TokenType::keyword_end_type:
return "end";
case TokenType::type_annotation_macro:
return "@T";
case TokenType::keyword_declare:
return "declare";
case TokenType::keyword_constructor:
return "constructor";
case TokenType::keyword_list:
return "list";
case TokenType::keyword_cast:
return "cast";
case TokenType::keyword_presume:
return "presume";
case TokenType::null:
return "<null>";
}
assert(false);
return "<null>";
}
const char* to_string(TokenType type) {
switch (type) {
case TokenType::left_parens:
return "left_parens";
case TokenType::right_parens:
return "right_parens";
case TokenType::left_brace:
return "left_brace";
case TokenType::right_brace:
return "right_brace";
case TokenType::left_bracket:
return "left_bracket";
case TokenType::right_bracket:
return "right_bracket";
// Punct
case TokenType::ellipsis:
return "ellipsis";
case TokenType::equal:
return "equal";
case TokenType::equal_equal:
return "equal_equal";
case TokenType::not_equal:
return "not_equal";
case TokenType::less:
return "less";
case TokenType::greater:
return "greater";
case TokenType::less_equal:
return "less_equal";
case TokenType::greater_equal:
return "greater_equal";
case TokenType::tilde:
return "tilde";
case TokenType::colon:
return "colon";
case TokenType::double_colon:
return "double_colon";
case TokenType::semicolon:
return "semicolon";
case TokenType::period:
return "period";
case TokenType::comma:
return "comma";
case TokenType::plus:
return "plus";
case TokenType::minus:
return "minus";
case TokenType::asterisk:
return "asterisk";
case TokenType::forward_slash:
return "forward_slash";
case TokenType::back_slash:
return "back_slash";
case TokenType::carat:
return "carat";
case TokenType::dot_apostrophe:
return "dot_apostrophe";
case TokenType::dot_asterisk:
return "dot_asterisk";
case TokenType::dot_forward_slash:
return "dot_forward_slash";
case TokenType::dot_back_slash:
return "dot_backslash";
case TokenType::dot_carat:
return "dot_carat";
case TokenType::at:
return "at";
case TokenType::new_line:
return "new_line";
case TokenType::question:
return "question";
case TokenType::apostrophe:
return "apostrophe";
case TokenType::quote:
return "quote";
case TokenType::vertical_bar:
return "vertical_bar";
case TokenType::ampersand:
return "ampersand";
case TokenType::double_vertical_bar:
return "double_vertical_bar";
case TokenType::double_ampersand:
return "double_ampersand";
case TokenType::op_end:
return "op_end";
// Ident + literals
case TokenType::identifier:
return "identifier";
case TokenType::char_literal:
return "char_literal";
case TokenType::string_literal:
return "string_literal";
case TokenType::number_literal:
return "number_literal";
// Keywords
case TokenType::keyword_break:
return "keyword_break";
case TokenType::keyword_case:
return "keyword_case";
case TokenType::keyword_catch:
return "keyword_catch";
case TokenType::keyword_classdef:
return "keyword_classdef";
case TokenType::keyword_continue:
return "keyword_continue";
case TokenType::keyword_else:
return "keyword_else";
case TokenType::keyword_elseif:
return "keyword_elseif";
case TokenType::keyword_end:
return "keyword_end";
case TokenType::keyword_for:
return "keyword_for";
case TokenType::keyword_function:
return "keyword_function";
case TokenType::keyword_global:
return "keyword_global";
case TokenType::keyword_if:
return "keyword_if";
case TokenType::keyword_otherwise:
return "keyword_otherwise";
case TokenType::keyword_parfor:
return "keyword_parfor";
case TokenType::keyword_persistent:
return "keyword_persistent";
case TokenType::keyword_return:
return "keyword_return";
case TokenType::keyword_spmd:
return "keyword_spmd";
case TokenType::keyword_switch:
return "keyword_switch";
case TokenType::keyword_try:
return "keyword_try";
case TokenType::keyword_while:
return "keyword_while";
// Class keywords
case TokenType::keyword_enumeration:
return "keyword_enumeration";
case TokenType::keyword_events:
return "keyword_events";
case TokenType::keyword_methods:
return "keyword_methods";
case TokenType::keyword_properties:
return "keyword_properties";
case TokenType::keyword_import:
return "keyword_import";
// Typing keywords
case TokenType::keyword_begin:
return "keyword_begin";
case TokenType::keyword_export:
return "keyword_export";
case TokenType::keyword_given:
return "keyword_given";
case TokenType::keyword_let:
return "keyword_let";
case TokenType::keyword_namespace:
return "keyword_namespace";
case TokenType::keyword_struct:
return "keyword_struct";
case TokenType::keyword_record:
return "keyword_record";
case TokenType::keyword_function_type:
return "keyword_function_type";
case TokenType::keyword_fun_type:
return "keyword_fun_type";
case TokenType::keyword_end_type:
return "keyword_end_type";
case TokenType::keyword_declare:
return "keyword_declare";
case TokenType::keyword_constructor:
return "keyword_constructor";
case TokenType::keyword_list:
return "keyword_list";
case TokenType::keyword_cast:
return "keyword_cast";
case TokenType::keyword_presume:
return "keyword_presume";
case TokenType::type_annotation_macro:
return "type_annotation_macro";
case TokenType::null:
return "null";
}
assert(false);
return "null";
}
bool unsafe_represents_keyword(TokenType type) {
// @TODO: Implement this more carefully.
// std::strlen("keyword")
return std::strncmp("keyword", to_string(type), 7) == 0;
}
bool represents_literal(TokenType type) {
return type == TokenType::string_literal || type == TokenType::char_literal ||
type == TokenType::number_literal;
}
bool represents_expr_terminator(TokenType type) {
return represents_stmt_terminator(type) || represents_grouping_terminator(type) || type == TokenType::equal;
}
bool represents_stmt_terminator(TokenType type) {
return type == TokenType::semicolon || type == TokenType::comma || type == TokenType::new_line ||
type == TokenType::null;
}
bool represents_grouping_component(TokenType type) {
const auto min = static_cast<unsigned int>(TokenType::left_parens);
const auto max = static_cast<unsigned int>(TokenType::right_bracket);
const auto t = static_cast<unsigned int>(type);
return t >= min && t <= max;
}
bool represents_grouping_initiator(TokenType type) {
return type == TokenType::left_parens || type == TokenType::left_brace ||
type == TokenType::left_bracket;
}
bool represents_grouping_terminator(TokenType type) {
return type == TokenType::right_parens || type == TokenType::right_brace ||
type == TokenType::right_bracket;
}
bool represents_binary_operator(TokenType type) {
// @Hack, first 21 token types are binary operators.
return static_cast<unsigned int>(type) < 21;
}
bool represents_unary_operator(TokenType type) {
return represents_postfix_unary_operator(type) || represents_prefix_unary_operator(type);
}
bool represents_prefix_unary_operator(TokenType type) {
return type == TokenType::plus || type == TokenType::minus || type == TokenType::tilde;
}
bool can_precede_prefix_unary_operator(TokenType type) {
switch (type) {
case TokenType::identifier:
case TokenType::string_literal:
case TokenType::char_literal:
case TokenType::number_literal:
case TokenType::keyword_end:
case TokenType::op_end:
return false;
default:
return !represents_grouping_terminator(type) && !represents_postfix_unary_operator(type);
}
}
bool can_be_skipped_in_classdef_block(TokenType type) {
switch (type) {
case TokenType::comma:
case TokenType::semicolon:
case TokenType::new_line:
return true;
default:
return false;
}
}
bool can_precede_postfix_unary_operator(TokenType type) {
return represents_literal(type) || represents_grouping_terminator(type) ||
type == TokenType::identifier || type == TokenType::apostrophe || type == TokenType::dot_apostrophe;
}
bool represents_postfix_unary_operator(TokenType type) {
return type == TokenType::apostrophe || type == TokenType::dot_apostrophe;
}
std::array<TokenType, 3> grouping_terminators() {
return {{TokenType::right_parens, TokenType::right_bracket, TokenType::right_bracket}};
}
TokenType grouping_terminator_for(TokenType initiator) {
switch (initiator) {
case TokenType::left_brace:
return TokenType::right_brace;
case TokenType::left_bracket:
return TokenType::right_bracket;
case TokenType::left_parens:
return TokenType::right_parens;
default:
assert(false && "No grouping terminator for type.");
return TokenType::null;
}
}
} | 30.16 | 110 | 0.661227 | nfagan |
c87cb139a11bc2d79c7fc9a779c71f2cebb692e3 | 385 | hpp | C++ | lib/ArduinoJson_ID64/src/ArduinoJson/Deserialization/NestingLimit.hpp | wwmoo7/IRbaby-firmware | 7de0304c2c708a7094324bce1560ac39fcdb8e84 | [
"MIT"
] | 38 | 2020-04-09T03:17:16.000Z | 2022-03-21T06:33:05.000Z | lib/ArduinoJson_ID64/src/ArduinoJson/Deserialization/NestingLimit.hpp | wwmoo7/IRbaby-firmware | 7de0304c2c708a7094324bce1560ac39fcdb8e84 | [
"MIT"
] | 6 | 2020-05-19T10:56:31.000Z | 2022-01-24T07:21:40.000Z | lib/ArduinoJson_ID64/src/ArduinoJson/Deserialization/NestingLimit.hpp | wwmoo7/IRbaby-firmware | 7de0304c2c708a7094324bce1560ac39fcdb8e84 | [
"MIT"
] | 15 | 2020-06-26T09:31:32.000Z | 2021-09-01T15:22:00.000Z | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
#pragma once
#include <ArduinoJson/Namespace.hpp>
namespace ARDUINOJSON_NAMESPACE {
struct NestingLimit {
NestingLimit() : value(ARDUINOJSON_DEFAULT_NESTING_LIMIT) {}
explicit NestingLimit(uint8_t n) : value(n) {}
uint8_t value;
};
} // namespace ARDUINOJSON_NAMESPACE
| 21.388889 | 63 | 0.727273 | wwmoo7 |
c87ec352920b8502108500d9aea45a3797591b07 | 1,373 | cpp | C++ | tests/dxbc/test_dxbc_disasm.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 8,148 | 2017-10-29T10:51:20.000Z | 2022-03-31T12:52:51.000Z | tests/dxbc/test_dxbc_disasm.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 2,270 | 2017-12-04T12:08:13.000Z | 2022-03-31T19:56:41.000Z | tests/dxbc/test_dxbc_disasm.cpp | lacc97/dxvk | 5fe8d823a03cc1c90361a4e89c385cefee8cbcf6 | [
"Zlib"
] | 732 | 2017-11-28T13:08:15.000Z | 2022-03-31T21:05:59.000Z | #include <iostream>
#include <string>
#include <d3dcompiler.h>
#include <shellapi.h>
#include <windows.h>
#include <windowsx.h>
#include "../../src/util/com/com_pointer.h"
using namespace dxvk;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow) {
int argc = 0;
LPWSTR* argv = CommandLineToArgvW(
GetCommandLineW(), &argc);
if (argc < 2 || argc > 3) {
std::cerr << "Usage: dxbc-disasm input.dxbc [output]" << std::endl;
return 1;
}
Com<ID3DBlob> assembly;
Com<ID3DBlob> binary;
// input file
if (FAILED(D3DReadFileToBlob(argv[1], &binary))) {
std::cerr << "Failed to read shader" << std::endl;
return 1;
}
HRESULT hr = D3DDisassemble(
binary->GetBufferPointer(),
binary->GetBufferSize(),
D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING, nullptr,
&assembly);
if (FAILED(hr)) {
std::cerr << "Failed to disassemble shader" << std::endl;
return 1;
}
// output file variant
if (argc == 3 && FAILED(D3DWriteBlobToFile(assembly.ptr(), argv[2], 1))) {
std::cerr << "Failed to write shader" << std::endl;
return 1;
}
// stdout variant
if (argc == 2) {
std::string data((const char *)assembly->GetBufferPointer(), assembly->GetBufferSize());
std::cout << data;
}
return 0;
}
| 22.508197 | 92 | 0.614712 | lacc97 |
c87f75ef369ffeddfaea9a76ab99e519052bf3d5 | 6,812 | cpp | C++ | client/cardmaker/cocos2d/cocos/base/CCController-android.cpp | zhs007/cardmaker | cd700327c8c1840eb817b3ea27b10be6423118ff | [
"MIT"
] | 120 | 2018-12-25T03:13:01.000Z | 2022-03-11T10:31:16.000Z | client/cardmaker/cocos2d/cocos/base/CCController-android.cpp | zhs007/cardmaker | cd700327c8c1840eb817b3ea27b10be6423118ff | [
"MIT"
] | 8 | 2016-07-17T06:39:54.000Z | 2021-07-06T15:14:19.000Z | client/cardmaker/cocos2d/cocos/base/CCController-android.cpp | zhs007/cardmaker | cd700327c8c1840eb817b3ea27b10be6423118ff | [
"MIT"
] | 98 | 2019-02-20T01:14:46.000Z | 2022-03-22T16:20:51.000Z | /****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCController.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <functional>
#include "ccMacros.h"
#include "CCDirector.h"
#include "jni/JniHelper.h"
#include "base/CCEventController.h"
NS_CC_BEGIN
class ControllerImpl
{
public:
ControllerImpl(Controller* controller)
: _controller(controller)
{
}
static std::vector<Controller*>::iterator findController(const std::string& deviceName, int deviceId)
{
auto iter = std::find_if(Controller::s_allController.begin(), Controller::s_allController.end(), [&](Controller* controller){
return (deviceName == controller->_deviceName) && (deviceId == controller->_deviceId);
});
return iter;
}
static void onConnected(const std::string& deviceName, int deviceId)
{
// Check whether the controller is already connected.
CCLOG("onConnected %s,%d", deviceName.c_str(),deviceId);
auto iter = findController(deviceName, deviceId);
if (iter != Controller::s_allController.end())
return;
// It's a new controller being connected.
auto controller = new cocos2d::Controller();
controller->_deviceId = deviceId;
controller->_deviceName = deviceName;
Controller::s_allController.push_back(controller);
controller->onConnected();
}
static void onDisconnected(const std::string& deviceName, int deviceId)
{
CCLOG("onDisconnected %s,%d", deviceName.c_str(),deviceId);
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
CCLOGERROR("Could not find the controller!");
return;
}
(*iter)->onDisconnected();
Controller::s_allController.erase(iter);
}
static void onButtonEvent(const std::string& deviceName, int deviceId, int keyCode, bool isPressed, float value, bool isAnalog)
{
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
CCLOG("onButtonEvent:connect new controller.");
onConnected(deviceName, deviceId);
iter = findController(deviceName, deviceId);
}
(*iter)->onButtonEvent(keyCode, isPressed, value, isAnalog);
}
static void onAxisEvent(const std::string& deviceName, int deviceId, int axisCode, float value, bool isAnalog)
{
auto iter = findController(deviceName, deviceId);
if (iter == Controller::s_allController.end())
{
CCLOG("onAxisEvent:connect new controller.");
onConnected(deviceName, deviceId);
iter = findController(deviceName, deviceId);
}
(*iter)->onAxisEvent(axisCode, value, isAnalog);
}
private:
Controller* _controller;
};
void Controller::startDiscoveryController()
{
// Empty implementation on Android
}
void Controller::stopDiscoveryController()
{
// Empty implementation on Android
}
Controller::~Controller()
{
delete _impl;
delete _connectEvent;
delete _keyEvent;
delete _axisEvent;
}
void Controller::registerListeners()
{
}
bool Controller::isConnected() const
{
// If there is a controller instance, it means that the controller is connected.
// If a controller is disconnected, the instance will be destroyed.
// So always returns true for this method.
return true;
}
Controller::Controller()
: _controllerTag(TAG_UNSET)
, _impl(new ControllerImpl(this))
, _connectEvent(nullptr)
, _keyEvent(nullptr)
, _axisEvent(nullptr)
{
init();
}
void Controller::receiveExternalKeyEvent(int externalKeyCode,bool receive)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/GameControllerHelper", "receiveExternalKeyEvent", "(IIZ)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, _deviceId, externalKeyCode, receive);
t.env->DeleteLocalRef(t.classID);
}
}
NS_CC_END
extern "C" {
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerConnected(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID)
{
CCLOG("controller id: %d connected!", controllerID);
cocos2d::ControllerImpl::onConnected(cocos2d::JniHelper::jstring2string(deviceName), controllerID);
}
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerDisconnected(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID)
{
CCLOG("controller id: %d disconnected!", controllerID);
cocos2d::ControllerImpl::onDisconnected(cocos2d::JniHelper::jstring2string(deviceName), controllerID);
}
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerButtonEvent(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID, jint button, jboolean isPressed, jfloat value, jboolean isAnalog)
{
cocos2d::ControllerImpl::onButtonEvent(cocos2d::JniHelper::jstring2string(deviceName), controllerID, button, isPressed, value, isAnalog);
}
void Java_org_cocos2dx_lib_GameControllerAdapter_nativeControllerAxisEvent(JNIEnv* env, jobject thiz, jstring deviceName, jint controllerID, jint axis, jfloat value, jboolean isAnalog)
{
cocos2d::ControllerImpl::onAxisEvent(cocos2d::JniHelper::jstring2string(deviceName), controllerID, axis, value, isAnalog);
}
} // extern "C" {
#endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
| 34.40404 | 213 | 0.689665 | zhs007 |
c8824f286d5b17113495585b80a3bc71e4428eb4 | 14,863 | cpp | C++ | src/asm_i8086.cpp | tgtakaoka/libasm | 41ae8dcca3924c20eb482dc9e034120d8ee966a7 | [
"Apache-2.0"
] | 15 | 2020-01-24T14:15:08.000Z | 2022-03-29T15:13:16.000Z | src/asm_i8086.cpp | tgtakaoka/libasm | 41ae8dcca3924c20eb482dc9e034120d8ee966a7 | [
"Apache-2.0"
] | 23 | 2020-05-31T14:13:53.000Z | 2021-09-22T17:06:29.000Z | src/asm_i8086.cpp | tgtakaoka/libasm | 41ae8dcca3924c20eb482dc9e034120d8ee966a7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Tadashi G. Takaoka
*
* 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 "asm_i8086.h"
#include "error_reporter.h"
#include "reg_i8086.h"
#include "table_i8086.h"
namespace libasm {
namespace i8086 {
bool AsmI8086::parseStringInst(const char *scan, Operand &op) {
Insn _insn(0);
InsnI8086 insn(_insn);
const char *endName = _parser.scanSymbol(scan);
insn.setName(scan, endName);
insn.setAddrMode(M_NONE, M_NONE);
if (TableI8086.searchName(insn))
return false;
if (!insn.stringInst())
return false;
_scan = skipSpaces(endName);
op.val32 = insn.opCode();
op.mode = M_ISTR;
return true;
}
const char *AsmI8086::parsePointerSize(const char *scan, Operand &op) {
const char *p = scan;
const RegName reg = RegI8086::parseRegName(p);
if (reg == REG_BYTE || reg == REG_WORD) {
p = skipSpaces(p + RegI8086::regNameLen(reg));
// Pointer size override
if (RegI8086::parseRegName(p) == REG_PTR) {
op.ptr = reg;
return skipSpaces(p + RegI8086::regNameLen(REG_PTR));
}
setError(UNKNOWN_OPERAND);
return nullptr;
}
return scan;
}
const char *AsmI8086::parseSegmentOverride(const char *scan, Operand &op) {
const char *p = scan;
const RegName reg = RegI8086::parseRegName(p);
if (RegI8086::isSegmentReg(reg)) {
p = skipSpaces(p + RegI8086::regNameLen(reg));
// Segment Override
if (*p == ':') {
op.seg = reg;
return skipSpaces(p + 1);
}
}
return scan;
}
const char *AsmI8086::parseBaseRegister(const char *scan, Operand &op) {
const char *p = scan;
const RegName reg = RegI8086::parseRegName(p);
if (reg == REG_BX || reg == REG_BP) {
op.reg = reg;
return skipSpaces(p + RegI8086::regNameLen(reg));
}
return scan;
}
const char *AsmI8086::parseIndexRegister(const char *scan, Operand &op) {
const char *p = scan;
if (op.reg != REG_UNDEF) {
if (*p != '+')
return scan;
p = skipSpaces(p + 1);
}
const RegName reg = RegI8086::parseRegName(p);
if (reg == REG_SI || reg == REG_DI) {
op.index = reg;
return skipSpaces(p + RegI8086::regNameLen(reg));
}
return scan;
}
const char *AsmI8086::parseDisplacement(const char *scan, Operand &op) {
const char *p = scan;
if (endOfLine(p) || *p == ']')
return scan;
if (op.reg != REG_UNDEF || op.index != REG_UNDEF) {
if (*p != '+' && *p != '-') {
setError(UNKNOWN_OPERAND);
return nullptr;
}
}
op.val32 = parseExpr32(p);
if (parserError()) {
setError(parserError());
return nullptr;
}
if (overflowUint16(static_cast<int32_t>(op.val32))) {
setError(OVERFLOW_RANGE);
return nullptr;
}
op.setError(getError());
op.hasVal = true;
return skipSpaces(_scan);
}
Error AsmI8086::parseOperand(const char *scan, Operand &op) {
const char *p = skipSpaces(scan);
_scan = p;
if (endOfLine(p))
return OK;
if (parseStringInst(p, op))
return OK;
p = parsePointerSize(p, op);
if (p == nullptr)
return getError();
p = parseSegmentOverride(p, op);
if (*p == '[') {
p = skipSpaces(p + 1);
p = parseBaseRegister(p, op);
p = parseIndexRegister(p, op);
p = parseDisplacement(p, op);
if (p == nullptr)
return getError();
if (*p == ']') {
_scan = p + 1;
if (op.reg == REG_UNDEF && op.index == REG_UNDEF) {
if (op.hasVal) {
op.mode =
(op.ptr == REG_UNDEF) ? M_DIR : (op.ptr == REG_BYTE ? M_BDIR : M_WDIR);
return OK;
}
return setError(UNKNOWN_OPERAND);
}
op.mode = (op.ptr == REG_UNDEF) ? M_MEM : (op.ptr == REG_BYTE ? M_BMEM : M_WMEM);
return OK;
}
return setError(MISSING_CLOSING_PAREN);
}
if (op.ptr != REG_UNDEF || op.seg != REG_UNDEF)
return setError(UNKNOWN_OPERAND);
const RegName reg = RegI8086::parseRegName(p);
if (RegI8086::isGeneralReg(reg)) {
_scan = p + RegI8086::regNameLen(reg);
op.reg = reg;
switch (reg) {
case REG_AL:
op.mode = M_AL;
break;
case REG_CL:
op.mode = M_CL;
break;
case REG_AX:
op.mode = M_AX;
break;
case REG_DX:
op.mode = M_DX;
break;
default:
op.mode = (RegI8086::generalRegSize(reg) == SZ_BYTE) ? M_BREG : M_WREG;
break;
}
return OK;
}
if (RegI8086::isSegmentReg(reg)) {
_scan = p + RegI8086::regNameLen(reg);
op.reg = reg;
op.mode = (reg == REG_CS) ? M_CS : M_SREG;
return OK;
}
if (reg != REG_UNDEF)
return setError(UNKNOWN_OPERAND);
op.val32 = parseExpr32(p);
if (parserError())
return getError();
op.setError(getError());
p = skipSpaces(_scan);
if (*p == ':') {
if (op.val32 >= 0x10000UL)
return setError(OVERFLOW_RANGE);
op.seg16 = op.val32;
op.val32 = parseExpr32(p + 1);
if (op.val32 >= 0x10000UL)
return setError(OVERFLOW_RANGE);
if (parserError())
return getError();
op.setErrorIf(getError());
op.mode = M_FAR;
return OK;
}
op.mode = op.immediateMode();
if (op.mode == M_NONE)
return setError(OVERFLOW_RANGE);
return OK;
}
AddrMode AsmI8086::Operand::immediateMode() const {
if (getError())
return M_IMM;
if (val32 == 1)
return M_VAL1;
if (val32 == 3)
return M_VAL3;
if (!overflowUint8(val32))
return M_IMM8;
if (!overflowUint16(val32))
return M_IMM;
return M_NONE;
}
Error AsmI8086::emitImmediate(InsnI8086 &insn, OprSize size, uint32_t val) {
if (size == SZ_BYTE) {
if (overflowUint8(val))
return setError(OVERFLOW_RANGE);
insn.emitOperand8(val);
}
if (size == SZ_WORD) {
if (overflowUint16(val))
return setError(OVERFLOW_RANGE);
insn.emitOperand16(val);
}
return OK;
}
Error AsmI8086::emitRelative(InsnI8086 &insn, const Operand &op, AddrMode mode) {
const Config::uintptr_t base = insn.address() + (mode == M_REL8 ? 2 : 3);
const Config::uintptr_t target = op.getError() ? base : op.val32;
const Config::ptrdiff_t delta = target - base;
if (mode == M_REL8) {
const bool overflow = (delta < -0x80 || delta >= 0x80);
if (insn.opCode() == 0xEB && (overflow || op.getError())) {
insn.setOpCode(0xE9, 0);
return emitRelative(insn, op, M_REL);
}
if (overflow)
return setError(OPERAND_TOO_FAR);
insn.emitOperand8(static_cast<uint8_t>(delta));
return OK;
}
// M_REL
if (delta < -0x8000 || delta >= 0x8000)
return setError(OPERAND_TOO_FAR);
insn.emitOperand16(static_cast<uint16_t>(delta));
return OK;
}
Error AsmI8086::emitRegister(InsnI8086 &insn, const Operand &op, OprPos pos) {
const uint8_t num = RegI8086::encodeRegNum(op.reg);
switch (pos) {
case P_OREG:
insn.embed(num);
break;
case P_OSEG:
insn.embed(num << 3);
break;
case P_OMOD:
insn.embed(0300 | num);
break;
case P_REG:
insn.embedModReg(num << 3);
break;
case P_MOD:
insn.embedModReg(0300 | num);
break;
default:
break;
}
return OK;
}
uint8_t AsmI8086::Operand::encodeMod() const {
const bool needDisp =
(reg == REG_BP && index == REG_UNDEF) || (hasVal && (val32 || getError()));
if (needDisp) {
const int32_t val = static_cast<int32_t>(val32);
return (val < -0x80 || val >= 0x80 || getError()) ? 2 : 1;
}
return 0;
}
uint8_t AsmI8086::Operand::encodeR_m() const {
uint8_t r_m = 0;
if (reg == REG_UNDEF) {
r_m = (index == REG_SI) ? 4 : 5;
} else if (index == REG_UNDEF) {
r_m = (reg == REG_BP) ? 6 : 7;
} else {
if (reg == REG_BP)
r_m |= 2;
if (index == REG_DI)
r_m |= 1;
}
return r_m;
}
Config::opcode_t AsmI8086::encodeSegmentOverride(RegName seg, RegName base) {
if (seg == REG_UNDEF)
return 0;
const Config::opcode_t segPrefix = TableI8086.segOverridePrefix(seg);
if (_optimizeSegment) {
if (base == REG_BP || base == REG_SP)
return seg == REG_SS ? 0 : segPrefix;
return seg == REG_DS ? 0 : segPrefix;
}
return segPrefix;
}
Error AsmI8086::emitModReg(InsnI8086 &insn, const Operand &op, OprPos pos) {
uint8_t mod;
uint8_t modReg;
switch (op.mode) {
case M_AL:
case M_CL:
case M_AX:
case M_DX:
case M_BREG:
case M_WREG:
return emitRegister(insn, op, pos);
case M_BDIR:
case M_WDIR:
case M_DIR:
return emitDirect(insn, op, pos);
case M_BMEM:
case M_WMEM:
case M_MEM:
insn.setSegment(encodeSegmentOverride(op.seg, op.reg));
mod = op.encodeMod();
modReg = mod << 6;
modReg |= op.encodeR_m();
if (pos == P_OMOD) {
insn.embed(modReg);
} else {
insn.embedModReg(modReg);
}
if (mod == 1) {
if (overflowRel8(static_cast<int32_t>(op.val32)))
return setError(OVERFLOW_RANGE);
insn.emitOperand8(op.val32);
} else if (mod == 2) {
if (overflowUint16(static_cast<int32_t>(op.val32)))
return setError(OVERFLOW_RANGE);
insn.emitOperand16(op.val32);
}
break;
default:
break;
}
return OK;
}
Error AsmI8086::emitDirect(InsnI8086 &insn, const Operand &op, OprPos pos) {
insn.setSegment(encodeSegmentOverride(op.seg, REG_UNDEF));
if (pos == P_MOD)
insn.embedModReg(0006);
if (pos == P_OMOD)
insn.embed(0006);
return emitImmediate(insn, SZ_WORD, op.val32);
}
Error AsmI8086::emitOperand(InsnI8086 &insn, AddrMode mode, const Operand &op, OprPos pos) {
switch (mode) {
case M_CS:
if (pos == P_NONE) // POP CS
return setError(REGISTER_NOT_ALLOWED);
/* Fall-through */
case M_BREG:
case M_WREG:
case M_SREG:
return emitRegister(insn, op, pos);
case M_BMOD:
case M_WMOD:
case M_BMEM:
case M_WMEM:
return emitModReg(insn, op, pos);
case M_BDIR:
case M_WDIR:
return emitDirect(insn, op, P_OPR);
case M_UI16:
if (static_cast<int32_t>(op.val32) >= 0x10000 || static_cast<int32_t>(op.val32) < 0)
return setError(OVERFLOW_RANGE);
insn.emitOperand16(op.val32);
return OK;
case M_IMM:
return emitImmediate(insn, insn.oprSize(), op.val32);
case M_IOA:
if (op.val32 >= 0x100)
return setError(OVERFLOW_RANGE);
/* Fall-through */
case M_IMM8:
return emitImmediate(insn, SZ_BYTE, op.val32);
case M_REL:
case M_REL8:
return emitRelative(insn, op, mode);
case M_FAR:
if (op.val32 >= 0x10000)
return setError(OVERFLOW_RANGE);
emitImmediate(insn, SZ_WORD, op.val32);
return emitImmediate(insn, SZ_WORD, op.seg16);
case M_ISTR:
insn.emitOperand8(op.val32);
return OK;
default:
return OK;
}
}
Error AsmI8086::emitStringOperand(InsnI8086 &insn, const Operand &op, RegName seg, RegName index) {
if (op.mode == M_NONE)
return OK;
if (op.reg != REG_UNDEF || op.index != index || op.hasVal)
return setError(ILLEGAL_OPERAND);
if (seg == REG_ES && op.seg != REG_ES)
return setError(ILLEGAL_SEGMENT);
if (seg == REG_DS && op.seg != REG_UNDEF && op.seg != REG_DS)
insn.setSegment(TableI8086.segOverridePrefix(op.seg));
return OK;
}
Error AsmI8086::encodeStringInst(InsnI8086 &insn, const Operand &dst, const Operand &src) {
switch (insn.opCode() & ~1) {
case 0xA4: // MOVS ES:[DI],DS:[SI]
if (emitStringOperand(insn, dst, REG_ES, REG_DI))
return getError();
if (emitStringOperand(insn, src, REG_DS, REG_SI))
return getError();
/* Fall-through */
case 0xAA: // STOS ES:[DI]
case 0xAE: // SCAS ES:[DI]
if (emitStringOperand(insn, dst, REG_ES, REG_DI))
return getError();
break;
case 0xA6: // CMPS DS:[SI],ES:[DI]
if (emitStringOperand(insn, src, REG_ES, REG_DI))
return getError();
/* Fall-through */
case 0xAC: // LODS DS:[SI]
if (emitStringOperand(insn, dst, REG_DS, REG_SI))
return getError();
break;
}
insn.emitInsn();
return setOK();
}
Error AsmI8086::encode(Insn &_insn) {
InsnI8086 insn(_insn);
const char *endName = _parser.scanSymbol(_scan);
insn.setName(_scan, endName);
Operand dstOp, srcOp;
if (parseOperand(endName, dstOp))
return getError();
const char *p = skipSpaces(_scan);
if (*p == ',') {
if (parseOperand(p + 1, srcOp))
return getError();
p = skipSpaces(_scan);
}
if (!endOfLine(p))
return setError(GARBAGE_AT_END);
setError(dstOp.getError());
setErrorIf(srcOp.getError());
insn.setAddrMode(dstOp.mode, srcOp.mode);
if (TableI8086.searchName(insn))
return setError(TableI8086.getError());
insn.prepairModReg();
if (insn.stringInst())
return encodeStringInst(insn, dstOp, srcOp);
const AddrMode dst = insn.dstMode();
if (dst != M_NONE) {
if (emitOperand(insn, dst, dstOp, insn.dstPos()))
return getError();
}
const AddrMode src = insn.srcMode();
if (src != M_NONE) {
if (emitOperand(insn, src, srcOp, insn.srcPos()))
return getError();
}
insn.emitInsn();
return getError();
}
} // namespace i8086
} // namespace libasm
// Local Variables:
// mode: c++
// c-basic-offset: 4
// tab-width: 4
// End:
// vim: set ft=cpp et ts=4 sw=4:
| 29.086106 | 99 | 0.571083 | tgtakaoka |
c88331cf9e5b35677d9745bebea844389a49b0e9 | 12,373 | cpp | C++ | core/io/resource_importer.cpp | shinyclaw/godot | 263f7319240df6d57c779b1eb857c7f7ad6dfe47 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2021-08-04T13:34:33.000Z | 2021-08-04T13:34:33.000Z | core/io/resource_importer.cpp | shinyclaw/godot | 263f7319240df6d57c779b1eb857c7f7ad6dfe47 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | core/io/resource_importer.cpp | shinyclaw/godot | 263f7319240df6d57c779b1eb857c7f7ad6dfe47 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 1 | 2020-08-30T10:57:19.000Z | 2020-08-30T10:57:19.000Z | /*************************************************************************/
/* resource_importer.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "resource_importer.h"
#include "core/config/project_settings.h"
#include "core/os/os.h"
#include "core/variant/variant_parser.h"
bool ResourceFormatImporter::SortImporterByName::operator()(const Ref<ResourceImporter> &p_a, const Ref<ResourceImporter> &p_b) const {
return p_a->get_importer_name() < p_b->get_importer_name();
}
Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndType &r_path_and_type, bool *r_valid) const {
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) {
if (r_valid) {
*r_valid = false;
}
return err;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
if (r_valid) {
*r_valid = true;
}
int lines = 0;
String error_text;
bool path_found = false; //first match must have priority
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
memdelete(f);
return OK;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return err;
}
if (assign != String()) {
if (!path_found && assign.begins_with("path.") && r_path_and_type.path == String()) {
String feature = assign.get_slicec('.', 1);
if (OS::get_singleton()->has_feature(feature)) {
r_path_and_type.path = value;
path_found = true; //first match must have priority
}
} else if (!path_found && assign == "path") {
r_path_and_type.path = value;
path_found = true; //first match must have priority
} else if (assign == "type") {
r_path_and_type.type = ClassDB::get_compatibility_remapped_class(value);
} else if (assign == "importer") {
r_path_and_type.importer = value;
} else if (assign == "group_file") {
r_path_and_type.group_file = value;
} else if (assign == "metadata") {
r_path_and_type.metadata = value;
} else if (assign == "valid") {
if (r_valid) {
*r_valid = value;
}
}
} else if (next_tag.name != "remap") {
break;
}
}
memdelete(f);
if (r_path_and_type.path == String() || r_path_and_type.type == String()) {
return ERR_FILE_CORRUPT;
}
return OK;
}
RES ResourceFormatImporter::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
if (r_error) {
*r_error = err;
}
return RES();
}
RES res = ResourceLoader::_load(pat.path, p_path, pat.type, p_no_cache, r_error, p_use_sub_threads, r_progress);
#ifdef TOOLS_ENABLED
if (res.is_valid()) {
res->set_import_last_modified_time(res->get_last_modified_time()); //pass this, if used
res->set_import_path(pat.path);
}
#endif
return res;
}
void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const {
Set<String> found;
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
}
}
}
}
void ResourceFormatImporter::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
if (p_type == "") {
get_recognized_extensions(p_extensions);
return;
}
Set<String> found;
for (int i = 0; i < importers.size(); i++) {
String res_type = importers[i]->get_resource_type();
if (res_type == String()) {
continue;
}
if (!ClassDB::is_parent_class(res_type, p_type)) {
continue;
}
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
}
}
}
}
bool ResourceFormatImporter::exists(const String &p_path) const {
return FileAccess::exists(p_path + ".import");
}
bool ResourceFormatImporter::recognize_path(const String &p_path, const String &p_for_type) const {
return FileAccess::exists(p_path + ".import");
}
bool ResourceFormatImporter::can_be_imported(const String &p_path) const {
return ResourceFormatLoader::recognize_path(p_path);
}
int ResourceFormatImporter::get_import_order(const String &p_path) const {
Ref<ResourceImporter> importer;
if (FileAccess::exists(p_path + ".import")) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err == OK) {
importer = get_importer_by_name(pat.importer);
}
} else {
importer = get_importer_by_extension(p_path.get_extension().to_lower());
}
if (importer.is_valid()) {
return importer->get_import_order();
}
return 0;
}
bool ResourceFormatImporter::handles_type(const String &p_type) const {
for (int i = 0; i < importers.size(); i++) {
String res_type = importers[i]->get_resource_type();
if (res_type == String()) {
continue;
}
if (ClassDB::is_parent_class(res_type, p_type)) {
return true;
}
}
return true;
}
String ResourceFormatImporter::get_internal_resource_path(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return String();
}
return pat.path;
}
void ResourceFormatImporter::get_internal_resource_path_list(const String &p_path, List<String> *r_paths) {
Error err;
FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) {
return;
}
VariantParser::StreamFile stream;
stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
int lines = 0;
String error_text;
while (true) {
assign = Variant();
next_tag.fields.clear();
next_tag.name = String();
err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
if (err == ERR_FILE_EOF) {
memdelete(f);
return;
} else if (err != OK) {
ERR_PRINT("ResourceFormatImporter::get_internal_resource_path_list - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return;
}
if (assign != String()) {
if (assign.begins_with("path.")) {
r_paths->push_back(value);
} else if (assign == "path") {
r_paths->push_back(value);
}
} else if (next_tag.name != "remap") {
break;
}
}
memdelete(f);
}
String ResourceFormatImporter::get_import_group_file(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
return valid ? pat.group_file : String();
}
bool ResourceFormatImporter::is_import_valid(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
return valid;
}
String ResourceFormatImporter::get_resource_type(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return "";
}
return pat.type;
}
Variant ResourceFormatImporter::get_resource_metadata(const String &p_path) const {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return Variant();
}
return pat.metadata;
}
void ResourceFormatImporter::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
PathAndType pat;
Error err = _get_path_and_type(p_path, pat);
if (err != OK) {
return;
}
ResourceLoader::get_dependencies(pat.path, p_dependencies, p_add_types);
}
Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String &p_name) const {
for (int i = 0; i < importers.size(); i++) {
if (importers[i]->get_importer_name() == p_name) {
return importers[i];
}
}
return Ref<ResourceImporter>();
}
void ResourceFormatImporter::get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter>> *r_importers) {
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (p_extension.to_lower() == F->get()) {
r_importers->push_back(importers[i]);
}
}
}
}
Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String &p_extension) const {
Ref<ResourceImporter> importer;
float priority = 0;
for (int i = 0; i < importers.size(); i++) {
List<String> local_exts;
importers[i]->get_recognized_extensions(&local_exts);
for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (p_extension.to_lower() == F->get() && importers[i]->get_priority() > priority) {
importer = importers[i];
priority = importers[i]->get_priority();
}
}
}
return importer;
}
String ResourceFormatImporter::get_import_base_path(const String &p_for_file) const {
return ProjectSettings::IMPORTED_FILES_PATH.plus_file(p_for_file.get_file() + "-" + p_for_file.md5_text());
}
bool ResourceFormatImporter::are_import_settings_valid(const String &p_path) const {
bool valid = true;
PathAndType pat;
_get_path_and_type(p_path, pat, &valid);
if (!valid) {
return false;
}
for (int i = 0; i < importers.size(); i++) {
if (importers[i]->get_importer_name() == pat.importer) {
if (!importers[i]->are_import_settings_valid(p_path)) { //importer thinks this is not valid
return false;
}
}
}
return true;
}
String ResourceFormatImporter::get_import_settings_hash() const {
Vector<Ref<ResourceImporter>> sorted_importers = importers;
sorted_importers.sort_custom<SortImporterByName>();
String hash;
for (int i = 0; i < sorted_importers.size(); i++) {
hash += ":" + sorted_importers[i]->get_importer_name() + ":" + sorted_importers[i]->get_import_settings_string();
}
return hash.md5_text();
}
ResourceFormatImporter *ResourceFormatImporter::singleton = nullptr;
ResourceFormatImporter::ResourceFormatImporter() {
singleton = this;
}
| 29.600478 | 163 | 0.649721 | shinyclaw |
c8836aeabab6bd7274fec72b2850b875afcacadb | 2,684 | cc | C++ | tensorflow/core/kernels/data/prefetch_autotuner.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | 1 | 2022-03-20T04:34:49.000Z | 2022-03-20T04:34:49.000Z | tensorflow/core/kernels/data/prefetch_autotuner.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | 1 | 2022-03-24T00:13:13.000Z | 2022-03-24T00:13:20.000Z | tensorflow/core/kernels/data/prefetch_autotuner.cc | kim-com/tensorflow | 4301e3f34b8da528c58bdafe05cd66c8a55fce9e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/prefetch_autotuner.h"
#include <memory>
#include "tensorflow/core/framework/model.h"
namespace tensorflow {
namespace data {
PrefetchAutotuner::PrefetchAutotuner(std::shared_ptr<model::Model> model,
std::shared_ptr<model::Node> prefetch_node,
int64_t initial_buffer_size,
int64_t buffer_size_min)
: model_(model),
prefetch_node_(prefetch_node),
buffer_limit_(initial_buffer_size) {
if (initial_buffer_size == model::kAutotune) {
mode_ = Mode::kUpswing;
buffer_limit_ = std::max(int64_t{1}, buffer_size_min);
}
}
namespace {
// Determines what strategy to use for increasing the buffer size limit. For
// limits less than the threshold, an exponential increase is used, while for
// limits greater than or equal to the threshold, a linear increase is used.
size_t kBufferLimitThreshold = 2048;
} // namespace
void PrefetchAutotuner::RecordConsumption(size_t current_buffer_size) {
switch (mode_) {
case Mode::kDisabled:
return;
case Mode::kUpswing:
if (static_cast<int64_t>(current_buffer_size) == buffer_limit_) {
mode_ = Mode::kDownswing;
}
return;
case Mode::kDownswing:
if (current_buffer_size == 0) {
double new_buffer_limit = buffer_limit_;
if (buffer_limit_ >= static_cast<int64_t>(kBufferLimitThreshold)) {
new_buffer_limit += kBufferLimitThreshold;
} else {
new_buffer_limit *= 2;
}
if (model_ != nullptr && prefetch_node_ != nullptr &&
model_->AllocateBufferedBytes(
prefetch_node_->MaximumBufferedBytes() *
(new_buffer_limit - buffer_limit_) /
static_cast<double>(buffer_limit_))) {
buffer_limit_ = new_buffer_limit;
}
mode_ = Mode::kUpswing;
}
return;
}
}
} // namespace data
} // namespace tensorflow
| 34.410256 | 80 | 0.653502 | kim-com |
c883ca21695e634dc712e6db8cf5ffee436cc3af | 4,252 | hpp | C++ | src/px4/mavlink/common/mavlink_msg_altitude.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 10 | 2021-03-15T03:58:06.000Z | 2021-12-30T15:33:38.000Z | src/px4/mavlink/common/mavlink_msg_altitude.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 1 | 2021-09-09T15:29:31.000Z | 2021-09-09T15:29:31.000Z | src/px4/mavlink/common/mavlink_msg_altitude.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 8 | 2021-10-09T08:47:53.000Z | 2022-01-17T07:45:33.000Z | // MESSAGE ALTITUDE support class
#pragma once
namespace mavlink {
namespace common {
namespace msg {
/**
* @brief ALTITUDE message
*
* The current system altitude.
*/
struct ALTITUDE : mavlink::Message {
static constexpr msgid_t MSG_ID = 141;
static constexpr size_t LENGTH = 32;
static constexpr size_t MIN_LENGTH = 32;
static constexpr uint8_t CRC_EXTRA = 47;
static constexpr auto NAME = "ALTITUDE";
uint64_t time_usec; /*< [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude of the number. */
float altitude_monotonic; /*< [m] This altitude measure is initialized on system boot and monotonic (it is never reset, but represents the local altitude change). The only guarantee on this field is that it will never be reset and is consistent within a flight. The recommended value for this field is the uncorrected barometric altitude at boot time. This altitude will also drift and vary between flights. */
float altitude_amsl; /*< [m] This altitude measure is strictly above mean sea level and might be non-monotonic (it might reset on events like GPS lock or when a new QNH value is set). It should be the altitude to which global altitude waypoints are compared to. Note that it is *not* the GPS altitude, however, most GPS modules already output MSL by default and not the WGS84 altitude. */
float altitude_local; /*< [m] This is the local altitude in the local coordinate frame. It is not the altitude above home, but in reference to the coordinate origin (0, 0, 0). It is up-positive. */
float altitude_relative; /*< [m] This is the altitude above the home position. It resets on each change of the current home position. */
float altitude_terrain; /*< [m] This is the altitude above terrain. It might be fed by a terrain database or an altimeter. Values smaller than -1000 should be interpreted as unknown. */
float bottom_clearance; /*< [m] This is not the altitude, but the clear space below the system according to the fused clearance estimate. It generally should max out at the maximum range of e.g. the laser altimeter. It is generally a moving target. A negative value indicates no measurement available. */
inline std::string get_name(void) const override
{
return NAME;
}
inline Info get_message_info(void) const override
{
return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA };
}
inline std::string to_yaml(void) const override
{
std::stringstream ss;
ss << NAME << ":" << std::endl;
ss << " time_usec: " << time_usec << std::endl;
ss << " altitude_monotonic: " << altitude_monotonic << std::endl;
ss << " altitude_amsl: " << altitude_amsl << std::endl;
ss << " altitude_local: " << altitude_local << std::endl;
ss << " altitude_relative: " << altitude_relative << std::endl;
ss << " altitude_terrain: " << altitude_terrain << std::endl;
ss << " bottom_clearance: " << bottom_clearance << std::endl;
return ss.str();
}
inline void serialize(mavlink::MsgMap &map) const override
{
map.reset(MSG_ID, LENGTH);
map << time_usec; // offset: 0
map << altitude_monotonic; // offset: 8
map << altitude_amsl; // offset: 12
map << altitude_local; // offset: 16
map << altitude_relative; // offset: 20
map << altitude_terrain; // offset: 24
map << bottom_clearance; // offset: 28
}
inline void deserialize(mavlink::MsgMap &map) override
{
map >> time_usec; // offset: 0
map >> altitude_monotonic; // offset: 8
map >> altitude_amsl; // offset: 12
map >> altitude_local; // offset: 16
map >> altitude_relative; // offset: 20
map >> altitude_terrain; // offset: 24
map >> bottom_clearance; // offset: 28
}
};
} // namespace msg
} // namespace common
} // namespace mavlink
| 50.023529 | 414 | 0.64158 | mfkiwl |
c884576ef618b792c52efeff13be551da01cebef | 2,318 | cpp | C++ | gym/index00_09/ioi2021_03/EE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | 6 | 2020-10-12T05:07:03.000Z | 2021-09-11T14:54:58.000Z | gym/index00_09/ioi2021_03/EE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | null | null | null | gym/index00_09/ioi2021_03/EE.cpp | daklqw/IOI2021-training | 4f21cef8eec47330e3db77a3d90cbe2309fa8294 | [
"Apache-2.0"
] | 2 | 2021-02-09T02:06:31.000Z | 2021-10-06T01:25:08.000Z | #include <bits/stdc++.h>
const int MAXN = 21;
typedef long double db;
const db eps = 1e-8;
const db g = 9.80665;
int A[MAXN][MAXN];
int H, W, R, V;
int pw(int x) { return x * x; }
std::pair<db, db> normal(db a, db b) {
db L = sqrtl(a * a + b * b);
return std::make_pair(a / L, b / L);
}
bool judge(int sx, int sy, int dx, int dy) {
db L = R * sqrtl(pw(sx - dx) + pw(sy - dy));
db c = A[dx][dy] - A[sx][sy];
db a = g * L * L / 2 / V / V;
c += a;
db b = -L;
db dta = b * b - 4 * a * c;
if (dta < -eps) return false;
if (dta < 0) dta = 0;
dta = sqrtl(dta);
db vx, vy;
std::tie(vx, vy) = normal(a * 2, -b + dta);
vx *= V, vy *= V;
db T = L / vx;
int l = std::min(sx, dx);
int r = std::max(sx, dx);
for (int i = l; i < r; ++i) {
db sc = (((i + 1) - (sx + 0.5)) / (dx - sx));
db t = T * sc;
db y = sc * (dy - sy) + sy + 0.5;
db h = vy * t - g * t * t / 2 + A[sx][sy];
int mh = 0;
for (int j = (int) y - 1; j <= (int) y + 1; ++j)
if (j - eps <= y && y <= j + 1 + eps)
mh = std::max(mh, std::max(A[i][j], A[i + 1][j]));
if (h < mh - eps) return false;
}
l = std::min(sy, dy);
r = std::max(sy, dy);
for (int i = l; i < r; ++i) {
db sc = (((i + 1) - (sy + 0.5)) / (dy - sy));
db t = T * sc;
db x = sc * (dx - sx) + sx + 0.5;
db h = vy * t - g * t * t / 2 + A[sx][sy];
int mh = 0;
for (int j = (int) x - 1; j <= (int) x + 1; ++j)
if (j - eps <= x && x <= j + 1 + eps)
mh = std::max(mh, std::max(A[j][i], A[j][i + 1]));
if (h < mh - eps) return false;
}
return true;
}
int dis[MAXN][MAXN];
int main() {
std::ios_base::sync_with_stdio(false), std::cin.tie(0);
int sx, sy;
std::cin >> W >> H >> R >> V >> sy >> sx;
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j)
std::cin >> A[i][j];
memset(dis, -1, sizeof dis);
dis[sx][sy] = 0;
std::queue<std::pair<int, int> > que;
que.emplace(sx, sy);
while (!que.empty()) {
int x, y;
std::tie(x, y) = que.front();
que.pop();
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j)
if (dis[i][j] == -1 && judge(x, y, i, j)) {
dis[i][j] = dis[x][y] + 1;
que.emplace(i, j);
}
}
for (int i = 1; i <= H; ++i)
for (int j = 1; j <= W; ++j) {
if (dis[i][j] == -1)
std::cout << 'X';
else
std::cout << dis[i][j];
std::cout << (" \n" [j == W]);
}
return 0;
}
| 26.044944 | 56 | 0.443054 | daklqw |
c8866e929e52292f1151f1a1e7830e9a194ccccd | 58 | cpp | C++ | main.cpp | JohnyJohnes/AlgorithmsCpp | bd1a1e7fec6e7c854a32f36349b644bb7d80f2b4 | [
"MIT"
] | null | null | null | main.cpp | JohnyJohnes/AlgorithmsCpp | bd1a1e7fec6e7c854a32f36349b644bb7d80f2b4 | [
"MIT"
] | null | null | null | main.cpp | JohnyJohnes/AlgorithmsCpp | bd1a1e7fec6e7c854a32f36349b644bb7d80f2b4 | [
"MIT"
] | null | null | null | //
// Created by Saxion on 10/12/2018.
//
int main(){
}
| 7.25 | 35 | 0.551724 | JohnyJohnes |
c886d1e99ae0c39db9519edec147e5de1610f3ed | 14,414 | cpp | C++ | source/game/rules/UserGroup.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | 2 | 2021-05-02T18:37:48.000Z | 2021-07-18T16:18:14.000Z | source/game/rules/UserGroup.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | source/game/rules/UserGroup.cpp | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | // Copyright (C) 2007 Id Software, Inc.
//
#include "../precompiled.h"
#pragma hdrstop
#if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE )
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "UserGroup.h"
#include "../Player.h"
#include "../guis/UIList.h"
typedef sdPair< const char*, userPermissionFlags_t > permissionName_t;
permissionName_t permissionNames[] = {
permissionName_t( "adminKick", PF_ADMIN_KICK ),
permissionName_t( "adminBan", PF_ADMIN_BAN ),
permissionName_t( "adminSetTeam", PF_ADMIN_SETTEAM ),
permissionName_t( "adminChangeCampaign", PF_ADMIN_CHANGE_CAMPAIGN ),
permissionName_t( "adminChangeMap", PF_ADMIN_CHANGE_MAP ),
permissionName_t( "adminGlobalMute", PF_ADMIN_GLOBAL_MUTE ),
permissionName_t( "adminGlobalVOIPMute", PF_ADMIN_GLOBAL_MUTE_VOIP ),
permissionName_t( "adminPlayerMute", PF_ADMIN_PLAYER_MUTE ),
permissionName_t( "adminPlayerVOIPMute", PF_ADMIN_PLAYER_MUTE_VOIP ),
permissionName_t( "adminWarn", PF_ADMIN_WARN ),
permissionName_t( "adminRestartMap", PF_ADMIN_RESTART_MAP ),
permissionName_t( "adminRestartCampaign", PF_ADMIN_RESTART_CAMPAIGN ),
permissionName_t( "adminStartMatch", PF_ADMIN_START_MATCH ),
permissionName_t( "adminExecConfig", PF_ADMIN_EXEC_CONFIG ),
permissionName_t( "adminShuffleTeams", PF_ADMIN_SHUFFLE_TEAMS ),
permissionName_t( "adminAddBot", PF_ADMIN_ADD_BOT ),
permissionName_t( "adminAdjustBots", PF_ADMIN_ADJUST_BOTS ),
permissionName_t( "adminDisableProficiency", PF_ADMIN_DISABLE_PROFICIENCY ),
permissionName_t( "adminSetTimeLimit", PF_ADMIN_SET_TIMELIMIT ),
permissionName_t( "adminSetTeamDamage", PF_ADMIN_SET_TEAMDAMAGE ),
permissionName_t( "adminSetTeamBalance", PF_ADMIN_SET_TEAMBALANCE ),
permissionName_t( "noBan", PF_NO_BAN ),
permissionName_t( "noKick", PF_NO_KICK ),
permissionName_t( "noMute", PF_NO_MUTE ),
permissionName_t( "noMuteVOIP", PF_NO_MUTE_VOIP ),
permissionName_t( "noWarn", PF_NO_WARN ),
permissionName_t( "quietLogin", PF_QUIET_LOGIN )
};
int numPermissionNames = _arraycount( permissionNames );
/*
===============================================================================
sdUserGroup
===============================================================================
*/
/*
============
sdUserGroup::sdUserGroup
============
*/
sdUserGroup::sdUserGroup( void ) : superUser( false ), voteLevel( -1 ), needsLogin( false ) {
}
/*
============
sdUserGroup::Write
============
*/
void sdUserGroup::Write( idBitMsg& msg ) const {
msg.WriteString( GetName() );
for ( int i = 0; i < flags.Size(); i++ ) {
msg.WriteLong( flags.GetDirect()[ i ] );
}
msg.WriteLong( controlGroups.Num() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
msg.WriteLong( controlGroups[ i ].second );
}
msg.WriteLong( voteLevel );
msg.WriteBool( needsLogin );
}
/*
============
sdUserGroup::Read
============
*/
void sdUserGroup::Read( const idBitMsg& msg ) {
char buffer[ 512 ];
msg.ReadString( buffer, sizeof( buffer ) );
SetName( buffer );
for ( int i = 0; i < flags.Size(); i++ ) {
flags.GetDirect()[ i ] = msg.ReadLong();
}
controlGroups.SetNum( msg.ReadLong() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
controlGroups[ i ].second = msg.ReadLong();
}
voteLevel = msg.ReadLong();
needsLogin = msg.ReadBool();
}
/*
============
sdUserGroup::Write
============
*/
void sdUserGroup::Write( idFile* file ) const {
file->WriteString( GetName() );
for ( int i = 0; i < flags.Size(); i++ ) {
file->WriteInt( flags.GetDirect()[ i ] );
}
file->WriteInt( controlGroups.Num() );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
file->WriteInt( controlGroups[ i ].second );
}
file->WriteInt( voteLevel );
file->WriteBool( needsLogin );
}
/*
============
sdUserGroup::Read
============
*/
void sdUserGroup::Read( idFile* file ) {
file->ReadString( name );
for ( int i = 0; i < flags.Size(); i++ ) {
file->ReadInt( flags.GetDirect()[ i ] );
}
int count;
file->ReadInt( count );
controlGroups.SetNum( count );
for ( int i = 0; i < controlGroups.Num(); i++ ) {
file->ReadInt( controlGroups[ i ].second );
}
file->ReadInt( voteLevel );
file->ReadBool( needsLogin );
}
/*
============
sdUserGroup::ParseControl
============
*/
bool sdUserGroup::ParseControl( idLexer& src ) {
if ( !src.ExpectTokenString( "{" ) ) {
return false;
}
idToken token;
while ( true ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
if ( token == "}" ) {
break;
}
sdPair< idStr, int >& control = controlGroups.Alloc();
control.first = token;
control.second = -1;
}
return true;
}
/*
============
sdUserGroup::Parse
============
*/
bool sdUserGroup::Parse( idLexer& src ) {
idToken token;
if ( !src.ReadToken( &token ) ) {
src.Warning( "No Name Specified" );
return false;
}
SetName( token );
if ( !src.ExpectTokenString( "{" ) ) {
return false;
}
while ( true ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
if ( token == "}" ) {
break;
}
if ( token.Icmp( "password" ) == 0 ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Unexpected end of file" );
return false;
}
// Gordon: The example file will have password set to password, this should never be a valid password
if ( token.Icmp( "password" ) != 0 ) {
SetPassword( token );
}
continue;
}
if ( token.Icmp( "control" ) == 0 ) {
if ( !ParseControl( src ) ) {
src.Warning( "Failed to parse control groups" );
return false;
}
continue;
}
if ( token.Icmp( "voteLevel" ) == 0 ) {
if ( !src.ReadToken( &token ) ) {
src.Warning( "Failed to parse voteLevel" );
return false;
}
voteLevel = token.GetIntValue();
continue;
}
int i;
for ( i = 0; i < numPermissionNames; i++ ) {
if ( idStr::Icmp( permissionNames[ i ].first, token ) ) {
continue;
}
GivePermission( permissionNames[ i ].second );
break;
}
if ( i != numPermissionNames ) {
continue;
}
src.Warning( "Unexpected token '%s'", token.c_str() );
return false;
}
return true;
}
/*
============
sdUserGroup::Parse
============
*/
void sdUserGroup::PostParseFixup( void ) {
sdUserGroupManagerLocal& groupManager = sdUserGroupManager::GetInstance();
for ( int i = 0; i < controlGroups.Num(); i++ ) {
sdPair< idStr, int >& control = controlGroups[ i ];
control.second = groupManager.FindGroup( control.first );
if ( control.second == -1 ) {
gameLocal.Warning( "sdUserGroup::PostParseFixup Control Group '%s' not found", control.first.c_str() );
}
}
}
/*
============
sdUserGroup::CanControl
============
*/
bool sdUserGroup::CanControl( const sdUserGroup& group ) const {
if ( superUser ) {
return true;
}
sdUserGroupManagerLocal& groupManager = sdUserGroupManager::GetInstance();
for ( int i = 0; i < controlGroups.Num(); i++ ) {
int index = controlGroups[ i ].second;
if ( index == -1 ) {
continue;
}
if ( &groupManager.GetGroup( index ) == &group ) {
return true;
}
}
return false;
}
/*
===============================================================================
sdUserGroupManagerLocal
===============================================================================
*/
/*
============
sdUserGroupManagerLocal::sdUserGroupManagerLocal
============
*/
sdUserGroupManagerLocal::sdUserGroupManagerLocal( void ) {
consoleGroup.SetName( "<CONSOLE>" ); // users coming from the console will use this user group which has full permissions
consoleGroup.MakeSuperUser();
defaultGroup = -1;
}
/*
============
sdUserGroupManagerLocal::sdUserGroupManagerLocal
============
*/
sdUserGroupManagerLocal::~sdUserGroupManagerLocal( void ) {
}
/*
============
sdUserGroupManagerLocal::Init
============
*/
void sdUserGroupManagerLocal::Init( void ) {
idStr groupNames[ MAX_CLIENTS ];
for ( int i = 0; i < MAX_CLIENTS; i++ ) {
nextLoginTime[ i ] = 0;
idPlayer* player = gameLocal.GetClient( i );
if ( !player ) {
continue;
}
groupNames[ i ] = GetGroup( player->GetUserGroup() ).GetName();
}
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
configs.Clear();
votes.Clear();
// load user groups
idLexer src( LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS | LEXFL_ALLOWPATHNAMES | LEXFL_ALLOWMULTICHARLITERALS | LEXFL_ALLOWBACKSLASHSTRINGCONCAT | LEXFL_NOFATALERRORS );
src.LoadFile( "usergroups.dat" );
if ( !src.IsLoaded() ) {
return;
}
idToken token;
while ( true ) {
if ( !src.ReadToken( &token ) ) {
break;
}
if ( !token.Icmp( "group" ) ) {
sdUserGroup& group = userGroups.Alloc();
if ( !group.Parse( src ) ) {
src.Warning( "Error Parsing Group" );
break;
}
} else if ( !token.Icmp( "configs" ) ) {
if ( !configs.Parse( src ) ) {
src.Warning( "Error Parsing configs" );
break;
}
} else if ( !token.Icmp( "votes" ) ) {
if ( !votes.Parse( src ) ) {
src.Warning( "Error Parsing votes" );
break;
}
} else {
src.Warning( "Invalid Token '%s'", token.c_str() );
break;
}
}
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
for ( int i = 0; i < MAX_CLIENTS; i++ ) {
idPlayer* player = gameLocal.GetClient( i );
if ( !player ) {
continue;
}
player->SetUserGroup( FindGroup( groupNames[ i ] ) );
}
for ( int i = 0; i < userGroups.Num(); i++ ) {
userGroups[ i ].PostParseFixup();
}
if ( gameLocal.isServer ) {
WriteNetworkData( sdReliableMessageClientInfoAll() );
}
}
/*
============
sdUserGroupManagerLocal::FindGroup
============
*/
int sdUserGroupManagerLocal::FindGroup( const char* name ) {
for ( int i = 0; i < userGroups.Num(); i++ ) {
if ( idStr::Icmp( userGroups[ i ].GetName(), name ) ) {
continue;
}
return i;
}
return -1;
}
/*
============
sdUserGroupManagerLocal::Login
============
*/
bool sdUserGroupManagerLocal::Login( idPlayer* player, const char* password ) {
int now = MS2SEC( sys->Milliseconds() );
if ( now < nextLoginTime[ player->entityNumber ] ) {
return false;
}
nextLoginTime[ player->entityNumber ] = now + 5; // Gordon: limit password brute forcing
for ( int i = 0; i < userGroups.Num(); i++ ) {
if ( !userGroups[ i ].CheckPassword( password ) ) {
continue;
}
player->SetUserGroup( i );
return true;
}
return false;
}
/*
============
sdUserGroupManagerLocal::CanLogin
============
*/
bool sdUserGroupManagerLocal::CanLogin() const {
for ( int i = 0; i < userGroups.Num(); i++ ) {
if( userGroups[ i ].HasPassword() ) {
return true;
}
}
return false;
}
/*
============
sdUserGroupManagerLocal::ReadNetworkData
============
*/
void sdUserGroupManagerLocal::ReadNetworkData( const idBitMsg& msg ) {
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
int count = msg.ReadLong();
for ( int i = 0; i < count; i++ ) {
sdUserGroup& group = userGroups.Alloc();
group.Read( msg );
}
msg.ReadDeltaDict( configs, NULL );
msg.ReadDeltaDict( votes, NULL );
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
}
/*
============
sdUserGroupManagerLocal::WriteNetworkData
============
*/
void sdUserGroupManagerLocal::WriteNetworkData( const sdReliableMessageClientInfoBase& target ) {
sdReliableServerMessage msg( GAME_RELIABLE_SMESSAGE_USERGROUPS );
msg.WriteLong( userGroups.Num() - 1 );
for ( int i = 1; i < userGroups.Num(); i++ ) {
sdUserGroup& group = userGroups[ i ];
group.Write( msg );
}
msg.WriteDeltaDict( configs, NULL );
msg.WriteDeltaDict( votes, NULL );
msg.Send( target );
}
/*
============
sdUserGroupManagerLocal::CreateUserGroupList
============
*/
void sdUserGroupManagerLocal::CreateUserGroupList( sdUIList* list ) {
sdUIList::ClearItems( list );
idPlayer* localPlayer = gameLocal.GetLocalPlayer();
if ( !localPlayer ) {
return;
}
const sdUserGroup& localGroup = gameLocal.isClient ? GetGroup( localPlayer->GetUserGroup() ) : GetConsoleGroup();
int index = 0;
for ( int i = 1; i < userGroups.Num(); i++ ) {
if ( !localGroup.CanControl( userGroups[ i ] ) ) {
continue;
}
sdUIList::InsertItem( list, va( L"%hs", userGroups[ i ].GetName() ), index, 0 );
index++;
}
/*
for ( int i = 1; i < userGroups.Num(); i++ ) {
sdUIList::InsertItem( list, va( L"%hs", userGroups[ i ].GetName() ), i - 1, 0 );
}
*/
}
/*
============
sdUserGroupManagerLocal::CreateServerConfigList
============
*/
void sdUserGroupManagerLocal::CreateServerConfigList( sdUIList* list ) {
sdUIList::ClearItems( list );
for ( int i = 0; i < configs.GetNumKeyVals(); i++ ) {
const idKeyValue* kv = configs.GetKeyVal( i );
sdUIList::InsertItem( list, va( L"%hs", kv->GetKey().c_str() ), i, 0 );
}
}
/*
============
sdUserGroupManagerLocal::Write
============
*/
void sdUserGroupManagerLocal::Write( idFile* file ) const {
file->WriteInt( userGroups.Num() - 1 );
for ( int i = 1; i < userGroups.Num(); i++ ) {
const sdUserGroup& group = userGroups[ i ];
group.Write( file );
}
configs.WriteToFileHandle( file );
votes.WriteToFileHandle( file );
}
/*
============
sdUserGroupManagerLocal::Read
============
*/
void sdUserGroupManagerLocal::Read( idFile* file ) {
userGroups.Clear();
userGroups.Alloc().SetName( "<DEFAULT>" );
int count;
file->ReadInt( count );
for ( int i = 0; i < count; i++ ) {
sdUserGroup& group = userGroups.Alloc();
group.Read( file );
}
configs.ReadFromFileHandle( file );
votes.ReadFromFileHandle( file );
defaultGroup = FindGroup( "default" );
if ( defaultGroup == -1 ) {
defaultGroup = 0;
}
}
/*
============
sdUserGroupManagerLocal::GetVoteLevel
============
*/
int sdUserGroupManagerLocal::GetVoteLevel( const char* voteName ) {
return votes.GetInt( voteName, "-1" );
}
| 23.47557 | 177 | 0.594769 | JasonHutton |
c88703d91472e8d16bc83873acf6e26e15aa076a | 432 | cpp | C++ | src/data/binary_tree/binary_tree.unit.cpp | Tomcus/escape-ge | 592bfa0a7206ea7c9c6fef4de51fa87450dfce70 | [
"MIT"
] | null | null | null | src/data/binary_tree/binary_tree.unit.cpp | Tomcus/escape-ge | 592bfa0a7206ea7c9c6fef4de51fa87450dfce70 | [
"MIT"
] | null | null | null | src/data/binary_tree/binary_tree.unit.cpp | Tomcus/escape-ge | 592bfa0a7206ea7c9c6fef4de51fa87450dfce70 | [
"MIT"
] | null | null | null | #include "binary_tree/binary_tree.hpp"
#include <catch2/catch_test_macros.hpp>
TEST_CASE("Binary tree tests with simple value type (int)", "[unit][binaryTree][binary_tree]") {
esc::data::BinaryTreeHeap<int> heap;
SECTION("Simple adding") {
heap.push(120);
heap.push(42);
heap.push(12);
heap.push(13);
heap.push(43);
heap.push(121);
REQUIRE(heap.size() == 6);
}
} | 27 | 96 | 0.604167 | Tomcus |
c88a47dd948b4abaade3bb380ab9606dab9b80ed | 2,394 | cc | C++ | selfdrive/ui/qt/window.cc | SamuelSandoval/openpilot | a337097b5ee515560e9f1a804b997753767d3c9a | [
"MIT"
] | 20 | 2020-12-04T12:20:57.000Z | 2022-03-31T00:40:15.000Z | selfdrive/ui/qt/window.cc | SamuelSandoval/openpilot | a337097b5ee515560e9f1a804b997753767d3c9a | [
"MIT"
] | 6 | 2020-03-06T18:13:55.000Z | 2020-07-20T05:10:20.000Z | selfdrive/ui/qt/window.cc | SamuelSandoval/openpilot | a337097b5ee515560e9f1a804b997753767d3c9a | [
"MIT"
] | 113 | 2020-10-08T07:37:05.000Z | 2022-02-12T04:26:34.000Z | #include "window.hpp"
#include "selfdrive/hardware/hw.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) {
main_layout = new QStackedLayout;
main_layout->setMargin(0);
homeWindow = new HomeWindow(this);
main_layout->addWidget(homeWindow);
settingsWindow = new SettingsWindow(this);
main_layout->addWidget(settingsWindow);
onboardingWindow = new OnboardingWindow(this);
main_layout->addWidget(onboardingWindow);
QObject::connect(homeWindow, SIGNAL(openSettings()), this, SLOT(openSettings()));
QObject::connect(homeWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
QObject::connect(homeWindow, SIGNAL(offroadTransition(bool)), this, SLOT(offroadTransition(bool)));
QObject::connect(homeWindow, SIGNAL(offroadTransition(bool)), settingsWindow, SIGNAL(offroadTransition(bool)));
QObject::connect(settingsWindow, SIGNAL(closeSettings()), this, SLOT(closeSettings()));
QObject::connect(settingsWindow, SIGNAL(reviewTrainingGuide()), this, SLOT(reviewTrainingGuide()));
// start at onboarding
main_layout->setCurrentWidget(onboardingWindow);
QObject::connect(onboardingWindow, SIGNAL(onboardingDone()), this, SLOT(closeSettings()));
onboardingWindow->updateActiveScreen();
// no outline to prevent the focus rectangle
setLayout(main_layout);
setStyleSheet(R"(
* {
font-family: Inter;
outline: none;
}
)");
}
void MainWindow::offroadTransition(bool offroad){
if(!offroad){
closeSettings();
}
}
void MainWindow::openSettings() {
main_layout->setCurrentWidget(settingsWindow);
}
void MainWindow::closeSettings() {
main_layout->setCurrentWidget(homeWindow);
}
void MainWindow::reviewTrainingGuide() {
main_layout->setCurrentWidget(onboardingWindow);
onboardingWindow->updateActiveScreen();
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event){
// wake screen on tap
if (event->type() == QEvent::MouseButtonPress) {
homeWindow->glWindow->wake();
}
// filter out touches while in android activity
#ifdef QCOM
const QList<QEvent::Type> filter_events = {QEvent::MouseButtonPress, QEvent::MouseMove, QEvent::TouchBegin, QEvent::TouchUpdate, QEvent::TouchEnd};
if (HardwareEon::launched_activity && filter_events.contains(event->type())) {
HardwareEon::check_activity();
if (HardwareEon::launched_activity) {
return true;
}
}
#endif
return false;
}
| 31.5 | 149 | 0.739766 | SamuelSandoval |
c88b0daeb5d1926f3af3443953c3e9c87226aba1 | 12,236 | cpp | C++ | Testbed/Framework/Test.cpp | blackberry/Box2D | 0462d125a55ef2ed448aa79861d34c2c18ffd39f | [
"Zlib"
] | 5 | 2015-04-13T06:43:30.000Z | 2020-08-26T00:53:17.000Z | Testbed/Framework/Test.cpp | blackberry/Box2D | 0462d125a55ef2ed448aa79861d34c2c18ffd39f | [
"Zlib"
] | null | null | null | Testbed/Framework/Test.cpp | blackberry/Box2D | 0462d125a55ef2ed448aa79861d34c2c18ffd39f | [
"Zlib"
] | 2 | 2015-06-14T04:01:33.000Z | 2019-02-15T19:10:46.000Z | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "Test.h"
#include <cstdio>
using namespace std;
#ifdef __QNX__
GLESDebugDraw Test::m_debugDraw;
#endif
void DestructionListener::SayGoodbye(b2Joint* joint)
{
if (test->m_mouseJoint == joint)
{
test->m_mouseJoint = NULL;
}
else
{
test->JointDestroyed(joint);
}
}
Test::Test()
{
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
m_world = new b2World(gravity);
m_bomb = NULL;
m_textLine = 30;
m_mouseJoint = NULL;
m_pointCount = 0;
m_destructionListener.test = this;
m_world->SetDestructionListener(&m_destructionListener);
m_world->SetContactListener(this);
m_world->SetDebugDraw(&m_debugDraw);
m_bombSpawning = false;
m_stepCount = 0;
b2BodyDef bodyDef;
m_groundBody = m_world->CreateBody(&bodyDef);
memset(&m_maxProfile, 0, sizeof(b2Profile));
memset(&m_totalProfile, 0, sizeof(b2Profile));
}
Test::~Test()
{
// By deleting the world, we delete the bomb, mouse joint, etc.
delete m_world;
m_world = NULL;
}
void Test::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
const b2Manifold* manifold = contact->GetManifold();
if (manifold->pointCount == 0)
{
return;
}
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints];
b2GetPointStates(state1, state2, oldManifold, manifold);
b2WorldManifold worldManifold;
contact->GetWorldManifold(&worldManifold);
for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i)
{
ContactPoint* cp = m_points + m_pointCount;
cp->fixtureA = fixtureA;
cp->fixtureB = fixtureB;
cp->position = worldManifold.points[i];
cp->normal = worldManifold.normal;
cp->state = state2[i];
++m_pointCount;
}
}
void Test::DrawTitle(int x, int y, const char *string)
{
m_debugDraw.DrawString(x, y, string);
}
class QueryCallback : public b2QueryCallback
{
public:
QueryCallback(const b2Vec2& point)
{
m_point = point;
m_fixture = NULL;
}
bool ReportFixture(b2Fixture* fixture)
{
b2Body* body = fixture->GetBody();
if (body->GetType() == b2_dynamicBody)
{
bool inside = fixture->TestPoint(m_point);
if (inside)
{
m_fixture = fixture;
// We are done, terminate the query.
return false;
}
}
// Continue the query.
return true;
}
b2Vec2 m_point;
b2Fixture* m_fixture;
};
void Test::MouseDown(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint != NULL)
{
return;
}
// Make a small box.
b2AABB aabb;
b2Vec2 d;
d.Set(0.001f, 0.001f);
aabb.lowerBound = p - d;
aabb.upperBound = p + d;
// Query the world for overlapping shapes.
QueryCallback callback(p);
m_world->QueryAABB(&callback, aabb);
if (callback.m_fixture)
{
b2Body* body = callback.m_fixture->GetBody();
b2MouseJointDef md;
md.bodyA = m_groundBody;
md.bodyB = body;
md.target = p;
md.maxForce = 1000.0f * body->GetMass();
m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&md);
body->SetAwake(true);
}
}
void Test::SpawnBomb(const b2Vec2& worldPt)
{
m_bombSpawnPoint = worldPt;
m_bombSpawning = true;
}
void Test::CompleteBombSpawn(const b2Vec2& p)
{
if (m_bombSpawning == false)
{
return;
}
const float multiplier = 30.0f;
b2Vec2 vel = m_bombSpawnPoint - p;
vel *= multiplier;
LaunchBomb(m_bombSpawnPoint,vel);
m_bombSpawning = false;
}
void Test::ShiftMouseDown(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint != NULL)
{
return;
}
SpawnBomb(p);
}
void Test::MouseUp(const b2Vec2& p)
{
if (m_mouseJoint)
{
m_world->DestroyJoint(m_mouseJoint);
m_mouseJoint = NULL;
}
if (m_bombSpawning)
{
CompleteBombSpawn(p);
}
}
void Test::MouseMove(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint)
{
m_mouseJoint->SetTarget(p);
}
}
void Test::LaunchBomb()
{
b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f);
b2Vec2 v = -5.0f * p;
LaunchBomb(p, v);
}
void Test::LaunchBomb(const b2Vec2& position, const b2Vec2& velocity)
{
if (m_bomb)
{
m_world->DestroyBody(m_bomb);
m_bomb = NULL;
}
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position = position;
bd.bullet = true;
m_bomb = m_world->CreateBody(&bd);
m_bomb->SetLinearVelocity(velocity);
b2CircleShape circle;
circle.m_radius = 0.3f;
b2FixtureDef fd;
fd.shape = &circle;
fd.density = 20.0f;
fd.restitution = 0.0f;
b2Vec2 minV = position - b2Vec2(0.3f,0.3f);
b2Vec2 maxV = position + b2Vec2(0.3f,0.3f);
b2AABB aabb;
aabb.lowerBound = minV;
aabb.upperBound = maxV;
m_bomb->CreateFixture(&fd);
}
void Test::Step(Settings* settings)
{
float32 timeStep = settings->hz > 0.0f ? 1.0f / settings->hz : float32(0.0f);
if (settings->pause)
{
if (settings->singleStep)
{
settings->singleStep = 0;
}
else
{
timeStep = 0.0f;
}
m_debugDraw.DrawString(5, m_textLine, "****PAUSED****");
m_textLine += 15;
}
uint32 flags = 0;
flags += settings->drawShapes * b2Draw::e_shapeBit;
flags += settings->drawJoints * b2Draw::e_jointBit;
flags += settings->drawAABBs * b2Draw::e_aabbBit;
flags += settings->drawPairs * b2Draw::e_pairBit;
flags += settings->drawCOMs * b2Draw::e_centerOfMassBit;
m_debugDraw.SetFlags(flags);
m_world->SetWarmStarting(settings->enableWarmStarting > 0);
m_world->SetContinuousPhysics(settings->enableContinuous > 0);
m_world->SetSubStepping(settings->enableSubStepping > 0);
m_pointCount = 0;
m_world->Step(timeStep, settings->velocityIterations, settings->positionIterations);
m_world->DrawDebugData();
if (timeStep > 0.0f)
{
++m_stepCount;
}
if (settings->drawStats)
{
int32 bodyCount = m_world->GetBodyCount();
int32 contactCount = m_world->GetContactCount();
int32 jointCount = m_world->GetJointCount();
m_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount);
m_textLine += 15;
int32 proxyCount = m_world->GetProxyCount();
int32 height = m_world->GetTreeHeight();
int32 balance = m_world->GetTreeBalance();
float32 quality = m_world->GetTreeQuality();
m_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality);
m_textLine += 15;
}
// Track maximum profile times
{
const b2Profile& p = m_world->GetProfile();
m_maxProfile.step = b2Max(m_maxProfile.step, p.step);
m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide);
m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve);
m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit);
m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity);
m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition);
m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI);
m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase);
m_totalProfile.step += p.step;
m_totalProfile.collide += p.collide;
m_totalProfile.solve += p.solve;
m_totalProfile.solveInit += p.solveInit;
m_totalProfile.solveVelocity += p.solveVelocity;
m_totalProfile.solvePosition += p.solvePosition;
m_totalProfile.solveTOI += p.solveTOI;
m_totalProfile.broadphase += p.broadphase;
}
if (settings->drawProfile)
{
const b2Profile& p = m_world->GetProfile();
b2Profile aveProfile;
memset(&aveProfile, 0, sizeof(b2Profile));
if (m_stepCount > 0)
{
float32 scale = 1.0f / m_stepCount;
aveProfile.step = scale * m_totalProfile.step;
aveProfile.collide = scale * m_totalProfile.collide;
aveProfile.solve = scale * m_totalProfile.solve;
aveProfile.solveInit = scale * m_totalProfile.solveInit;
aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity;
aveProfile.solvePosition = scale * m_totalProfile.solvePosition;
aveProfile.solveTOI = scale * m_totalProfile.solveTOI;
aveProfile.broadphase = scale * m_totalProfile.broadphase;
}
m_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI);
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase);
m_textLine += 15;
}
if (m_mouseJoint)
{
b2Vec2 p1 = m_mouseJoint->GetAnchorB();
b2Vec2 p2 = m_mouseJoint->GetTarget();
b2Color c;
c.Set(0.0f, 1.0f, 0.0f);
m_debugDraw.DrawPoint(p1, 4.0f, c);
m_debugDraw.DrawPoint(p2, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
m_debugDraw.DrawSegment(p1, p2, c);
}
if (m_bombSpawning)
{
b2Color c;
c.Set(0.0f, 0.0f, 1.0f);
m_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
m_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c);
}
if (settings->drawContactPoints)
{
//const float32 k_impulseScale = 0.1f;
const float32 k_axisScale = 0.3f;
for (int32 i = 0; i < m_pointCount; ++i)
{
ContactPoint* point = m_points + i;
if (point->state == b2_addState)
{
// Add
m_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f));
}
else if (point->state == b2_persistState)
{
// Persist
m_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f));
}
if (settings->drawContactNormals == 1)
{
b2Vec2 p1 = point->position;
b2Vec2 p2 = p1 + k_axisScale * point->normal;
m_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f));
}
else if (settings->drawContactForces == 1)
{
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->normalForce * point->normal;
//DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
if (settings->drawFrictionForces == 1)
{
//b2Vec2 tangent = b2Cross(point->normal, 1.0f);
//b2Vec2 p1 = point->position;
//b2Vec2 p2 = p1 + k_forceScale * point->tangentForce * tangent;
//DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
}
}
}
| 27.070796 | 166 | 0.673995 | blackberry |
c88bc8c976353d1c975bf01b01c4b541ab19a0ff | 1,206 | cpp | C++ | Practice/2017/2017.11.10/Luogu3371-Dij.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2017/2017.11.10/Luogu3371-Dij.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2017/2017.11.10/Luogu3371-Dij.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=10010;
const int maxM=500010;
const int inf=2147483647;
class Queue_Data
{
public:
int u,dist;
};
bool operator < (Queue_Data A,Queue_Data B)
{
return A.dist>B.dist;
}
int n,m,S;
int cnt=0,Head[maxN],Next[maxM],V[maxM],W[maxM];
int Dist[maxN];
bool vis[maxN];
priority_queue<Queue_Data> Q;
int main()
{
mem(Head,-1);
scanf("%d%d%d",&n,&m,&S);
for (int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
cnt++;Next[cnt]=Head[u];Head[u]=cnt;
V[cnt]=v;W[cnt]=w;
}
Queue_Data init;
for (int i=1;i<=n;i++) Dist[i]=inf;
Dist[S]=0;
init.u=S;init.dist=0;
Q.push(init);
do
{
int u=Q.top().u;
Q.pop();
if (vis[u]) continue;
vis[u]=1;
for (int i=Head[u];i!=-1;i=Next[i])
{
int v=V[i];
if ((Dist[u]+W[i]<Dist[v])&&(vis[v]==0))
{
Dist[v]=Dist[u]+W[i];
Q.push((Queue_Data){v,Dist[v]});
}
}
}
while (!Q.empty());
for (int i=1;i<=n;i++) printf("%d ",Dist[i]);
printf("\n");
return 0;
}
| 17.228571 | 49 | 0.563847 | SYCstudio |
c88ccd14b2767edda4ef779172d4e0e724c51fef | 11,998 | cpp | C++ | gtn/functions/compose.cpp | csukuangfj/gtn | 7607bdef9014b55db6e1eaa7953fc23987e6bacb | [
"MIT"
] | 1 | 2021-01-27T16:01:51.000Z | 2021-01-27T16:01:51.000Z | gtn/functions/compose.cpp | KonstantinKlepikov/gtn | 319e939f292121dcfc6bcb001773889b18227034 | [
"MIT"
] | null | null | null | gtn/functions/compose.cpp | KonstantinKlepikov/gtn | 319e939f292121dcfc6bcb001773889b18227034 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <queue>
#include "gtn/functions/compose.h"
namespace gtn {
namespace detail {
namespace {
inline size_t toIndex(int n1, int n2, const Graph& g) {
return n1 + g.numNodes() * n2;
}
/* Find any state in the new composed graph which can reach
* an accepting state. */
auto findReachable(
const Graph& first,
const Graph& second,
std::shared_ptr<ArcMatcher> matcher) {
std::vector<bool> reachable(first.numNodes() * second.numNodes(), false);
std::queue<std::pair<int, int>> toExplore;
for (auto f : first.accept()) {
for (auto s : second.accept()) {
toExplore.emplace(f, s);
reachable[toIndex(f, s, first)] = true;
}
}
while (!toExplore.empty()) {
auto curr = toExplore.front();
toExplore.pop();
bool epsilon_matched = false;
matcher->match(curr.first, curr.second, true);
int i, j;
while (matcher->hasNext()) {
std::tie(i, j) = matcher->next();
epsilon_matched |= (first.olabel(i) == epsilon);
auto un1 = first.srcNode(i);
auto un2 = second.srcNode(j);
auto idx = toIndex(un1, un2, first);
if (!reachable[idx]) {
// If we haven't seen this state before, explore it.
toExplore.emplace(un1, un2);
}
reachable[idx] = true;
}
if (!epsilon_matched) {
for (auto i : first.in(curr.first)) {
if (first.olabel(i) != epsilon) {
if (first.olabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
auto un1 = first.srcNode(i);
auto idx = toIndex(un1, curr.second, first);
if (!reachable[idx]) {
// If we haven't seen this state before, explore it.
toExplore.emplace(un1, curr.second);
}
reachable[idx] = true;
}
}
if (!epsilon_matched) {
for (auto j : second.in(curr.second)) {
if (second.ilabel(j) != epsilon) {
if (second.ilabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
auto un2 = second.srcNode(j);
auto idx = toIndex(curr.first, un2, first);
if (!reachable[idx]) {
// If we haven't seen this state before, explore it.
toExplore.emplace(curr.first, un2);
}
reachable[idx] = true;
}
}
}
return reachable;
}
} // namespace
void UnsortedMatcher::match(int lnode, int rnode, bool matchIn /* = false*/) {
auto& lv = matchIn ? g1_.in(lnode) : g1_.out(lnode);
auto& rv = matchIn ? g2_.in(rnode) : g2_.out(rnode);
lIt_ = lv.begin();
lItEnd_ = lv.end();
rItBegin_ = rIt_ = rv.begin();
rItEnd_ = rv.end();
}
bool UnsortedMatcher::hasNext() {
for (; lIt_ != lItEnd_; ++lIt_) {
for (; rIt_ != rItEnd_; ++rIt_) {
if (g1_.olabel(*lIt_) == g2_.ilabel(*rIt_)) {
return true;
}
}
rIt_ = rItBegin_;
}
return false;
}
std::pair<int, int> UnsortedMatcher::next() {
return std::make_pair(*lIt_, *rIt_++);
}
SinglySortedMatcher::SinglySortedMatcher(
const Graph& g1,
const Graph& g2,
bool searchG1 /* = false */)
: g1_(g1), g2_(g2), searchG1_(searchG1) {}
void SinglySortedMatcher::match(
int lnode,
int rnode,
bool matchIn /* = false */) {
auto& lv = matchIn ? g1_.in(lnode) : g1_.out(lnode);
auto& rv = matchIn ? g2_.in(rnode) : g2_.out(rnode);
searchItBegin_ = searchIt_ = lv.begin();
searchItEnd_ = lv.end();
queryIt_ = rv.begin();
queryItEnd_ = rv.end();
if (!searchG1_) {
searchItBegin_ = queryIt_;
std::swap(queryIt_, searchIt_);
std::swap(queryItEnd_, searchItEnd_);
}
}
bool SinglySortedMatcher::hasNext() {
if (queryIt_ == queryItEnd_) {
return false;
}
if (searchIt_ != searchItEnd_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
auto sl = searchG1_ ? g1_.olabel(*searchIt_) : g2_.ilabel(*searchIt_);
if (ql == sl) {
return true;
}
}
if (searchIt_ != searchItBegin_) {
// Not at the start of the search
++queryIt_;
}
// Update the query pointer and the start of the search range pointer
for (; queryIt_ != queryItEnd_; ++queryIt_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
// Set the comparison function appropriately
auto comparisonFn = [this](int arc, int val) {
return searchG1_ ? g1_.olabel(arc) < val : g2_.ilabel(arc) < val;
};
searchIt_ =
std::lower_bound(searchItBegin_, searchItEnd_, ql, comparisonFn);
if (searchIt_ == searchItEnd_) {
continue;
}
auto sl = searchG1_ ? g1_.olabel(*searchIt_) : g2_.ilabel(*searchIt_);
if (sl == ql) {
return true;
}
}
return false;
}
std::pair<int, int> SinglySortedMatcher::next() {
if (searchG1_) {
return std::make_pair(*searchIt_++, *queryIt_);
} else {
return std::make_pair(*queryIt_, *searchIt_++);
}
}
void DoublySortedMatcher::match(
int lnode,
int rnode,
bool matchIn /* = false */) {
auto& lv = matchIn ? g1_.in(lnode) : g1_.out(lnode);
auto& rv = matchIn ? g2_.in(rnode) : g2_.out(rnode);
searchItBegin_ = searchIt_ = lv.begin();
searchItEnd_ = lv.end();
queryIt_ = rv.begin();
queryItEnd_ = rv.end();
searchG1_ = lv.size() > rv.size();
if (!searchG1_) {
searchItBegin_ = queryIt_;
std::swap(queryIt_, searchIt_);
std::swap(queryItEnd_, searchItEnd_);
}
}
bool DoublySortedMatcher::hasNext() {
if (queryIt_ == queryItEnd_) {
return false;
}
if (searchIt_ != searchItEnd_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
auto sl = searchG1_ ? g1_.olabel(*searchIt_) : g2_.ilabel(*searchIt_);
if (ql == sl) {
return true;
}
}
if (searchIt_ != searchItBegin_) {
// Not at the start of the search
++queryIt_;
}
// Update the query pointer and the start of the search range pointer
for (; queryIt_ != queryItEnd_; ++queryIt_) {
auto ql = searchG1_ ? g2_.ilabel(*queryIt_) : g1_.olabel(*queryIt_);
// Set the comparison function appropriately
auto comparisonFn = [this](int arc, int val) {
return searchG1_ ? g1_.olabel(arc) < val : g2_.ilabel(arc) < val;
};
// Allowed because the query vector is sorted.
searchItBegin_ =
std::lower_bound(searchItBegin_, searchItEnd_, ql, comparisonFn);
if (searchItBegin_ == searchItEnd_) {
return false;
}
auto sl =
searchG1_ ? g1_.olabel(*searchItBegin_) : g2_.ilabel(*searchItBegin_);
if (sl == ql) {
searchIt_ = searchItBegin_;
return true;
}
}
return false;
}
std::pair<int, int> DoublySortedMatcher::next() {
if (searchG1_) {
return std::make_pair(*searchIt_++, *queryIt_);
} else {
return std::make_pair(*queryIt_, *searchIt_++);
}
}
// Composes two graphs and returns a new graph
Graph compose(
const Graph& first,
const Graph& second,
std::shared_ptr<ArcMatcher> matcher) {
// Compute reachable nodes from any accept state in the new graph
auto reachable = findReachable(first, second, matcher);
// Compose the graphs
Graph ngraph(nullptr, {first, second});
std::vector<int> newNodes(first.numNodes() * second.numNodes(), -1);
std::queue<std::pair<int, int>> toExplore;
for (auto s1 : first.start()) {
for (auto s2 : second.start()) {
auto idx = toIndex(s1, s2, first);
if (reachable[idx]) {
newNodes[idx] =
ngraph.addNode(true, first.isAccept(s1) && second.isAccept(s2));
toExplore.emplace(s1, s2);
}
}
}
std::vector<std::pair<int, int>> gradInfo;
while (!toExplore.empty()) {
auto curr = toExplore.front();
toExplore.pop();
auto currNode = newNodes[toIndex(curr.first, curr.second, first)];
int i, j;
matcher->match(curr.first, curr.second);
while (matcher->hasNext()) {
std::tie(i, j) = matcher->next();
auto dn1 = first.dstNode(i);
auto dn2 = second.dstNode(j);
// Ignore if we can't get to an accept state.
auto idx = toIndex(dn1, dn2, first);
if (!reachable[idx]) {
continue;
}
// Build the node
if (newNodes[idx] < 0) {
newNodes[idx] = ngraph.addNode(
first.isStart(dn1) && second.isStart(dn2),
first.isAccept(dn1) && second.isAccept(dn2));
toExplore.emplace(dn1, dn2);
}
auto weight = first.weight(i) + second.weight(j);
auto newarc = ngraph.addArc(
currNode, newNodes[idx], first.ilabel(i), second.olabel(j), weight);
// Arcs remember where they came from for
// easy gradient computation.
gradInfo.emplace_back(i, j);
}
// Check for output epsilons in the first graph
for (auto i : first.out(curr.first)) {
if (first.olabel(i) != epsilon) {
if (first.olabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
// We only advance along the first arc.
auto dn1 = first.dstNode(i);
auto dn2 = curr.second;
auto idx = toIndex(dn1, dn2, first);
if (!reachable[idx]) {
continue;
}
if (newNodes[idx] < 0) {
newNodes[idx] = ngraph.addNode(
first.isStart(dn1) && second.isStart(dn2),
first.isAccept(dn1) && second.isAccept(dn2));
toExplore.emplace(dn1, dn2);
}
auto weight = first.weight(i);
auto newarc = ngraph.addArc(
currNode, newNodes[idx], first.ilabel(i), epsilon, weight);
gradInfo.emplace_back(i, -1);
}
// Check out input epsilons in the second graph
for (auto j : second.out(curr.second)) {
if (second.ilabel(j) != epsilon) {
if (second.ilabelSorted()) {
// epsilon < 0
break;
} else {
continue;
}
}
// We only advance along the second arc.
auto dn1 = curr.first;
auto dn2 = second.dstNode(j);
auto idx = toIndex(dn1, dn2, first);
if (!reachable[idx]) {
continue;
}
if (newNodes[idx] < 0) {
newNodes[idx] = ngraph.addNode(
first.isStart(dn1) && second.isStart(dn2),
first.isAccept(dn1) && second.isAccept(dn2));
toExplore.emplace(dn1, dn2);
}
auto weight = second.weight(j);
auto newarc = ngraph.addArc(
currNode, newNodes[idx], epsilon, second.olabel(j), weight);
gradInfo.emplace_back(-1, j);
}
}
/* Here we assume deltas is the output (e.g. ngraph) and we know where
* each arc came from. This makes it possible to disambiguate two arcs in the
* composed graph with the same label and the same src and destination nodes.
*/
auto gradFunc = [gradInfo = std::move(gradInfo)](
std::vector<Graph>& inputs, Graph deltas) {
// In this case the arc's parents are always from the
// first and second input graphs respectively.
bool calcGrad1 = inputs[0].calcGrad();
bool calcGrad2 = inputs[1].calcGrad();
auto grad1 = calcGrad1 ? std::vector<float>(inputs[0].numArcs(), 0.0)
: std::vector<float>{};
auto grad2 = calcGrad2 ? std::vector<float>(inputs[1].numArcs(), 0.0)
: std::vector<float>{};
for (int i = 0; i < gradInfo.size(); i++) {
auto arcGrad = deltas.weight(i);
auto& arcs = gradInfo[i];
if (calcGrad1 && arcs.first >= 0) {
grad1[arcs.first] += arcGrad;
}
if (calcGrad2 && arcs.second >= 0) {
grad2[arcs.second] += arcGrad;
}
}
inputs[0].addGrad(std::move(grad1));
inputs[1].addGrad(std::move(grad2));
};
ngraph.setGradFunc(std::move(gradFunc));
return ngraph;
}
} // namespace detail
} // namespace gtn
| 29.406863 | 79 | 0.590182 | csukuangfj |
c88ec2f7d1e285bdbaea93d58133cef7a2e597b0 | 358 | cpp | C++ | mc/tmc.cpp | curv3d/tmc | 2afbceeb8f232b2a4771da7fc1d46489e2e7252a | [
"MIT"
] | 14 | 2018-01-23T08:01:45.000Z | 2022-02-13T20:23:39.000Z | mc/tmc.cpp | curv3d/tmc | 2afbceeb8f232b2a4771da7fc1d46489e2e7252a | [
"MIT"
] | 1 | 2020-08-02T07:56:00.000Z | 2020-08-02T07:56:00.000Z | mc/tmc.cpp | curv3d/tmc | 2afbceeb8f232b2a4771da7fc1d46489e2e7252a | [
"MIT"
] | 3 | 2016-06-08T20:34:28.000Z | 2021-11-15T20:47:35.000Z | //
//
// Libs
#include <iostream>
#include <string>
// Project files
#include "MarchingCubes.h"
int main(int argc, char* argv[])
{
// Marcing cubes
tmc::MarchingCubes mc;
// parameters
std::string i_file = "";
std::string objF = "";
std::string offF = "";
const double i0 = 801.3;
mc(i0,i_file,true,true,objF,true,offF);
return 0;
}
| 14.916667 | 43 | 0.620112 | curv3d |
c88efbda1587fef2bb7135dbd8b03ffd3429f339 | 642 | cpp | C++ | src/v8jsiapp/logger.cpp | mganandraj/v8-jsi | aff826a5567a4fd0fd66b3f3af1187400a666fa9 | [
"MIT"
] | null | null | null | src/v8jsiapp/logger.cpp | mganandraj/v8-jsi | aff826a5567a4fd0fd66b3f3af1187400a666fa9 | [
"MIT"
] | null | null | null | src/v8jsiapp/logger.cpp | mganandraj/v8-jsi | aff826a5567a4fd0fd66b3f3af1187400a666fa9 | [
"MIT"
] | null | null | null | #include "logger.h"
std::mutex Logger::log_m;
void Logger::log(const std::string& s) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << s << std::endl;
}
void Logger::log(const char* ch) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << ch << std::endl;
}
void Logger::log(const char* prefix, const std::string& s) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << std::string(prefix) << " >>>>" << s << std::endl;
}
void Logger::log(const char* prefix, const char* ch) {
std::unique_lock<std::mutex> lock(log_m);
std::cout << std::string(prefix) << " >>>>" << ch << std::endl;
} | 27.913043 | 66 | 0.596573 | mganandraj |
c88f5c3a40eb2640b4807e4aff3aa76851d586e5 | 26,474 | cpp | C++ | tests/TestStrUtils.cpp | pauldardeau/chaudiere | b9e4878da8b3ffd18cb30ea29fa91d46d02ae26c | [
"BSD-3-Clause"
] | null | null | null | tests/TestStrUtils.cpp | pauldardeau/chaudiere | b9e4878da8b3ffd18cb30ea29fa91d46d02ae26c | [
"BSD-3-Clause"
] | 13 | 2017-03-19T03:38:44.000Z | 2017-09-09T20:55:39.000Z | tests/TestStrUtils.cpp | pauldardeau/chaudiere | b9e4878da8b3ffd18cb30ea29fa91d46d02ae26c | [
"BSD-3-Clause"
] | null | null | null | // Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include <string.h>
#include <string>
#include "TestStrUtils.h"
#include "StrUtils.h"
static const std::string emptyString = "";
using namespace chaudiere;
using namespace poivre;
//******************************************************************************
TestStrUtils::TestStrUtils() :
TestSuite("TestStrUtils") {
}
//******************************************************************************
void TestStrUtils::runTests() {
// parsing
testParseInt();
testParseLong();
testParseFloat();
testParseDouble();
// toString
testToStringWithInt();
testToStringWithLong();
testToStringWithULong();
// strip
testStrip();
testStripWithChar();
testStartsWith();
testEndsWith();
testContainsString();
// upper/lower case
testToUpperCase();
testToLowerCase();
// search & replace
testReplaceAll();
// strip
testStripInPlace();
testStripTrailing();
testStripLeading();
testTrimLeadingSpaces();
testTrim();
// padding
testPadRight();
testPadLeft();
// makeStringOfChar
testMakeStringOfChar();
// split
testSplit();
}
//******************************************************************************
class ParseRunner : public Runnable {
public:
explicit ParseRunner(const std::string& arg) :
m_arg(arg) {
}
ParseRunner(const ParseRunner& copy) :
m_arg(copy.m_arg) {
}
~ParseRunner() {}
ParseRunner& operator=(const ParseRunner& copy) {
if (this == ©) {
return *this;
}
m_arg = copy.m_arg;
return *this;
}
virtual void run() = 0;
protected:
std::string m_arg;
};
class ParseIntRunner : public ParseRunner {
public:
ParseIntRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseInt(m_arg);
}
};
class ParseLongRunner : public ParseRunner {
public:
ParseLongRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseLong(m_arg);
}
};
class ParseFloatRunner : public ParseRunner {
public:
ParseFloatRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseFloat(m_arg);
}
};
class ParseDoubleRunner : public ParseRunner {
public:
ParseDoubleRunner(const std::string& arg) :
ParseRunner(arg) {
}
virtual void run() {
StrUtils::parseDouble(m_arg);
}
};
//*****************************************************************************
//*****************************************************************************
void TestStrUtils::testParseInt() {
TEST_CASE("parseInt");
require(3 == StrUtils::parseInt("3"), "1 digit positive integer");
require(-5 == StrUtils::parseInt("-5"), "1 digit negative integer");
require(0 == StrUtils::parseInt("0"), "zero");
require(35 == StrUtils::parseInt("35"), "2 digit positive integer");
require(121 == StrUtils::parseInt("121"), "3 digit positive integer");
require(4096 == StrUtils::parseInt("4096"), "4 digit positive integer");
require(65535 == StrUtils::parseInt("65535"), "5 digit positive integer");
// try largest (absolute value) signed value for 32 bits
require(2147483647 == StrUtils::parseInt("2147483647"),
"large positive int");
require(-2147483648UL == StrUtils::parseInt("-2147483648"),
"negative int with large absolute value");
requireException("NumberFormatException", new ParseIntRunner(""),
"empty string");
requireException("NumberFormatException", new ParseIntRunner("x"), "letter");
requireException("NumberFormatException", new ParseIntRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseIntRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testParseLong() {
TEST_CASE("parseLong");
require(3L == StrUtils::parseLong("3"), "1 digit positive long");
require(-5L == StrUtils::parseLong("-5"), "1 digit negative long");
require(0L == StrUtils::parseLong("0"), "zero");
require(35L == StrUtils::parseLong("35"), "2 digit positive long");
require(121L == StrUtils::parseLong("121"), "3 digit positive long");
require(4096L == StrUtils::parseLong("4096"), "4 digit positive long");
require(65535L == StrUtils::parseLong("65535"), "5 digit positive long");
// try largest (absolute value) signed value for 32 bits
require(2147483647L == StrUtils::parseLong("2147483647"),
"large positive long");
require(-2147483648UL == StrUtils::parseLong("-2147483648"),
"negative long with large absolute value");
requireException("NumberFormatException", new ParseLongRunner(""),
"empty string");
requireException("NumberFormatException", new ParseLongRunner("x"), "letter");
requireException("NumberFormatException", new ParseLongRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseLongRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testParseFloat() {
TEST_CASE("parseFloat");
require(3.0f == StrUtils::parseFloat("3"), "1 digit positive integral");
require(-5.0f == StrUtils::parseFloat("-5"), "1 digit negative integral");
require(0.0f == StrUtils::parseFloat("0"), "zero");
require(35.0f == StrUtils::parseFloat("35"), "2 digit positive integral");
require(121.0f == StrUtils::parseFloat("121"), "3 digit positive integral");
require(4096.0f == StrUtils::parseFloat("4096"), "4 digit positive integral");
require(65535.0f == StrUtils::parseFloat("65535"),
"5 digit positive integral");
require(3.1415f == StrUtils::parseFloat("3.1415"), "positive float value");
require(-1492.524f == StrUtils::parseFloat("-1492.524"),
"negative float value");
requireException("NumberFormatException", new ParseFloatRunner(""),
"empty string");
requireException("NumberFormatException", new ParseFloatRunner("x"),
"letter");
requireException("NumberFormatException", new ParseFloatRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseFloatRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testParseDouble() {
TEST_CASE("parseDouble");
require(3.0 == StrUtils::parseDouble("3"), "1 digit positive integral");
require(-5.0 == StrUtils::parseDouble("-5"), "1 digit negative integral");
require(0.0 == StrUtils::parseDouble("0"), "zero");
require(35.0 == StrUtils::parseDouble("35"), "2 digit positive integral");
require(121.0 == StrUtils::parseDouble("121"), "3 digit positive integral");
require(4096.0 == StrUtils::parseDouble("4096"), "4 digit positive integral");
require(65535.0 == StrUtils::parseDouble("65535"),
"5 digit positive integral");
require(3.1415 == StrUtils::parseDouble("3.1415"), "positive double value");
require(-1492.524 == StrUtils::parseDouble("-1492.524"),
"negative double value");
requireException("NumberFormatException", new ParseDoubleRunner(""),
"empty string");
requireException("NumberFormatException", new ParseDoubleRunner("x"),
"letter");
requireException("NumberFormatException", new ParseDoubleRunner("y123"),
"leading char");
requireException("NumberFormatException", new ParseDoubleRunner("456t"),
"trailing char");
}
//******************************************************************************
void TestStrUtils::testToStringWithInt() {
TEST_CASE("toStringWithInt");
requireStringEquals(StrUtils::toString(2112), "2112", "positive value");
requireStringEquals(StrUtils::toString(-57), "-57", "negative value");
requireStringEquals(StrUtils::toString(0), "0", "zero");
}
//******************************************************************************
void TestStrUtils::testToStringWithLong() {
TEST_CASE("toStringWithLong");
requireStringEquals(StrUtils::toString(2112L), "2112", "positive value");
requireStringEquals(StrUtils::toString(-57L), "-57", "negative value");
requireStringEquals(StrUtils::toString(0L), "0", "zero");
}
//******************************************************************************
void TestStrUtils::testToStringWithULong() {
TEST_CASE("toStringWithULong");
requireStringEquals(StrUtils::toString(2112UL), "2112", "non-zero value");
requireStringEquals(StrUtils::toString(0UL), "0", "zero");
}
//******************************************************************************
void TestStrUtils::testStrip() {
TEST_CASE("strip");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleLeadingTrailingSpace = " now is the time ";
std::string leadingAndTrailing = " now is the time ";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::strip(withSingleTrailingSpace),
"single trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingTrailingSpace),
"single leading and trailing space");
requireStringEquals(target, StrUtils::strip(leadingAndTrailing),
"trimmed string has leading strip chars");
requireStringEquals(target, StrUtils::strip(alreadyTrimmed),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testStripWithChar() {
TEST_CASE("stripWithChar");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleLeadingTrailingSpace = " now is the time ";
std::string withSingleLeadingX = "xnow is the time";
std::string withSingleTrailingX = "now is the timex";
std::string withLeadingTrailingPunctuation = ",now is the time,";
std::string withTrailingPunctuation = "now is the time,";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::strip(withSingleTrailingSpace, ' '),
"single trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingTrailingSpace,
' '),
"single leading and trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingX, 'x'),
"leading char");
requireStringEquals(target, StrUtils::strip(withSingleTrailingX, 'x'),
"trailing char");
requireStringEquals(target, StrUtils::strip(withTrailingPunctuation, ','),
"trailing punctuation");
requireStringEquals(target, StrUtils::strip(withLeadingTrailingPunctuation,
','),
"leading and trailing punctuation");
requireStringEquals(target, StrUtils::strip(leadingAndTrailing, '.'),
"leading and trailing strip chars");
requireStringEquals(target, StrUtils::strip(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testStartsWith() {
TEST_CASE("startsWith");
const std::string haystack = "abcdefg";
const std::string needle = "abc";
const std::string razor = "xyz";
const std::string upperNeedle = "ABC";
require(StrUtils::startsWith(haystack, needle),
"haystack contains needle at beginning");
requireFalse(StrUtils::startsWith(haystack, razor),
"haystack doesn't contain needle anywhere");
requireFalse(StrUtils::startsWith(haystack, emptyString),
"haystack doesn't start with empty string");
requireFalse(StrUtils::startsWith(emptyString, needle),
"empty haystack doesn't start with needle");
requireFalse(StrUtils::startsWith(haystack, upperNeedle),
"haystack doesn't start with upper needle");
}
//******************************************************************************
void TestStrUtils::testEndsWith() {
TEST_CASE("endsWith");
const std::string haystack = "abcdefg";
const std::string needle = "efg";
const std::string razor = "xyz";
const std::string upperNeedle = "EFG";
require(StrUtils::endsWith(haystack, needle),
"haystack contains needle at end");
requireFalse(StrUtils::endsWith(haystack, razor),
"haystack doesn't contain needle anywhere");
requireFalse(StrUtils::endsWith(haystack, emptyString),
"haystack doesn't end with empty string");
requireFalse(StrUtils::endsWith(emptyString, needle),
"empty haystack doesn't end with needle");
requireFalse(StrUtils::endsWith(haystack, upperNeedle),
"haystack doesn't end with upper needle");
}
//******************************************************************************
void TestStrUtils::testContainsString() {
TEST_CASE("containsString");
const std::string haystack =
"She said that it was he, and I said that it was she";
const std::string She = "She";
const std::string she = "she";
const std::string he = "he";
const std::string notThere = "continent";
require(StrUtils::containsString(haystack, She), "haystack contains needle");
require(StrUtils::containsString(haystack, she), "haystack contains needle");
require(StrUtils::containsString(haystack, he), "haystack contains needle");
requireFalse(StrUtils::containsString(haystack, notThere),
"haystack does not contain needle");
}
//******************************************************************************
void TestStrUtils::testToUpperCase() {
TEST_CASE("toUpperCase");
const std::string target = "NOW IS THE TIME";
std::string source = "now is the time";
StrUtils::toUpperCase(source);
requireStringEquals(target, source, "all lower should convert to all upper");
source = "Now Is The Time";
StrUtils::toUpperCase(source);
requireStringEquals(target, source, "mixed case should convert to all upper");
source = target;
StrUtils::toUpperCase(source);
requireStringEquals(target, source,
"no alteration of already uppercase string");
const std::string targetNonLetters = "1234;.,!";
source = targetNonLetters;
StrUtils::toUpperCase(source);
requireStringEquals(targetNonLetters, source,
"no alteration of string not containing letters");
}
//******************************************************************************
void TestStrUtils::testToLowerCase() {
TEST_CASE("toLowerCase");
const std::string target = "now is the time";
std::string source = "NOW IS THE TIME";
StrUtils::toLowerCase(source);
requireStringEquals(target, source, "all upper should convert to all lower");
source = "Now Is The Time";
StrUtils::toLowerCase(source);
requireStringEquals(target, source, "mixed case should convert to all lower");
source = target;
StrUtils::toLowerCase(source);
requireStringEquals(target, source,
"no alteration of already lowercase string");
const std::string targetNonLetters = "1234;.,!";
source = targetNonLetters;
StrUtils::toLowerCase(source);
requireStringEquals(targetNonLetters, source,
"no alteration of string not containing letters");
}
//******************************************************************************
void TestStrUtils::testReplaceAll() {
TEST_CASE("replaceAll");
const std::string source =
"She said that it was he, and I said that it was she";
const std::string target_she_She =
"She said that it was he, and I said that it was She";
const std::string target_She_she =
"she said that it was he, and I said that it was she";
const std::string target_She_He =
"He said that it was he, and I said that it was she";
const std::string target_he_she =
"Sshe said that it was she, and I said that it was sshe";
std::string target;
const std::string She = "She";
const std::string she = "she";
const std::string He = "He";
const std::string he = "he";
const std::string notThere = "or";
const std::string xyz = "xyz";
target = source;
requireStringEquals(target_she_She, StrUtils::replaceAll(target, she, She),
"replace 'she' with 'She'");
target = source;
requireStringEquals(target_She_she, StrUtils::replaceAll(target, She, she),
"replace 'She' with 'she'");
target = source;
requireStringEquals(target_She_He, StrUtils::replaceAll(target, She, He),
"replace 'She' with 'He'");
target = source;
requireStringEquals(target_he_she, StrUtils::replaceAll(target, he, she),
"replace 'he' with 'she'");
target = source;
requireStringEquals(target, StrUtils::replaceAll(target, notThere, xyz),
"no alteration of string with non-existent needle");
}
//******************************************************************************
void TestStrUtils::testStripInPlace() {
TEST_CASE("stripInPlace");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleLeadingTrailingSpace = " now is the time ";
std::string withSingleLeadingX = "xnow is the time";
std::string withSingleTrailingX = "now is the timex";
std::string withLeadingTrailingPunctuation = ",now is the time,";
std::string withTrailingPunctuation = "now is the time,";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::strip(withSingleTrailingSpace, ' '),
"single trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingTrailingSpace,
' '),
"single leading and trailing space");
requireStringEquals(target, StrUtils::strip(withSingleLeadingX, 'x'),
"leading char");
requireStringEquals(target, StrUtils::strip(withSingleTrailingX, 'x'),
"trailing char");
requireStringEquals(target, StrUtils::strip(withTrailingPunctuation, ','),
"trailing punctuation");
requireStringEquals(target, StrUtils::strip(withLeadingTrailingPunctuation,
','),
"leading and trailing punctuation");
requireStringEquals(target, StrUtils::strip(leadingAndTrailing, '.'),
"leading and trailing strip chars");
requireStringEquals(target, StrUtils::strip(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testStripTrailing() {
TEST_CASE("stripTrailing");
const std::string target = "now is the time";
std::string withSingleTrailingSpace = "now is the time ";
std::string withSingleTrailingX = "now is the timex";
std::string withTrailingPunctuation = "now is the time,";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
std::string onlyTrimChars = "xxxxxxxxxx";
const std::string empty = "";
requireStringEquals(target, StrUtils::stripTrailing(withSingleTrailingSpace,
' '),
"single trailing space");
requireStringEquals(target, StrUtils::stripTrailing(withSingleTrailingX,
'x'),
"trailing char");
requireStringEquals(target, StrUtils::stripTrailing(withTrailingPunctuation,
','),
"trailing punctuation");
require(target != StrUtils::stripTrailing(leadingAndTrailing, '.'),
"trimmed string has leading strip chars");
requireStringEquals(target, StrUtils::stripTrailing(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
requireStringEquals(empty, StrUtils::stripTrailing(onlyTrimChars, 'x'),
"string containing only char to strip");
}
//******************************************************************************
void TestStrUtils::testStripLeading() {
TEST_CASE("stripLeading");
const std::string target = "now is the time";
std::string withSingleLeadingSpace = " now is the time";
std::string withSingleLeadingX = "xnow is the time";
std::string withLeadingPunctuation = ",now is the time";
std::string leadingAndTrailing = "...now is the time...";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::stripLeading(withSingleLeadingSpace, ' '),
"single leading space");
requireStringEquals(target, StrUtils::stripLeading(withSingleLeadingX, 'x'),
"leading char");
requireStringEquals(target, StrUtils::stripLeading(withLeadingPunctuation, ','),
"leading punctuation");
require(target != StrUtils::stripLeading(leadingAndTrailing, '.'),
"trimmed string has trailing strip chars");
requireStringEquals(target, StrUtils::stripLeading(alreadyTrimmed, ' '),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testTrimLeadingSpaces() {
TEST_CASE("trimLeadingSpaces");
const std::string target = "now is the time";
std::string withSingleLeadingSpace = " now is the time";
std::string withLeadingSpaces = " now is the time";
std::string leadingAndTrailing = " now is the time ";
std::string alreadyTrimmed = "now is the time";
requireStringEquals(target, StrUtils::trimLeadingSpaces(withSingleLeadingSpace),
"single leading space");
requireStringEquals(target, StrUtils::trimLeadingSpaces(withLeadingSpaces),
"leading spaces");
require(target != StrUtils::trimLeadingSpaces(leadingAndTrailing),
"trimmed string has trailing spaces");
requireStringEquals(target, StrUtils::trimLeadingSpaces(alreadyTrimmed),
"no alteration of already trimmed string");
}
//******************************************************************************
void TestStrUtils::testTrim() {
TEST_CASE("trim");
// trim is just alias for strip. strip tested elsewhere
}
//******************************************************************************
void TestStrUtils::testPadRight() {
TEST_CASE("padRight");
std::string startedEmpty;
const std::string tenChars = "xxxxxxxxxx";
StrUtils::padRight(startedEmpty, 'x', 10);
requireStringEquals(tenChars, startedEmpty, "empty");
std::string noPaddingNeeded = "xxxxxxxxxx";
StrUtils::padRight(noPaddingNeeded, 'x', 10);
requireStringEquals(tenChars, noPaddingNeeded, "no padding needed");
std::string onePadCharNeeded = "...";
const std::string fourChars = "....";
StrUtils::padRight(onePadCharNeeded, '.', 4);
requireStringEquals(fourChars, onePadCharNeeded, "one pad char needed");
std::string threePadCharsNeeded = "888 ";
const std::string spacePadded = "888 ";
StrUtils::padRight(threePadCharsNeeded, ' ', 10);
requireStringEquals(spacePadded, threePadCharsNeeded,
"three pad chars needed");
}
//******************************************************************************
void TestStrUtils::testPadLeft() {
TEST_CASE("padLeft");
std::string startedEmpty;
const std::string tenChars = "xxxxxxxxxx";
StrUtils::padLeft(startedEmpty, 'x', 10);
requireStringEquals(tenChars, startedEmpty, "empty");
std::string noPaddingNeeded = "xxxxxxxxxx";
StrUtils::padLeft(noPaddingNeeded, 'x', 10);
requireStringEquals(tenChars, noPaddingNeeded, "no padding needed");
std::string onePadCharNeeded = "...";
const std::string fourChars = "....";
StrUtils::padLeft(onePadCharNeeded, '.', 4);
requireStringEquals(fourChars, onePadCharNeeded, "one pad char needed");
std::string threePadCharsNeeded = "888 ";
const std::string spacePadded = " 888 ";
StrUtils::padLeft(threePadCharsNeeded, ' ', 10);
requireStringEquals(spacePadded, threePadCharsNeeded,
"three pad chars needed");
}
//******************************************************************************
void TestStrUtils::testMakeStringOfChar() {
TEST_CASE("makeStringOfChar");
requireStringEquals(std::string("xxx"),
StrUtils::makeStringOfChar('x', 3),
"simple construction");
requireStringEquals(std::string(""),
StrUtils::makeStringOfChar('z', 0),
"zero-length");
}
//******************************************************************************
void TestStrUtils::testSplit() {
TEST_CASE("split");
std::vector<std::string> r;
r = StrUtils::split("comma,separated,values", ",");
require(r.size() == 3, "comma separated values");
r = StrUtils::split("/usr/local/bin", "/");
require(r.size() == 3, "leading delimiter");
r = StrUtils::split("/usr/local/bin", ":");
require(r.size() == 1, "missing delimiter");
r = StrUtils::split("abc:def:ghi:", ":");
require(r.size() == 3, "trailing delimiter");
}
//******************************************************************************
| 37.498584 | 83 | 0.590995 | pauldardeau |
c88f7761978e809e98300066e9405fafcf3d606d | 5,592 | hpp | C++ | dsa/XVDPU-TRD/vck190_platform/overlays/Vitis_Libraries/vision/L1/include/imgproc/xf_aec.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 1 | 2022-02-17T22:13:23.000Z | 2022-02-17T22:13:23.000Z | dsa/XVDPU-TRD/vck190_platform/overlays/Vitis_Libraries/vision/L1/include/imgproc/xf_aec.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | dsa/XVDPU-TRD/vck190_platform/overlays/Vitis_Libraries/vision/L1/include/imgproc/xf_aec.hpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _XF_AEC_HPP_
#define _XF_AEC_HPP_
#include "common/xf_common.hpp"
#include "hls_math.h"
#include "hls_stream.h"
#include "xf_bgr2hsv.hpp"
#include "xf_channel_combine.hpp"
#include "xf_channel_extract.hpp"
#include "xf_cvt_color.hpp"
#include "xf_cvt_color_1.hpp"
#include "xf_duplicateimage.hpp"
#include "xf_hist_equalize.hpp"
#include "xf_histogram.hpp"
template <typename T>
T xf_satcast_aec(int in_val){};
template <>
inline ap_uint<8> xf_satcast_aec<ap_uint<8> >(int v) {
v = (v > 255 ? 255 : v);
v = (v < 0 ? 0 : v);
return v;
};
template <>
inline ap_uint<10> xf_satcast_aec<ap_uint<10> >(int v) {
v = (v > 1023 ? 1023 : v);
v = (v < 0 ? 0 : v);
return v;
};
template <>
inline ap_uint<12> xf_satcast_aec<ap_uint<12> >(int v) {
v = (v > 4095 ? 4095 : v);
v = (v < 0 ? 0 : v);
return v;
};
template <>
inline ap_uint<16> xf_satcast_aec<ap_uint<16> >(int v) {
v = (v > 65535 ? 65535 : v);
v = (v < 0 ? 0 : v);
return v;
};
namespace xf {
namespace cv {
template <int SRC_T, int DST_T, int SIN_CHANNEL_TYPE, int ROWS, int COLS, int NPC = 1>
void autoexposurecorrection_mono(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& src,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& dst,
uint32_t hist_array1[1][256],
uint32_t hist_array2[1][256]) {
#pragma HLS INLINE OFF
int rows = src.rows;
int cols = src.cols;
uint16_t cols_shifted = cols >> (XF_BITSHIFT(NPC));
uint16_t rows_shifted = rows;
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage1(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage2(rows, cols);
xf::cv::duplicateMat(src, vimage1, vimage2);
xFHistogramKernel<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC,
XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC), ((COLS >> (XF_BITSHIFT(NPC))) >> 1),
XF_CHANNELS(SIN_CHANNEL_TYPE, NPC)>(vimage1, hist_array1, rows_shifted, cols_shifted);
xFEqualize<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC, XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC),
(COLS >> XF_BITSHIFT(NPC))>(vimage2, hist_array2, dst, rows_shifted, cols_shifted);
}
template <int SRC_T, int DST_T, int SIN_CHANNEL_TYPE, int ROWS, int COLS, int NPC = 1>
void autoexposurecorrection(xf::cv::Mat<SRC_T, ROWS, COLS, NPC>& src,
xf::cv::Mat<DST_T, ROWS, COLS, NPC>& dst,
uint32_t hist_array1[1][256],
uint32_t hist_array2[1][256]) {
#pragma HLS INLINE OFF
int rows = src.rows;
int cols = src.cols;
uint16_t cols_shifted = cols >> (XF_BITSHIFT(NPC));
uint16_t rows_shifted = rows;
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> bgr2hsv(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> hsvimg1(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> hsvimg2(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> hsvimg3(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> himage(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> simage(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage1(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage2(rows, cols);
xf::cv::Mat<SIN_CHANNEL_TYPE, ROWS, COLS, NPC> vimage_eq(rows, cols);
xf::cv::Mat<SRC_T, ROWS, COLS, NPC> imgHelper6(rows, cols);
assert(((rows <= ROWS) && (cols <= COLS)) && "ROWS and COLS should be greater than input image");
// clang-format off
#pragma HLS DATAFLOW
// clang-format on
// Convert RGBA to HSV:
xf::cv::bgr2hsv<SRC_T, ROWS, COLS, NPC>(src, bgr2hsv);
xf::cv::duplicateimages<SRC_T, ROWS, COLS, NPC>(bgr2hsv, hsvimg1, hsvimg2, hsvimg3);
xf::cv::extractChannel<SRC_T, SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(hsvimg1, himage, 0);
xf::cv::extractChannel<SRC_T, SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(hsvimg2, simage, 1);
xf::cv::extractChannel<SRC_T, SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(hsvimg3, vimage, 2);
xf::cv::duplicateMat(vimage, vimage1, vimage2);
// xf::cv::equalizeHist<SIN_CHANNEL_TYPE, ROWS, COLS, NPC>(vimage1, vimage2,
// vimage_eq);
xFHistogramKernel<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC,
XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC), ((COLS >> (XF_BITSHIFT(NPC))) >> 1),
XF_CHANNELS(SIN_CHANNEL_TYPE, NPC)>(vimage1, hist_array1, rows_shifted, cols_shifted);
xFEqualize<SIN_CHANNEL_TYPE, ROWS, COLS, XF_DEPTH(SIN_CHANNEL_TYPE, NPC), NPC, XF_WORDWIDTH(SIN_CHANNEL_TYPE, NPC),
(COLS >> XF_BITSHIFT(NPC))>(vimage2, hist_array2, vimage_eq, rows_shifted, cols_shifted);
xf::cv::merge<SIN_CHANNEL_TYPE, SRC_T, ROWS, COLS, NPC>(vimage_eq, simage, himage, imgHelper6);
xf::cv::hsv2bgr<SRC_T, SRC_T, ROWS, COLS, NPC>(imgHelper6, dst);
}
}
}
#endif
| 36.789474 | 119 | 0.651466 | hito0512 |
c88f97f6d56c8a6001659a8efc886de7c32a0fe9 | 9,387 | hh | C++ | TrackerConditions/inc/StrawResponse.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 1 | 2021-06-23T22:09:28.000Z | 2021-06-23T22:09:28.000Z | TrackerConditions/inc/StrawResponse.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | null | null | null | TrackerConditions/inc/StrawResponse.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | null | null | null | #ifndef TrackerConditions_StrawResponse_hh
#define TrackerConditions_StrawResponse_hh
//
// StrawResponse collects the net response features of straws
// used in reconstruction
//
#include <iostream>
#include <vector>
#include <array>
#include "TrackerGeom/inc/Straw.hh"
#include "DataProducts/inc/TrkTypes.hh"
#include "DataProducts/inc/StrawId.hh"
#include "TrackerConditions/inc/StrawDrift.hh"
#include "TrackerConditions/inc/StrawElectronics.hh"
#include "TrackerConditions/inc/StrawPhysics.hh"
#include "Mu2eInterfaces/inc/ProditionsEntity.hh"
namespace mu2e {
class Straw;
class StrawDrift;
class StrawId;
class StrawResponse : virtual public ProditionsEntity {
public:
typedef std::shared_ptr<StrawResponse> ptr_t;
typedef std::shared_ptr<const StrawResponse> cptr_t;
constexpr static const char* cxname = {"StrawResponse"};
explicit StrawResponse( StrawDrift::cptr_t strawDrift,
StrawElectronics::cptr_t strawElectronics,
StrawPhysics::cptr_t strawPhysics,
int eBins, double eBinWidth,
std::vector<double> edep, std::vector<double> halfvp,
double central, std::vector<double> centres,
std::vector<double> resslope, int totTBins, double totTBinWidth,
int totEBins, double totEBinWidth, std::vector<double> totdtime,
bool usederr, std::vector<double> derr,
bool usepderr, std::vector<double> parDriftDocas,
std::vector<double> parDriftOffsets, std::vector<double> parDriftRes,
double wbuf, double slfac, double errfac, bool usenonlindrift,
double lindriftvel, double rres_min, double rres_max,
double rres_rad, double mint0doca, double t0shift,
std::array<double, StrawId::_nustraws> pmpEnergyScale,
double electronicsTimeDelay, double gasGain,
std::array<double,StrawElectronics::npaths> analognoise,
std::array<double,StrawElectronics::npaths> dVdI,
double vsat, double ADCped, double pmpEnergyScaleAvg) :
ProditionsEntity(cxname),
_strawDrift(strawDrift),
_strawElectronics(strawElectronics),
_strawPhysics(strawPhysics),
_eBins(eBins), _eBinWidth(eBinWidth),
_edep(edep), _halfvp(halfvp), _central(central), _centres(centres),
_resslope(resslope), _totTBins(totTBins), _totTBinWidth(totTBinWidth),
_totEBins(totEBins), _totEBinWidth(totEBinWidth),
_totdtime(totdtime), _usederr(usederr),
_derr(derr), _usepderr(usepderr), _parDriftDocas(parDriftDocas),
_parDriftOffsets(parDriftOffsets), _parDriftRes(parDriftRes),
_wbuf(wbuf), _slfac(slfac), _errfac(errfac),
_usenonlindrift(usenonlindrift), _lindriftvel(lindriftvel),
_rres_min(rres_min), _rres_max(rres_max), _rres_rad(rres_rad),
_mint0doca(mint0doca), _t0shift(t0shift),
_pmpEnergyScale(pmpEnergyScale),
_electronicsTimeDelay(electronicsTimeDelay),
_gasGain(gasGain), _analognoise(analognoise),
_dVdI(dVdI), _vsat(vsat), _ADCped(ADCped),
_pmpEnergyScaleAvg(pmpEnergyScaleAvg) {}
virtual ~StrawResponse() {}
bool wireDistance(Straw const& straw, double edep, double dt,
double& wdist, double& wderr, double& halfpv) const;
bool useDriftError() const { return _usederr; }
bool useParameterizedDriftError() const { return _usepderr; }
bool useNonLinearDrift() const { return _usenonlindrift; }
double Mint0doca() const { return _mint0doca;}
double strawGain() const { return _strawPhysics->strawGain();}
double halfPropV(StrawId strawId, double kedep) const;
// this is used to update values from the database
void setOffsets( std::array<double, StrawId::_nupanels> timeOffsetPanel,
std::array<double, StrawId::_nustraws> timeOffsetStrawHV,
std::array<double, StrawId::_nustraws> timeOffsetStrawCal ) {
_timeOffsetPanel = timeOffsetPanel;
_timeOffsetStrawHV = timeOffsetStrawHV;
_timeOffsetStrawCal = timeOffsetStrawCal;
}
double driftDistanceToTime(StrawId strawId, double ddist, double phi) const;
double driftTimeToDistance(StrawId strawId, double dtime, double phi) const;
double driftInstantSpeed(StrawId strawId, double ddist, double phi) const;
double driftConstantSpeed() const {return _lindriftvel;} // constant value used for annealing errors, should be close to average velocity
double driftTimeMaxError() const {return _rres_max/_lindriftvel;} // constant value used for initialization
double driftDistanceError(StrawId strawId, double ddist, double phi, double DOCA) const;
double driftDistanceOffset(StrawId strawId, double ddist, double phi, double DOCA) const;
double driftTimeError(StrawId strawId, double ddist, double phi, double DOCA) const;
double driftTimeOffset(StrawId strawId, double ddist, double phi, double DOCA) const;
double peakMinusPedestalEnergyScale() const { return _pmpEnergyScaleAvg; }
double peakMinusPedestalEnergyScale(StrawId sid) const { return _pmpEnergyScale[sid.uniqueStraw()]; }
double analogNoise(StrawElectronics::Path ipath) const { return _analognoise[ipath]; } // incoherent noise
double fallTime(StrawElectronics::Path ipath) const { return 22.;} //FIXME
double currentToVoltage(StrawElectronics::Path ipath) const { return _dVdI[ipath]; }
double saturatedResponse(double vlin) const;
double ADCPedestal() const { return _ADCped; };
double t0shift() const { return _t0shift; }
// converts times from TDC times to time relative to Event Window
// removes channel to channel delays and overall electronics time delay
void calibrateTimes(TrkTypes::TDCValues const& tdc, TrkTypes::TDCTimes ×, const StrawId &id) const;
// approximate drift distatnce from ToT value
double driftTime(Straw const& straw, double tot, double edep) const;
double pathLength(Straw const& straw, double tot) const;
// double pathLength(StrawHit const& strawhit, double theta) const;
void print(std::ostream& os) const;
void printVector(std::ostream& os, std::string const& name,
std::vector<double> const& a) const;
template<typename T, size_t SIZE>
void printArray(std::ostream& os, std::string const& name,
std::array<T,SIZE> const& a) const;
// StrawElectronics functions we are allowed to use
inline size_t nADCPreSamples() const { return _strawElectronics->nADCPreSamples(); }
inline double adcLSB() const { return _strawElectronics->adcLSB(); }
inline double totLSB() const { return _strawElectronics->totLSB(); }
inline double adcPeriod() const { return _strawElectronics->adcPeriod(); }
inline uint16_t maxADC() const { return _strawElectronics->maxADC(); }
// StrawPhysics functions we are allowed to use
inline double ionizationEnergy(double q) const { return _strawPhysics->ionizationEnergy(q); }
double wpRes(double kedep, double wdist) const;
private:
// helper functions
static double PieceLine(std::vector<double> const& xvals,
std::vector<double> const& yvals, double xval);
StrawDrift::cptr_t _strawDrift;
StrawElectronics::cptr_t _strawElectronics;
StrawPhysics::cptr_t _strawPhysics;
// parametric data for calibration functions
// TD reconstruction uses 1/2 the propagation velocity and depends on the
// Dependence on position and straw length still needed FIXME!
// (reconstructed) energy deposit
bool _evenBins;
int _eBins;
double _eBinWidth;
std::vector<double> _edep; // energy deposit boundaries
std::vector<double> _halfvp; // effective 1/2 propagation velocity by edep
double _central; // max wire distance for central wire region
std::vector<double> _centres; // wire center resolution by edep
std::vector<double> _resslope; // resolution slope vs position by edep
size_t _totTBins;
double _totTBinWidth;
size_t _totEBins;
double _totEBinWidth;
std::vector<double> _totdtime;
bool _usederr; // flag to use the doca-dependent calibration of the drift error
std::vector<double> _derr; // parameters describing the drift error function
bool _usepderr; // flag to use calculated version of drift error calculation
std::vector<double> _parDriftDocas;
std::vector<double> _parDriftOffsets;
std::vector<double> _parDriftRes;
double _wbuf; // buffer at the edge of the straws, in terms of sigma
double _slfac; // factor of straw length to set 'missing cluster' hits
double _errfac; // error inflation for 'missing cluster' hits
bool _usenonlindrift;
double _lindriftvel;
double _rres_min;
double _rres_max;
double _rres_rad;
double _mint0doca; // minimum doca for t0 calculation. Note this is a SIGNED QUANTITITY
double _t0shift;
std::array<double, StrawId::_nustraws> _pmpEnergyScale;
std::array<double, StrawId::_nupanels> _timeOffsetPanel;
std::array<double, StrawId::_nustraws> _timeOffsetStrawHV;
std::array<double, StrawId::_nustraws> _timeOffsetStrawCal;
double _electronicsTimeDelay;
double _gasGain;
std::array<double,StrawElectronics::npaths> _analognoise; //noise (mVolt) from the straw itself
std::array<double,StrawElectronics::npaths> _dVdI; // scale factor between charge and voltage (milliVolts/picoCoulombs)
double _vsat;
double _ADCped;
double _pmpEnergyScaleAvg;
};
}
#endif
| 47.409091 | 141 | 0.735166 | lborrel |
c88fb017ce154fca4bcaf7cd635396e65d64ee2f | 829 | hpp | C++ | third_party/zeromq/src/macros.hpp | Martin-Oehler/tiny-differentiable-simulator | 36c76f60450aa00ccabf44caee8a8d27514e95dd | [
"Apache-2.0"
] | 862 | 2020-05-14T19:22:27.000Z | 2022-03-20T20:23:24.000Z | third_party/zeromq/src/macros.hpp | Martin-Oehler/tiny-differentiable-simulator | 36c76f60450aa00ccabf44caee8a8d27514e95dd | [
"Apache-2.0"
] | 82 | 2020-05-26T11:41:33.000Z | 2022-03-15T16:46:00.000Z | third_party/zeromq/src/macros.hpp | Martin-Oehler/tiny-differentiable-simulator | 36c76f60450aa00ccabf44caee8a8d27514e95dd | [
"Apache-2.0"
] | 93 | 2020-05-15T05:37:59.000Z | 2022-03-03T09:09:50.000Z |
/******************************************************************************/
/* 0MQ Internal Use */
/******************************************************************************/
#define LIBZMQ_UNUSED(object) (void) object
#define LIBZMQ_DELETE(p_object) \
{ \
delete p_object; \
p_object = 0; \
}
/******************************************************************************/
#if !defined ZMQ_NOEXCEPT
#if defined ZMQ_HAVE_NOEXCEPT
#define ZMQ_NOEXCEPT noexcept
#else
#define ZMQ_NOEXCEPT
#endif
#endif
| 37.681818 | 80 | 0.24608 | Martin-Oehler |
c89119af28b381c6c906a650419a79ab2d778611 | 13,865 | cc | C++ | src/devices/lib/amlogic/aml-pdm-audio.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/devices/lib/amlogic/aml-pdm-audio.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | src/devices/lib/amlogic/aml-pdm-audio.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/ddk/debug.h>
#include <limits>
#include <memory>
#include <utility>
#include <fbl/alloc_checker.h>
#include <soc/aml-common/aml-pdm-audio.h>
// Filter configurations
// mode 1 lpf1
static const uint32_t lpf1m1[] = {
0x000014, 0xffffb2, 0xfffed9, 0xfffdce, 0xfffd45, 0xfffe32, 0x000147, 0x000645, 0x000b86,
0x000e21, 0x000ae3, 0x000000, 0xffeece, 0xffdca8, 0xffd212, 0xffd7d1, 0xfff2a7, 0x001f4c,
0x0050c2, 0x0072aa, 0x006ff1, 0x003c32, 0xffdc4e, 0xff6a18, 0xff0fef, 0xfefbaf, 0xff4c40,
0x000000, 0x00ebc8, 0x01c077, 0x02209e, 0x01c1a4, 0x008e60, 0xfebe52, 0xfcd690, 0xfb8fa5,
0xfba498, 0xfd9812, 0x0181ce, 0x06f5f3, 0x0d112f, 0x12a958, 0x169686, 0x18000e, 0x169686,
0x12a958, 0x0d112f, 0x06f5f3, 0x0181ce, 0xfd9812, 0xfba498, 0xfb8fa5, 0xfcd690, 0xfebe52,
0x008e60, 0x01c1a4, 0x02209e, 0x01c077, 0x00ebc8, 0x000000, 0xff4c40, 0xfefbaf, 0xff0fef,
0xff6a18, 0xffdc4e, 0x003c32, 0x006ff1, 0x0072aa, 0x0050c2, 0x001f4c, 0xfff2a7, 0xffd7d1,
0xffd212, 0xffdca8, 0xffeece, 0x000000, 0x000ae3, 0x000e21, 0x000b86, 0x000645, 0x000147,
0xfffe32, 0xfffd45, 0xfffdce, 0xfffed9, 0xffffb2, 0x000014,
};
constexpr uint32_t kLpf1m1Len = static_cast<uint32_t>(std::size(lpf1m1));
// mode 1 lpf3
static const uint32_t lpf3m1[] = {
0x000000, 0x000081, 0x000000, 0xfffedb, 0x000000, 0x00022d, 0x000000, 0xfffc46, 0x000000,
0x0005f7, 0x000000, 0xfff6eb, 0x000000, 0x000d4e, 0x000000, 0xffed1e, 0x000000, 0x001a1c,
0x000000, 0xffdcb0, 0x000000, 0x002ede, 0x000000, 0xffc2d1, 0x000000, 0x004ebe, 0x000000,
0xff9beb, 0x000000, 0x007dd7, 0x000000, 0xff633a, 0x000000, 0x00c1d2, 0x000000, 0xff11d5,
0x000000, 0x012368, 0x000000, 0xfe9c45, 0x000000, 0x01b252, 0x000000, 0xfdebf6, 0x000000,
0x0290b8, 0x000000, 0xfcca0d, 0x000000, 0x041d7c, 0x000000, 0xfa8152, 0x000000, 0x07e9c6,
0x000000, 0xf28fb5, 0x000000, 0x28b216, 0x3fffde, 0x28b216, 0x000000, 0xf28fb5, 0x000000,
0x07e9c6, 0x000000, 0xfa8152, 0x000000, 0x041d7c, 0x000000, 0xfcca0d, 0x000000, 0x0290b8,
0x000000, 0xfdebf6, 0x000000, 0x01b252, 0x000000, 0xfe9c45, 0x000000, 0x012368, 0x000000,
0xff11d5, 0x000000, 0x00c1d2, 0x000000, 0xff633a, 0x000000, 0x007dd7, 0x000000, 0xff9beb,
0x000000, 0x004ebe, 0x000000, 0xffc2d1, 0x000000, 0x002ede, 0x000000, 0xffdcb0, 0x000000,
0x001a1c, 0x000000, 0xffed1e, 0x000000, 0x000d4e, 0x000000, 0xfff6eb, 0x000000, 0x0005f7,
0x000000, 0xfffc46, 0x000000, 0x00022d, 0x000000, 0xfffedb, 0x000000, 0x000081, 0x000000,
};
constexpr uint32_t kLpf3m1Len = static_cast<uint32_t>(std::size(lpf3m1));
// osr64 lpf2
static const uint32_t lpf2osr64[] = {
0x00050a, 0xfff004, 0x0002c1, 0x003c12, 0xffa818, 0xffc87d, 0x010aef, 0xff5223, 0xfebd93,
0x028f41, 0xff5c0e, 0xfc63f8, 0x055f81, 0x000000, 0xf478a0, 0x11c5e3, 0x2ea74d, 0x11c5e3,
0xf478a0, 0x000000, 0x055f81, 0xfc63f8, 0xff5c0e, 0x028f41, 0xfebd93, 0xff5223, 0x010aef,
0xffc87d, 0xffa818, 0x003c12, 0x0002c1, 0xfff004, 0x00050a,
};
constexpr uint32_t kLpf2osr64Len = static_cast<uint32_t>(std::size(lpf2osr64));
// static
std::unique_ptr<AmlPdmDevice> AmlPdmDevice::Create(
fdf::MmioBuffer pdm_mmio, fdf::MmioBuffer audio_mmio, ee_audio_mclk_src_t pdm_clk_src,
uint32_t sysclk_div, uint32_t dclk_div, aml_toddr_t toddr_dev, metadata::AmlVersion version) {
// TODDR A has 256 64-bit lines in the FIFO, B and C have 128.
uint32_t fifo_depth = 128 * 8; // in bytes.
if (toddr_dev == TODDR_A) {
fifo_depth = 256 * 8;
}
fbl::AllocChecker ac;
auto pdm = std::unique_ptr<AmlPdmDevice>(
new (&ac) AmlPdmDevice(std::move(pdm_mmio), std::move(audio_mmio), pdm_clk_src, sysclk_div,
dclk_div, toddr_dev, fifo_depth, version));
if (!ac.check()) {
zxlogf(ERROR, "%s: Could not create AmlPdmDevice", __func__);
return nullptr;
}
pdm->InitRegs();
constexpr uint32_t default_frames_per_second = 48000;
pdm->ConfigFilters(default_frames_per_second);
return pdm;
}
void AmlPdmDevice::InitRegs() {
// Setup toddr block
switch (version_) {
case metadata::AmlVersion::kS905D2G:
audio_mmio_.Write32((0x30 << 16) | // Enable interrupts for FIFO errors.
(0x02 << 13) | // Right justified 16-bit
(31 << 8) | // msb position of data out of pdm
(16 << 3) | // lsb position of data out of pdm
(0x04 << 0), // select pdm as data source
GetToddrOffset(TODDR_CTRL0_OFFS));
audio_mmio_.Write32(((fifo_depth_ / 8 / 2) << 16) | // trigger ddr when fifo half full
(0x02 << 8), // STATUS2 source is ddr position
GetToddrOffset(TODDR_CTRL1_OFFS));
break;
case metadata::AmlVersion::kS905D3G:
audio_mmio_.Write32((0x02 << 13) | // Right justified 16-bit
(31 << 8) | // msb position of data out of pdm
(16 << 3), // lsb position of data out of pdm
GetToddrOffset(TODDR_CTRL0_OFFS));
audio_mmio_.Write32((0x04 << 28) | // select pdm as data source
((fifo_depth_ / 8 / 2) << 12) | // trigger ddr when fifo half full
(0x02 << 8), // STATUS2 source is ddr position
GetToddrOffset(TODDR_CTRL1_OFFS));
break;
}
//*To keep things simple, we are using the same clock source for both the
// pdm sysclk and dclk. Sysclk needs to be ~100-200MHz per AmLogic recommendations.
// dclk is osr*fs
//*Sysclk must be configured, enabled, and PDM audio clock gated prior to
// accessing any of the registers mapped via pdm_mmio. Writing without sysclk
// operating properly (and in range) will result in unknown results, reads
// will wedge the system.
audio_mmio_.Write32((clk_src_ << 24) | dclk_div_, EE_AUDIO_CLK_PDMIN_CTRL0);
audio_mmio_.Write32((1 << 31) | (clk_src_ << 24) | sysclk_div_, EE_AUDIO_CLK_PDMIN_CTRL1);
audio_mmio_.SetBits32((1 << 31) | (1 << toddr_ch_), EE_AUDIO_ARB_CTRL);
// Enable the audio domain clocks used by this instance.
AudioClkEna(EE_AUDIO_CLK_GATE_PDM | (EE_AUDIO_CLK_GATE_TODDRA << toddr_ch_) |
EE_AUDIO_CLK_GATE_ARB);
// It is now safe to write to pdm registers
// Ensure clocks are stable before accessing any of the pdm_mmio_ registers.
zx::nanosleep(zx::deadline_after(zx::msec(10)));
// Ensure system is in idle state in case we are re-initing hardware
// which was already running. Keep de-inited for 100ms with no pdm_dclk to
// ensure pdm microphones will start reliably.
Stop();
zx::nanosleep(zx::deadline_after(zx::msec(100)));
// Enable cts_pdm_clk gate (clock gate within pdm module)
pdm_mmio_.SetBits32(0x01, PDM_CLKG_CTRL);
pdm_mmio_.Write32((0x01 << 29), // 24bit output mode
PDM_CTRL);
// This sets the number of sysclk cycles between edge of dclk and when
// data is sampled. AmLogic material suggests this should be 3/4 of a
// dclk half-cycle. Go ahead and set all eight channels.
uint32_t samp_delay = 3 * (dclk_div_ + 1) / (4 * 2 * (sysclk_div_ + 1));
pdm_mmio_.Write32((samp_delay << 0) | (samp_delay << 8) | (samp_delay << 16) | (samp_delay << 24),
PDM_CHAN_CTRL);
pdm_mmio_.Write32((samp_delay << 0) | (samp_delay << 8) | (samp_delay << 16) | (samp_delay << 24),
PDM_CHAN_CTRL1);
}
void AmlPdmDevice::ConfigFilters(uint32_t frames_per_second) {
ZX_ASSERT(frames_per_second == 96000 || frames_per_second == 48000);
uint32_t gain_shift = (frames_per_second == 96000) ? 0xe : 0x15;
uint32_t downsample_rate = (frames_per_second == 96000) ? 0x4 : 0x8;
pdm_mmio_.Write32((1 << 31) | // Enable
(gain_shift << 24) | // Final gain shift parameter
(0x80 << 16) | // Final gain multiplier
(downsample_rate << 4) | // hcic downsample rate
(0x07 << 0), // hcic stage number (must be between 3-9)
PDM_HCIC_CTRL1);
// Note: The round mode field for the lowpass control registers is shown in AmLogic
// documentation to be occupying bits [16:15] fo the register. This was confirmed
// by amlogic to be an error in the datasheet and the correct position is [17:16]
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x01 << 16) | // Round mode
(0x02 << 12) | // Filter 1 downsample rate
(kLpf1m1Len << 0), // Number of taps in filter
PDM_F1_CTRL);
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x00 << 16) | // Round mode
(0x02 << 12) | // Filter 2 downsample rate
(kLpf2osr64Len << 0), // Number of taps in filter
PDM_F2_CTRL);
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x01 << 16) | // Round mode
(2 << 12) | // Filter 3 downsample rate
(kLpf3m1Len << 0), // Number of taps in filter
PDM_F3_CTRL);
pdm_mmio_.Write32((0x01 << 31) | // Enable filter
(0x0d << 16) | // Shift steps
(0x8000 << 0), // Output factor
PDM_HPF_CTRL);
// set coefficient index pointer to 0
pdm_mmio_.Write32(0x0000, PDM_COEFF_ADDR);
// Write coefficients to coefficient memory
// --these appear to be packed with the filter length in each filter
// control register being the mechanism that helps reference them
for (uint32_t i = 0; i < std::size(lpf1m1); i++) {
pdm_mmio_.Write32(lpf1m1[i], PDM_COEFF_DATA);
}
for (uint32_t i = 0; i < std::size(lpf2osr64); i++) {
pdm_mmio_.Write32(lpf2osr64[i], PDM_COEFF_DATA);
}
for (uint32_t i = 0; i < std::size(lpf3m1); i++) {
pdm_mmio_.Write32(lpf3m1[i], PDM_COEFF_DATA);
}
// set coefficient index pointer back to 0
pdm_mmio_.Write32(0x0000, PDM_COEFF_ADDR);
}
void AmlPdmDevice::SetMute(uint8_t mute_mask) {
pdm_mmio_.ModifyBits<uint32_t>(static_cast<uint32_t>(mute_mask) << 20, 0xff << 20, PDM_CTRL);
}
void AmlPdmDevice::SetRate(uint32_t frames_per_second) {
ZX_ASSERT(frames_per_second == 48000 || frames_per_second == 96000);
ConfigFilters(frames_per_second);
}
uint32_t AmlPdmDevice::GetRingPosition() {
uint32_t pos = audio_mmio_.Read32(GetToddrOffset(TODDR_STATUS2_OFFS));
uint32_t base = audio_mmio_.Read32(GetToddrOffset(TODDR_START_ADDR_OFFS));
return (pos - base);
}
uint32_t AmlPdmDevice::GetDmaStatus() {
return audio_mmio_.Read32(GetToddrOffset(TODDR_STATUS1_OFFS));
}
uint32_t AmlPdmDevice::GetPdmStatus() { return audio_mmio_.Read32(PDM_STS); }
void AmlPdmDevice::AudioClkEna(uint32_t audio_blk_mask) {
audio_mmio_.SetBits32(audio_blk_mask, EE_AUDIO_CLK_GATE_EN);
}
void AmlPdmDevice::AudioClkDis(uint32_t audio_blk_mask) {
audio_mmio_.ClearBits32(audio_blk_mask, EE_AUDIO_CLK_GATE_EN);
}
zx_status_t AmlPdmDevice::SetBuffer(zx_paddr_t buf, size_t len) {
// Ensure ring buffer resides in lower memory (dma pointers are 32-bit)
// and len is at least 8 (size of each dma operation)
if (((buf + len - 1) > std::numeric_limits<uint32_t>::max()) || (len < 8)) {
return ZX_ERR_INVALID_ARGS;
}
// Write32 the start and end pointers. Each fetch is 64-bits, so end pointer
// is pointer to the last 64-bit fetch (inclusive)
audio_mmio_.Write32(static_cast<uint32_t>(buf), GetToddrOffset(TODDR_START_ADDR_OFFS));
audio_mmio_.Write32(static_cast<uint32_t>(buf), GetToddrOffset(TODDR_INIT_ADDR_OFFS));
audio_mmio_.Write32(static_cast<uint32_t>(buf + len - 8), GetToddrOffset(TODDR_FINISH_ADDR_OFFS));
return ZX_OK;
}
// Stops the pdm from clocking
void AmlPdmDevice::PdmInDisable() {
audio_mmio_.ClearBits32(1 << 31, EE_AUDIO_CLK_PDMIN_CTRL0);
pdm_mmio_.ClearBits32((1 << 31) | (1 << 16), PDM_CTRL);
}
// Enables the pdm to clock data
void AmlPdmDevice::PdmInEnable() {
// Start pdm_dclk
audio_mmio_.SetBits32(1 << 31, EE_AUDIO_CLK_PDMIN_CTRL0);
pdm_mmio_.SetBits32((1 << 31) | (1 << 16), PDM_CTRL);
}
// Takes channels out of reset and enables them.
void AmlPdmDevice::ConfigPdmIn(uint8_t mask) {
pdm_mmio_.ModifyBits<uint32_t>((mask << 8) | (mask << 0), (0xff << 8) | (0xff << 0), PDM_CTRL);
}
void AmlPdmDevice::TODDREnable() {
// Set the load bit, will make sure things start from beginning of buffer
audio_mmio_.SetBits32(1 << 31, GetToddrOffset(TODDR_CTRL0_OFFS));
}
void AmlPdmDevice::TODDRDisable() {
// Clear the load bit (this is the bit that forces the initial fetch of
// start address into current ptr)
audio_mmio_.ClearBits32(1 << 31, GetToddrOffset(TODDR_CTRL0_OFFS));
audio_mmio_.ClearBits32(1 << 25, GetToddrOffset(TODDR_CTRL1_OFFS));
}
void AmlPdmDevice::Sync() {
pdm_mmio_.ClearBits32(1 << 16, PDM_CTRL);
pdm_mmio_.SetBits32(1 << 16, PDM_CTRL);
}
// Resets frddr mechanisms to start at beginning of buffer
// starts the frddr (this will fill the fifo)
// starts the tdm to clock out data on the bus
// returns the start time
uint64_t AmlPdmDevice::Start() {
uint64_t a, b;
Sync();
TODDREnable();
a = zx_clock_get_monotonic();
PdmInEnable();
b = zx_clock_get_monotonic();
return ((b - a) >> 1) + a;
}
void AmlPdmDevice::Stop() {
PdmInDisable();
TODDRDisable();
}
void AmlPdmDevice::Shutdown() { Stop(); }
| 45.016234 | 100 | 0.660945 | fabio-d |
c89248bf62a79ad2f47c29d90aaac243f3ef9eb0 | 1,936 | cpp | C++ | Plugins/LeapMotion/Source/LeapMotion/Private/LeapGesture.cpp | vrmad1/UE4-LeapMotionPlugin | 1cbbd4fe30bb2b0c7b6f1a641eb3afb69cab49ae | [
"MIT"
] | 246 | 2015-01-03T03:29:03.000Z | 2021-11-17T11:22:58.000Z | Plugins/LeapMotion/Source/LeapMotion/Private/LeapGesture.cpp | vrmad1/UE4-LeapMotionPlugin | 1cbbd4fe30bb2b0c7b6f1a641eb3afb69cab49ae | [
"MIT"
] | 27 | 2015-01-07T04:57:47.000Z | 2021-11-23T17:14:10.000Z | Plugins/LeapMotion/Source/LeapMotion/Private/LeapGesture.cpp | vrmad1/UE4-LeapMotionPlugin | 1cbbd4fe30bb2b0c7b6f1a641eb3afb69cab49ae | [
"MIT"
] | 88 | 2015-01-08T15:35:14.000Z | 2021-04-14T02:27:57.000Z | #include "LeapMotionPrivatePCH.h"
class PrivateGesture
{
public:
Leap::Gesture Gesture;
};
ULeapGesture::ULeapGesture(const FObjectInitializer &ObjectInitializer) : UObject(ObjectInitializer), Private(new PrivateGesture())
{
}
ULeapGesture::~ULeapGesture()
{
delete Private;
}
ULeapFrame* ULeapGesture::Frame()
{
if (PFrame == nullptr)
{
PFrame = NewObject<ULeapFrame>(this);
}
PFrame->SetFrame(Private->Gesture.frame());
return (PFrame);
}
ULeapHandList* ULeapGesture::Hands()
{
if (PHands == nullptr)
{
PHands = NewObject<ULeapHandList>(this);
}
PHands->SetHandList(Private->Gesture.hands());
return (PHands);
}
ULeapPointableList* ULeapGesture::Pointables()
{
if (PPointables == nullptr)
{
PPointables = NewObject<ULeapPointableList>(this);
}
PPointables->SetPointableList(Private->Gesture.pointables());
return (PPointables);
}
LeapGestureState gestureState(Leap::Gesture::State State)
{
switch (State)
{
case Leap::Gesture::STATE_START:
return (GESTURE_STATE_START);
case Leap::Gesture::STATE_UPDATE:
return (GESTURE_STATE_UPDATE);
case Leap::Gesture::STATE_STOP:
return (GESTURE_STATE_STOP);
default:
return (GESTURE_STATE_INVALID);
}
}
LeapGestureType gestureType(Leap::Gesture::Type Type)
{
switch (Type)
{
case Leap::Gesture::TYPE_CIRCLE:
return (GESTURE_TYPE_CIRCLE);
case Leap::Gesture::TYPE_KEY_TAP:
return (GESTURE_TYPE_KEY_TAP);
case Leap::Gesture::TYPE_SCREEN_TAP:
return (GESTURE_TYPE_SCREEN_TAP);
case Leap::Gesture::TYPE_SWIPE:
return (GESTURE_TYPE_SWIPE);
default:
return (GESTURE_TYPE_INVALID);
}
}
void ULeapGesture::SetGesture(const Leap::Gesture &Gesture)
{
Private->Gesture = Gesture;
Duration = Private->Gesture.duration();
DurationSeconds = Private->Gesture.durationSeconds();
Id = Private->Gesture.id();
IsValid = Private->Gesture.isValid();
State = gestureState(Private->Gesture.state());
Type = gestureType(Private->Gesture.type());
} | 21.511111 | 131 | 0.742252 | vrmad1 |
c892f3b7eeaeca94f34c24edad0a012e691658cd | 1,241 | cpp | C++ | src/service.cpp | The-Garlic-Network/old | 412b331c1ef484eef54e7da065fb756e0420aa16 | [
"MIT"
] | null | null | null | src/service.cpp | The-Garlic-Network/old | 412b331c1ef484eef54e7da065fb756e0420aa16 | [
"MIT"
] | null | null | null | src/service.cpp | The-Garlic-Network/old | 412b331c1ef484eef54e7da065fb756e0420aa16 | [
"MIT"
] | null | null | null | /**
* service.cpp - Точка входа в программу.
*
* @mrrva - 2019
*/
#include "include/encryption.hpp"
#include "include/network.hpp"
#include "include/storage.hpp"
#include "include/struct.hpp"
int main()
{
using tgnstruct::secret_key;
using tgnstruct::public_key;
using tgnstorage::db;
std::string pub = db.get_var("PUBLIC_KEY");
std::string sec = db.get_var("SECRET_KEY");
const short hs = HASHSIZE * 2;
if (pub.length() == hs && sec.length() == hs) {
public_key = hex2bin<hs>(pub);
secret_key = hex2bin<hs>(sec);
}
else {
tgnencryption::new_keys();
pub = bin2hex<HASHSIZE>(public_key);
sec = bin2hex<HASHSIZE>(secret_key);
db.set_var("PUBLIC_KEY", pub);
db.set_var("SECRET_KEY", sec);
}
tgnstorage::nodes.select();
if (tgnstruct::nodes.size() == 0) {
std::cout << "[E] Node list is empty. Please "
<< "download database with current list "
<< "of nodes.\n";
return 1;
}
if (!tgnnetwork::socket.start()) {
std::cout << "[E] socket.start.\n";
return 1;
}
while (true) {
tgnstorage::neighbors.autocheck();
tgnstorage::clients.autoremove();
tgnstorage::garlic.autoremove();
tgnstorage::nodes.autocheck();
tgnstorage::routes.autoremove();
}
tgnnetwork::recv.join();
return 0;
}
| 20.683333 | 48 | 0.65834 | The-Garlic-Network |
c894784c32653171c9b35077f9789c5bdf2545da | 3,254 | cc | C++ | python/jittor/src/misc/ring_buffer.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 2,571 | 2020-03-20T03:38:35.000Z | 2022-03-31T08:20:05.000Z | python/jittor/src/misc/ring_buffer.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 197 | 2020-03-20T04:11:47.000Z | 2022-03-31T10:14:24.000Z | python/jittor/src/misc/ring_buffer.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 284 | 2020-03-20T03:53:15.000Z | 2022-03-28T07:20:32.000Z | // ***************************************************************
// Copyright (c) 2021 Jittor. All Rights Reserved.
// Maintainers: Dun Liang <randonlang@gmail.com>.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#include <chrono>
#include <thread>
#ifndef _WIN32
#include <sys/mman.h>
#endif
#include "common.h"
#include "misc/ring_buffer.h"
namespace jittor {
RingBuffer::RingBuffer(uint64 size, bool multiprocess) : m(multiprocess), cv(multiprocess) {
int i=0;
for (;(1ll<<i)<size;i++);
size_mask = (1ll<<i)-1;
this->size = size_mask+1;
size_bit = i;
l = r = is_wait = is_stop = 0;
is_multiprocess = multiprocess;
}
void RingBuffer::stop() {
MutexScope _(m);
is_stop = 1;
cv.notify();
}
RingBuffer::~RingBuffer() {
stop();
}
RingBuffer* RingBuffer::make_ring_buffer(uint64 size, bool multiprocess, uint64 buffer, bool init) {
int i=0;
for (;(1ll<<i)<size;i++);
uint64 size_mask = (1ll<<i)-1;
size = size_mask+1;
uint64 total_size = sizeof(RingBuffer) + size;
void* ptr = multiprocess ?
// mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0) :
#ifndef _WIN32
mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)
#else
// TODO: multiprocess ring buffer in windows
(void*)buffer
#endif
:
// mmap(NULL, total_size, PROT_READ | PROT_WRITE, MAP_SHARED, -1, 0) :
(void*)malloc(total_size);
auto rb = (RingBuffer*)ptr;
if (!init) return rb;
std::memset(ptr, 0, total_size);
new (rb) RingBuffer(size, multiprocess);
return rb;
}
void RingBuffer::free_ring_buffer(RingBuffer* rb, uint64 buffer, bool init) {
uint64 total_size = sizeof(RingBuffer) + rb->size;
auto is_multiprocess = rb->is_multiprocess;
if (init)
rb->~RingBuffer();
if (is_multiprocess) {
#ifndef _WIN32
munmap(rb, total_size);
#else
if (!buffer)
free((void*)rb);
// this buffer is not owned by this obj
#endif
(void)total_size;
} else {
free((void*)rb);
}
}
// test
JIT_TEST(ring_buffer_benchmark) {
size_t n = 1ll << 20;
size_t size = 1<<15;
// size_t n = 1ll << 30;
// size_t size = 1<<20;
// size_t n = 1ll << 10;
// size_t size = 1<<5;
RingBuffer* rb = RingBuffer::make_ring_buffer(size, 0);
std::thread p([&]() {
for (size_t i=0; i<n; i++) {
rb->push_t<int>(i);
}
});
auto start = std::chrono::high_resolution_clock::now();
size_t s = 0;
for (size_t i=0; i<n; i++) {
auto x = rb->pop_t<int>();
s += x;
}
auto finish = std::chrono::high_resolution_clock::now();
auto tt = std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();
p.join();
expect_error([&]() { rb->push(size+1); });
RingBuffer::free_ring_buffer(rb);
LOGi << tt << tt*1.0/n;
LOGi << s << (n*(n-1)/2);
ASSERTop(s,==,(n*(n-1)/2));
ASSERTop(tt*1.0/n,<=,100);
}
}
| 28.295652 | 108 | 0.56638 | Exusial |
c8970ae43c456d41ceb28e24702c317cb3b7a059 | 8,954 | cxx | C++ | itkEMS/robust/QHullMSTClusteringProcess.cxx | NIRALUser/ARCTIC | 0cc38d92db43a3861e6e7491d516d5edb543bc4b | [
"Apache-2.0"
] | null | null | null | itkEMS/robust/QHullMSTClusteringProcess.cxx | NIRALUser/ARCTIC | 0cc38d92db43a3861e6e7491d516d5edb543bc4b | [
"Apache-2.0"
] | null | null | null | itkEMS/robust/QHullMSTClusteringProcess.cxx | NIRALUser/ARCTIC | 0cc38d92db43a3861e6e7491d516d5edb543bc4b | [
"Apache-2.0"
] | 2 | 2016-06-20T15:06:11.000Z | 2019-01-24T02:19:07.000Z |
#include "Heap.h"
#include "QHullMSTClusteringProcess.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern "C"
{
#include "qhull.h"
#include "mem.h"
#include "qset.h"
}
#define BUF_SIZE 2048
#define QHULL_COMMAND "qhull d QJ Tv "
//#define QHULL_COMMAND "qhull d QJ "
// For sorting cluster maps based on size (descending)
class MSTCluster
{
public:
unsigned int map;
unsigned int size;
MSTCluster() { this->map = 0; this->size = 0; }
~MSTCluster() { }
inline MSTCluster& operator=(const MSTCluster& c)
{ this->map = c.map; this->size = c.size; return (*this); }
inline bool operator<(const MSTCluster& c) const
{ return this->size > c.size; }
};
QHullMSTClusteringProcess
::QHullMSTClusteringProcess()
{
m_NumberOfVertices = 0;
m_MSTEdges = 0;
m_NodeAverages = 0;
m_SortFlag = false;
}
QHullMSTClusteringProcess
::~QHullMSTClusteringProcess()
{
delete [] m_MSTEdges;
delete [] m_NodeAverages;
}
void
QHullMSTClusteringProcess
::SetInputVertices(const VertexList& vlist)
{
m_NumberOfVertices = vlist.GetSize();
delete [] m_MSTEdges;
delete [] m_NodeAverages;
if (m_NumberOfVertices == 0)
return;
unsigned int dim = vlist[0].size();
m_MSTEdges = new MSTEdge[m_NumberOfVertices-1];
m_NodeAverages = new float[m_NumberOfVertices];
// Compute Delaunay triangulation and insert it to heap
Heap<MSTEdge> delaunayHeap;
int curlong, totlong, exitcode;
char options [BUF_SIZE];
coordT *points;
facetT *facet;
vertexT *vertex, **vertexp;
// Allocate memory to store elements of the list
points = (coordT*) malloc((dim+1)*m_NumberOfVertices*sizeof(coordT));
// Store each coordinate in an array element
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
{
VertexType v = vlist[k];
long pos = k*(dim+1);
#if 1
double sumS = 0;
for (unsigned int j = 0; j < dim; j++)
{
points[pos+j] = v[j];
sumS += v[j] * v[j];
}
points[pos+dim] = sumS;
#else
points[pos+dim] = 0.0;
#endif
}
// Call out to qhull library to compute DeLaunay triangulation
qh_init_A(stdin, stdout, stderr, 0, NULL);
exitcode= setjmp(qh errexit);
if (!exitcode)
{
// Add extra options here
strcpy(options, QHULL_COMMAND);
qh_initflags(options);
qh_setdelaunay(dim+1, m_NumberOfVertices, points);
qh_init_B(points, m_NumberOfVertices, dim+1, False);
qh_qhull();
qh_check_output();
long numfacets = 0;
FORALLfacets
{
if (!facet->upperdelaunay)
{
numfacets++;
}
}
// Insert DT edges to heap
FORALLfacets
{
if (!facet->upperdelaunay)
{
DynArray<unsigned int> ids;
ids.Allocate(dim+1);
FOREACHvertex_(facet->vertices)
{
ids.Append( qh_pointid(vertex->point) );
}
for (unsigned int s = 0; s < ids.GetSize(); s++)
for (unsigned int t = s+1; t < ids.GetSize(); t++)
{
MSTEdge e;
e.i = ids[s];
e.j = ids[t];
VertexType dij = vlist[e.i] - vlist[e.j];
e.dist = dij.squared_magnitude();
delaunayHeap.Insert(e);
}
}
}
}
// Free allocated memory
qh NOerrexit= True;
qh_freeqhull (False);
qh_memfreeshort (&curlong, &totlong);
free(points);
if (curlong || totlong)
{
std::cerr << "qhull internal warning (main): did not free " << totlong
<< "bytes of long memory (" << curlong << "pieces)" << std::endl;
throw "QHull error";
}
// Map vertex to set (tree) it belongs to, for cycle test
unsigned int* treeMap = new unsigned int[m_NumberOfVertices];
for (unsigned int i = 0; i < m_NumberOfVertices; i++)
treeMap[i] = i;
// Number of edges in MST
unsigned int edgeCount = 0;
// Build MST using Kruskal's algorithm
//
// Edges added in ascending order
while (!delaunayHeap.IsEmpty())
{
MSTEdge minEdge = delaunayHeap.ExtractMinimum();
unsigned int a = minEdge.i;
unsigned int b = minEdge.j;
unsigned int map1 = treeMap[a];
unsigned int map2 = treeMap[b];
// Skip if they belong to the same tree (will form cycle)
if (map1 == map2)
continue;
// Merge trees
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
{
if (treeMap[k] == map2)
treeMap[k] = map1;
}
m_MSTEdges[edgeCount] = minEdge;
edgeCount++;
// See if a tree is formed already
if (edgeCount == (m_NumberOfVertices-1))
break;
}
delete [] treeMap;
if (edgeCount != (m_NumberOfVertices-1))
{
std::cerr << "MST construction failed, E != (V-1)" << std::endl;
throw "MST construction failed, E != (V-1)";
}
// Compute node averages
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
m_NodeAverages[k] = 0.0;
unsigned int* countArray = new unsigned int[m_NumberOfVertices];
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
countArray[k] = 0;
DynArray< DynArray<double> > nodeDistances;
nodeDistances.Allocate(m_NumberOfVertices+1);
for (unsigned int i = 0; i <= m_NumberOfVertices+1; i++)
{
DynArray<double> dlist;
nodeDistances.Append(dlist);
}
for (unsigned int k = 0; k < (m_NumberOfVertices-1); k++)
{
unsigned int a = m_MSTEdges[k].i;
unsigned int b = m_MSTEdges[k].j;
m_NodeAverages[a] += m_MSTEdges[k].dist;
countArray[a]++;
m_NodeAverages[b] += m_MSTEdges[k].dist;
countArray[b]++;
nodeDistances[a].Append(m_MSTEdges[k].dist);
nodeDistances[b].Append(m_MSTEdges[k].dist);
}
for (unsigned int k = 0; k < m_NumberOfVertices; k++)
{
// Use mean OR...
//if (countArray[k] != 0)
// m_NodeAverages[k] /= countArray[k];
// Median instead?
if (countArray[k] != 0)
m_NodeAverages[k] =
heapMedian(nodeDistances[k].GetRawArray(), nodeDistances[k].GetSize());
}
delete [] countArray;
}
unsigned int
QHullMSTClusteringProcess
::GetClusters(unsigned int* treeMap, float T)
{
// Get number of vertices and edges
unsigned int v = m_NumberOfVertices;
unsigned int e = v - 1;
// Allocate edge break flag array
unsigned char* breakArray = new unsigned char[e];
for (unsigned int k = 0; k < e; k++)
breakArray[k] = 0;
// Break edges
unsigned int numBroken = 0;
for (unsigned int i = 0; i < v; i++)
{
float thres = T * m_NodeAverages[i];
// Break the coinciding long edges
for (unsigned int k = 0; k < e; k++)
{
if (breakArray[k] != 0)
continue;
unsigned int a = m_MSTEdges[k].i;
unsigned int b = m_MSTEdges[k].j;
bool incident = (i == a) || (i == b);
// Never break zero length edges
if (incident && (m_MSTEdges[k].dist > thres))
{
breakArray[k] = 1;
numBroken++;
}
}
}
if (numBroken == 0)
{
std::cerr << "No edges broken" << std::endl;
delete [] breakArray;
// TODO: FIXME:
//return whole tree with same label
return 0;
}
// Figure out distinct trees, merge connected vertices
for (unsigned int k = 0; k < v; k++)
treeMap[k] = k;
for (unsigned int i = 0; i < v; i++)
{
unsigned int map1 = treeMap[i];
// Check incident edges
for (unsigned int j = 0; j < e; j++)
{
if (breakArray[j] != 0)
continue;
unsigned int a = m_MSTEdges[j].i;
unsigned int b = m_MSTEdges[j].j;
bool incident = (i == a) || (i == b);
if (!incident)
continue;
// Get the map of the other id
unsigned int map2 = treeMap[b];
if (i == b)
map2 = treeMap[a];
if (map1 == map2)
continue;
for (unsigned int k = 0; k < v; k++)
if (treeMap[k] == map2)
treeMap[k] = map1;
} // for neighbors
} // for i
delete [] breakArray;
if (!m_SortFlag)
return numBroken+1;
//
// Sort the cluster maps based on cluster size (descending)
// Cluster 0 is the largest cluster
//
// Obtain cluster info
MSTCluster* clusters = new MSTCluster[v];
unsigned int numNonZero = 0;
for (unsigned int i = 0; i < v; i++)
{
clusters[i].map = i;
unsigned int s = 0;
for (unsigned int j = 0; j < v; j++)
if (treeMap[j] == i)
s++;
if (s > 0)
numNonZero++;
clusters[i].size = s;
}
Heap<MSTCluster> heap;
heap.Allocate(numNonZero);
for (unsigned int i = 0; i < v; i++)
if (clusters[i].size != 0)
heap.Insert(clusters[i]);
delete [] clusters;
unsigned int* sortedMap = new unsigned int[v];
for (unsigned int i = 0; i < numNonZero; i++)
{
MSTCluster c = heap.ExtractMinimum();
unsigned int m = c.map;
for (unsigned int j = 0; j < v; j++)
if (treeMap[j] == m)
sortedMap[j] = i;
}
for (unsigned int i = 0; i < v; i++)
treeMap[i] = sortedMap[i];
delete [] sortedMap;
return numBroken+1;
}
| 21.628019 | 79 | 0.595041 | NIRALUser |
c89855adcd4c33f594f70db3cd5c6d089b808a81 | 5,911 | cpp | C++ | Gem/Code/Source/SkinnedMeshExampleComponent.cpp | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | null | null | null | Gem/Code/Source/SkinnedMeshExampleComponent.cpp | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | null | null | null | Gem/Code/Source/SkinnedMeshExampleComponent.cpp | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"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
*
*/
#include <SkinnedMeshExampleComponent.h>
#include <SampleComponentManager.h>
#include <SampleComponentConfig.h>
#include <Automation/ScriptableImGui.h>
#include <Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h>
#include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
#include <Atom/Component/DebugCamera/NoClipControllerBus.h>
#include <AzCore/Script/ScriptTimePoint.h>
#include <Atom/RPI.Public/View.h>
#include <Atom/RPI.Public/Image/StreamingImage.h>
#include <Atom/RPI.Reflect/Asset/AssetUtils.h>
#include <Atom/RPI.Reflect/Model/ModelAsset.h>
#include <Atom/RPI.Reflect/Material/MaterialAsset.h>
#include <RHI/BasicRHIComponent.h>
namespace AtomSampleViewer
{
void SkinnedMeshExampleComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class < SkinnedMeshExampleComponent, AZ::Component>()
->Version(0)
;
}
}
void SkinnedMeshExampleComponent::Activate()
{
CreateSkinnedMeshContainer();
m_skinnedMeshContainer->SetActiveSkinnedMeshCount(1);
AZ::TickBus::Handler::BusConnect();
m_imguiSidebar.Activate();
ConfigureCamera();
AddImageBasedLight();
}
void SkinnedMeshExampleComponent::CreatePlaneObject()
{
auto meshAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>("objects/plane.azmodel");
m_planeMeshHandle = GetMeshFeatureProcessor()->AcquireMesh(AZ::Render::MeshHandleDescriptor{ meshAsset });
GetMeshFeatureProcessor()->SetTransform(m_planeMeshHandle, AZ::Transform::CreateIdentity());
}
void SkinnedMeshExampleComponent::Deactivate()
{
m_skinnedMeshContainer = nullptr;
AZ::TickBus::Handler::BusDisconnect();
m_imguiSidebar.Deactivate();
GetMeshFeatureProcessor()->ReleaseMesh(m_planeMeshHandle);
m_defaultIbl.Reset();
}
void SkinnedMeshExampleComponent::AddImageBasedLight()
{
m_defaultIbl.Init(m_scene);
}
void SkinnedMeshExampleComponent::ConfigureCamera()
{
AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
AZ::Debug::NoClipControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPosition, AZ::Vector3(0.0f, -1.0f, 1.0f));
AZ::Debug::NoClipControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPitch, -0.8f);
}
void SkinnedMeshExampleComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint timePoint)
{
m_runTime += deltaTime;
DrawSidebar();
if (!m_useFixedTime)
{
m_skinnedMeshContainer->UpdateAnimation(m_runTime, m_useOutOfSyncBoneAnimation);
}
if (m_drawBones)
{
m_skinnedMeshContainer->DrawBones();
}
}
void SkinnedMeshExampleComponent::DrawSidebar()
{
if (!m_imguiSidebar.Begin())
{
return;
}
SkinnedMeshConfig config = m_skinnedMeshContainer->GetSkinnedMeshConfig();
bool configWasModified = false;
// Imgui limits slider range to half the natural range of the type
float segmentCountFloat = static_cast<float>(config.m_segmentCount);
configWasModified |= ScriptableImGui::SliderFloat("Segments Per-Mesh", &segmentCountFloat, 2.0f, 2048.0f, "%.0f", ImGuiSliderFlags_Logarithmic);
configWasModified |= ScriptableImGui::SliderInt("Vertices Per-Segment", &config.m_verticesPerSegment, 4, 2048);
configWasModified |= ScriptableImGui::SliderInt("Bones Per-Mesh", &config.m_boneCount, 4, 256);
configWasModified |= ScriptableImGui::SliderInt("Influences Per-Vertex", &config.m_influencesPerVertex, 4, 4);
configWasModified |= ScriptableImGui::SliderInt("Sub-mesh count", &config.m_subMeshCount, 1, 128);
if (configWasModified)
{
config.m_segmentCount = static_cast<int>(segmentCountFloat);
m_skinnedMeshContainer->SetSkinnedMeshConfig(config);
}
bool animationWasModified = configWasModified;
animationWasModified |= ScriptableImGui::Checkbox("Use Fixed Animation Time", &m_useFixedTime);
animationWasModified |= ScriptableImGui::SliderFloat("Fixed Animation Time", &m_fixedAnimationTime, 0.0f, 20.0f);
animationWasModified |= ScriptableImGui::Checkbox("Use Out of Sync Bone Animation", &m_useOutOfSyncBoneAnimation);
if (m_useFixedTime && animationWasModified)
{
m_skinnedMeshContainer->UpdateAnimation(m_fixedAnimationTime, m_useOutOfSyncBoneAnimation);
}
ScriptableImGui::Checkbox("Draw bones", &m_drawBones);
m_imguiSidebar.End();
}
void SkinnedMeshExampleComponent::CreateSkinnedMeshContainer()
{
const auto skinnedMeshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::SkinnedMeshFeatureProcessorInterface>();
const auto meshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::MeshFeatureProcessorInterface>();
// Default settings for the sample
SkinnedMeshConfig config;
config.m_segmentCount = 10;
config.m_verticesPerSegment = 7;
config.m_boneCount = 4;
config.m_influencesPerVertex = 4;
m_skinnedMeshContainer = AZStd::make_unique<SkinnedMeshContainer>(skinnedMeshFeatureProcessor, meshFeatureProcessor, config);
}
}
| 39.671141 | 167 | 0.705464 | Bindless-Chicken |
c89a30e63b180a83d6fa94a0c3359de41219ed24 | 605 | cpp | C++ | src/Search/InAreaSearchSession.cpp | jmakovicka/OsmAnd-core | d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610 | [
"MIT"
] | null | null | null | src/Search/InAreaSearchSession.cpp | jmakovicka/OsmAnd-core | d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610 | [
"MIT"
] | null | null | null | src/Search/InAreaSearchSession.cpp | jmakovicka/OsmAnd-core | d18f57bb123b6c6ad0adbed0c2f4419d0e6a6610 | [
"MIT"
] | null | null | null | #include "InAreaSearchSession.h"
#include "InAreaSearchSession_P.h"
OsmAnd::InAreaSearchSession::InAreaSearchSession(const QList< std::shared_ptr<const ISearchEngine::IDataSource> >& dataSources)
: BaseSearchSession(new InAreaSearchSession_P(this), dataSources)
, _p(std::static_pointer_cast<InAreaSearchSession_P>(BaseSearchSession::_p.shared_ptr()))
{
}
OsmAnd::InAreaSearchSession::~InAreaSearchSession()
{
}
void OsmAnd::InAreaSearchSession::setArea(const AreaI64& area)
{
_p->setArea(area);
}
OsmAnd::AreaI64 OsmAnd::InAreaSearchSession::getArea() const
{
return _p->getArea();
}
| 26.304348 | 127 | 0.771901 | jmakovicka |
c89af4bba658a9c079a4764f48078d18630417df | 13,491 | cpp | C++ | src/openms/source/CHEMISTRY/NASequence.cpp | avasq011/FinalProject_OpenMS_76ers | 6c9e2c295df6ec0eb296a3badfcdff245a869d59 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 1 | 2019-07-15T20:50:22.000Z | 2019-07-15T20:50:22.000Z | src/openms/source/CHEMISTRY/NASequence.cpp | avasq011/FinalProject_OpenMS_76ers | 6c9e2c295df6ec0eb296a3badfcdff245a869d59 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 150 | 2017-09-05T09:43:12.000Z | 2020-02-03T10:07:36.000Z | src/openms/source/CHEMISTRY/NASequence.cpp | avasq011/FinalProject_OpenMS_76ers | 6c9e2c295df6ec0eb296a3badfcdff245a869d59 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 2 | 2018-04-02T18:41:20.000Z | 2018-08-11T21:39:24.000Z | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2018.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Samuel Wein $
// $Authors: Samuel Wein, Timo Sachsenberg, Hendrik Weisser $
// --------------------------------------------------------------------------
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CHEMISTRY/NASequence.h>
#include <OpenMS/CHEMISTRY/RibonucleotideDB.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Macros.h>
#include <map>
#include <string>
using namespace std;
namespace OpenMS
{
NASequence::NASequence(vector<const Ribonucleotide*> seq,
const RibonucleotideChainEnd* five_prime,
const RibonucleotideChainEnd* three_prime)
{
seq_ = seq;
five_prime_ = five_prime;
three_prime_ = three_prime;
}
bool NASequence::operator==(const NASequence& rhs) const
{
return (tie(seq_, five_prime_, three_prime_) ==
tie(rhs.seq_, rhs.five_prime_, rhs.three_prime_));
}
bool NASequence::operator!=(const NASequence& rhs) const
{
return !(operator==(rhs));
}
bool NASequence::operator<(const NASequence& rhs) const
{
// can't use std::tie here as we might prefer sorting by string instead of pointer address
// compare 5' mod
if (five_prime_ != rhs.five_prime_) return (five_prime_ < rhs.five_prime_);
// compare sequence length
if (seq_.size() != rhs.seq_.size()) return (seq_.size() < rhs.seq_.size());
// compare pointers. If different, we compare the more expensive code (string)
for (size_t i = 0; i != seq_.size(); ++i)
{
if (seq_[i] != rhs.seq_[i])
{
return (seq_[i]->getCode() < rhs.seq_[i]->getCode());
}
}
// compare 3' mod
if (three_prime_ != rhs.three_prime_)
{
return (three_prime_ < rhs.three_prime_);
}
// exactly equal
return false;
}
void NASequence::setSequence(const vector<const Ribonucleotide*>& seq)
{
seq_ = seq;
}
bool NASequence::empty() const
{
return seq_.empty();
}
NASequence NASequence::getPrefix(Size length) const
{
if (length >= seq_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
length, seq_.size() - 1);
}
return NASequence({seq_.begin(), seq_.begin() + length}, five_prime_, nullptr);
}
NASequence NASequence::getSuffix(Size length) const
{
if (length >= seq_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
length, seq_.size() - 1);
}
return NASequence({seq_.end() - length, seq_.end()}, nullptr, three_prime_);
}
NASequence NASequence::getSubsequence(Size start, Size length) const
{
if (start >= size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, start, size());
}
if (length > size() - start) length = size() - start;
const RibonucleotideChainEnd* five_prime = ((start == 0) ? five_prime_ :
nullptr);
const RibonucleotideChainEnd* three_prime = ((start + length == size()) ?
three_prime_ : nullptr);
vector<const Ribonucleotide*>::const_iterator it = seq_.begin() + start;
return NASequence({it, it + length}, five_prime, three_prime);
}
EmpiricalFormula NASequence::getFormula(NASFragmentType type, Int charge) const
{
static const EmpiricalFormula H_form = EmpiricalFormula("H");
static const EmpiricalFormula internal_to_full = EmpiricalFormula("H2O");
// static const EmpiricalFormula five_prime_to_full = EmpiricalFormula("HPO3");
// static const EmpiricalFormula three_prime_to_full = EmpiricalFormula("");
static const EmpiricalFormula a_ion_to_full = EmpiricalFormula("H-2O-1");
static const EmpiricalFormula b_ion_to_full = EmpiricalFormula("");
static const EmpiricalFormula c_ion_to_full = EmpiricalFormula("H-1PO2");
static const EmpiricalFormula d_ion_to_full = EmpiricalFormula("HPO3");
static const EmpiricalFormula w_ion_to_full = EmpiricalFormula("HPO3");
static const EmpiricalFormula x_ion_to_full = EmpiricalFormula("H-1PO2");
static const EmpiricalFormula y_ion_to_full = EmpiricalFormula("");
static const EmpiricalFormula z_ion_to_full = EmpiricalFormula("H-2O-1");
static const EmpiricalFormula aminusB_ion_to_full = EmpiricalFormula("H-4O-2");
static const EmpiricalFormula phosphate_form = EmpiricalFormula("HPO3");
// static const EmpiricalFormula abasicform_RNA = EmpiricalFormula("C5H8O4");
// static const EmpiricalFormula abasicform_DNA = EmpiricalFormula("C5H7O5P");
if (seq_.empty()) return EmpiricalFormula();
EmpiricalFormula our_form;
// Add all the ribonucleotide masses
for (const auto& i : seq_)
{
our_form += i->getFormula();
}
// phosphates linking nucleosides:
our_form += (phosphate_form - internal_to_full) * (seq_.size() - 1);
EmpiricalFormula local_three_prime, local_five_prime;
// Make local copies of the formulas for the terminal mods so we don't get into trouble dereferencing nullptrs
if (three_prime_ != nullptr)
{
local_three_prime = three_prime_->getFormula() - H_form;
}
if (five_prime_ != nullptr)
{
local_five_prime = five_prime_->getFormula() - H_form;
}
switch (type)
{
case Full:
return our_form + (H_form * charge) + local_five_prime + local_three_prime;
// case FivePrime:
// return our_form - five_prime_to_full + OH_form + (H_form * charge) + local_three_prime;
case AminusB:
return our_form + (H_form * charge) + local_five_prime + aminusB_ion_to_full - seq_.back()->getFormula() + seq_.back()->getBaselossFormula();
case AIon:
return our_form + (H_form * charge) + local_five_prime + a_ion_to_full;
case BIon:
return our_form + (H_form * charge) + local_five_prime + b_ion_to_full;
case CIon:
return our_form + (H_form * charge) + local_five_prime + c_ion_to_full;
case DIon:
return our_form + (H_form * charge) + local_five_prime + d_ion_to_full;
case WIon:
return our_form + (H_form * charge) + local_three_prime + w_ion_to_full;
case XIon:
return our_form + (H_form * charge) + local_three_prime + x_ion_to_full;
case YIon:
return our_form + (H_form * charge) + local_three_prime + y_ion_to_full;
case ZIon:
return our_form + (H_form * charge) + local_three_prime + z_ion_to_full;
default:
OPENMS_LOG_ERROR << "NASequence::getFormula: unsupported NASFragmentType" << endl;
}
return our_form;
}
void NASequence::set(size_t index, const Ribonucleotide* r)
{
seq_[index] = r;
}
bool NASequence::hasFivePrimeMod() const
{
return (five_prime_ != nullptr);
}
void NASequence::setFivePrimeMod(const RibonucleotideChainEnd* r)
{
five_prime_= r;
}
const RibonucleotideChainEnd* NASequence::getFivePrimeMod() const
{
return five_prime_;
}
bool NASequence::hasThreePrimeMod() const
{
return (three_prime_ != nullptr);
}
void NASequence::setThreePrimeMod(const RibonucleotideChainEnd* r)
{
three_prime_= r;
}
const RibonucleotideChainEnd* NASequence::getThreePrimeMod() const
{
return three_prime_;
}
double NASequence::getMonoWeight(NASFragmentType type, Int charge) const
{
return getFormula(type, charge).getMonoWeight();
}
double NASequence::getAverageWeight(NASFragmentType type, Int charge) const
{
return getFormula(type, charge).getAverageWeight();
}
size_t NASequence::size() const
{
return seq_.size();
}
NASequence NASequence::fromString(const char* s)
{
NASequence nas;
parseString_(String(s), nas);
return nas;
}
NASequence NASequence::fromString(const String& s)
{
NASequence nas;
parseString_(s, nas);
return nas;
}
string NASequence::toString() const
{
string s;
if (five_prime_)
{
const String& code = five_prime_->getCode();
if (code == "5'-p")
{
s = "p";
}
else
{
s = "[" + code + "]";
}
}
for (const auto& r : seq_)
{
const String& code = r->getCode();
if (code.size() == 1)
{
s += code;
}
else
{
s += "[" + code + "]"; // add brackets around non-standard ribos
}
}
if (three_prime_)
{
const String& code = three_prime_->getCode();
if (code == "3'-p")
{
s += "p";
}
else
{
s += "[" + code + "]";
}
}
return s;
}
void NASequence::clear()
{
seq_.clear();
three_prime_ = nullptr;
five_prime_ = nullptr;
}
void NASequence::parseString_(const String& s, NASequence& nas)
{
nas.clear();
if (s.empty()) return;
static RibonucleotideDB* rdb = RibonucleotideDB::getInstance();
String::ConstIterator str_it = s.begin();
if (*str_it == 'p') // special case for 5' phosphate
{
nas.setFivePrimeMod(rdb->getRibonucleotide("5'-p"));
++str_it;
}
String::ConstIterator stop = s.end();
if ((s.size() > 1) && (s.back() == 'p')) // special case for 3' phosphate
{
nas.setThreePrimeMod(rdb->getRibonucleotide("3'-p"));
--stop;
}
for (; str_it != stop; ++str_it)
{
// skip spaces
if (*str_it == ' ') continue;
// default case: add unmodified, standard ribonucleotide
if (*str_it != '[')
{
try
{
ConstRibonucleotidePtr r = rdb->getRibonucleotide(string(1, *str_it));
nas.seq_.push_back(r);
}
catch (Exception::ElementNotFound)
{
String msg = "Cannot convert string to nucleic acid sequence: invalid character '" + String(*str_it) + "'";
throw Exception::ParseError(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, s, msg);
}
}
else // if (*str_it == '[') // non-standard ribonucleotide
{
// parse modified ribonucleotide and add it to the sequence:
str_it = parseMod_(str_it, s, nas);
}
}
}
String::ConstIterator NASequence::parseMod_(
const String::ConstIterator str_it, const String& str, NASequence& nas)
{
static RibonucleotideDB* rdb = RibonucleotideDB::getInstance();
OPENMS_PRECONDITION(*str_it == '[', "Modification must start with '['.");
String::ConstIterator mod_start(str_it);
String::ConstIterator mod_end(++mod_start);
while ((mod_end != str.end()) && (*mod_end != ']')) ++mod_end; // advance to closing bracket
string mod(mod_start, mod_end);
if (mod_end == str.end())
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, str, "Cannot convert string to modified ribonucleotide: missing ']'");
}
ConstRibonucleotidePtr r = rdb->getRibonucleotide(mod);
// @TODO: check if position is actually 5'/3' and there's no mod already
if (r->getTermSpecificity() == Ribonucleotide::FIVE_PRIME)
{
nas.setFivePrimeMod(r);
}
else if (r->getTermSpecificity() == Ribonucleotide::THREE_PRIME)
{
nas.setThreePrimeMod(r);
}
else
{
nas.seq_.push_back(r);
}
return mod_end;
}
OPENMS_DLLAPI ostream& operator<<(ostream& os, const NASequence& seq)
{
return (os << seq.toString());
}
}
| 31.521028 | 148 | 0.632051 | avasq011 |
c89bae18739e1796abedb0132ebdd6f89f5eeea1 | 1,008 | hpp | C++ | include/soralog/impl/fallback_configurator.hpp | GeniusVentures/soralog | 53bc6eeba84ad35e018fe4e94f6a8cc74284aa44 | [
"Apache-2.0"
] | 2 | 2022-03-12T14:30:07.000Z | 2022-03-12T21:16:20.000Z | include/soralog/impl/fallback_configurator.hpp | GeniusVentures/soralog | 53bc6eeba84ad35e018fe4e94f6a8cc74284aa44 | [
"Apache-2.0"
] | 6 | 2021-03-17T13:24:01.000Z | 2022-03-09T12:52:27.000Z | include/soralog/impl/fallback_configurator.hpp | GeniusVentures/soralog | 53bc6eeba84ad35e018fe4e94f6a8cc74284aa44 | [
"Apache-2.0"
] | 4 | 2021-03-15T09:06:43.000Z | 2022-03-12T14:04:42.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef SORALOG_FALLBACKCONFIGURATOR
#define SORALOG_FALLBACKCONFIGURATOR
#include <soralog/configurator.hpp>
#include <soralog/logging_system.hpp>
namespace soralog {
/**
* @class FallbackConfigurator
* @brief Fallback configurator of Logging System. Creates just one sink (to
* console) and default group '*'. Constructor accepts detalisation level and
* flag to shitch on color in console
*/
class FallbackConfigurator : public Configurator {
public:
explicit FallbackConfigurator(Level level = Level::INFO,
bool with_color = false)
: level_(level), with_color_(with_color) {}
~FallbackConfigurator() override = default;
Result applyOn(LoggingSystem &system) const override;
private:
Level level_ = Level::INFO;
bool with_color_ = false;
};
} // namespace soralog
#endif // SORALOG_FALLBACKCONFIGURATOR
| 25.846154 | 79 | 0.703373 | GeniusVentures |
c89f022c36aed709be3b248cba420d23b9e14297 | 1,484 | hpp | C++ | Application/src/vendor/include/glm/ext/vector_uint2_precision.hpp | ankitpaudel20/opengl | 3d32f466c6f7b0d53c17d672a29800bc46a888ef | [
"MIT"
] | 2 | 2021-08-16T16:55:01.000Z | 2021-08-16T16:57:12.000Z | Application/src/vendor/include/glm/ext/vector_uint2_precision.hpp | ankitpaudel20/opengl | 3d32f466c6f7b0d53c17d672a29800bc46a888ef | [
"MIT"
] | 3 | 2021-08-10T16:32:47.000Z | 2021-08-10T16:46:36.000Z | Application/src/vendor/include/glm/ext/vector_uint2_precision.hpp | ankitpaudel20/opengl | 3d32f466c6f7b0d53c17d672a29800bc46a888ef | [
"MIT"
] | 2 | 2021-11-30T11:09:44.000Z | 2021-11-30T11:11:16.000Z | /// @ref core
/// @file glm/ext/vector_uint2_precision.hpp
#pragma once
#include "../detail/type_vec2.hpp"
namespace glm {
/// @addtogroup core_vector_precision
/// @{
/// 2 components vector of high qualifier unsigned integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<2, unsigned int, highp> highp_uvec2;
/// 2 components vector of medium qualifier unsigned integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<2, unsigned int, mediump> mediump_uvec2;
/// 2 components vector of low qualifier unsigned integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<2, unsigned int, lowp> lowp_uvec2;
/// @}
}//namespace glm
| 46.375 | 146 | 0.671159 | ankitpaudel20 |
c8a1892e312cc5045486575feb33806f6d055304 | 3,829 | hxx | C++ | main/svgio/inc/svgio/svgreader/svgdocumenthandler.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/svgio/inc/svgio/svgreader/svgdocumenthandler.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/svgio/inc/svgio/svgreader/svgdocumenthandler.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef INCLUDED_SVGIO_SVGREADER_SVGDOCUMENTHANDLER_HXX
#define INCLUDED_SVGIO_SVGREADER_SVGDOCUMENTHANDLER_HXX
#include <svgio/svgiodllapi.h>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <svgio/svgreader/svgdocument.hxx>
//////////////////////////////////////////////////////////////////////////////
// predefines
namespace svgio { namespace svgreader { class SvgCharacterNode; }}
//////////////////////////////////////////////////////////////////////////////
namespace svgio
{
namespace svgreader
{
class SvgDocHdl : public cppu::WeakImplHelper1< com::sun::star::xml::sax::XDocumentHandler >
{
private:
// the complete SVG Document
SvgDocument maDocument;
// current node for parsing
SvgNode* mpTarget;
// text collector string stack for css styles
std::vector< rtl::OUString > maCssContents;
public:
SvgDocHdl(const rtl::OUString& rAbsolutePath);
~SvgDocHdl();
// Methods XDocumentHandler
virtual void SAL_CALL startDocument( ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endDocument( ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL startElement( const ::rtl::OUString& aName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttribs ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endElement( const ::rtl::OUString& aName ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL characters( const ::rtl::OUString& aChars ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setDocumentLocator( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XLocator >& xLocator ) throw (com::sun::star::xml::sax::SAXException, com::sun::star::uno::RuntimeException);
const SvgDocument& getSvgDocument() const { return maDocument; }
};
} // end of namespace svgreader
} // end of namespace svgio
//////////////////////////////////////////////////////////////////////////////
#endif //INCLUDED_SVGIO_SVGREADER_SVGDOCUMENTHANDLER_HXX
// eof
| 50.381579 | 257 | 0.621833 | Grosskopf |
c8a1a791bd6f00ca496dc0c50a14de312c1c0ccf | 61,007 | cc | C++ | node_modules/bcrypto/src/secp256k1.cc | corollari/bcoin | 2dece4fbe10fffa369e9dd0e8263eb57ba30dcac | [
"MIT"
] | 2 | 2021-05-15T03:51:49.000Z | 2021-05-15T03:51:50.000Z | node_modules/bcrypto/src/secp256k1.cc | corollari/bcoin | 2dece4fbe10fffa369e9dd0e8263eb57ba30dcac | [
"MIT"
] | null | null | null | node_modules/bcrypto/src/secp256k1.cc | corollari/bcoin | 2dece4fbe10fffa369e9dd0e8263eb57ba30dcac | [
"MIT"
] | 1 | 2020-06-02T23:08:20.000Z | 2020-06-02T23:08:20.000Z | /*!
* Parts of this software are based on cryptocoinjs/secp256k1-node:
*
* https://github.com/cryptocoinjs/secp256k1-node
*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 secp256k1-node contributors
*
* Parts of this software are based on bn.js, elliptic, hash.js
* Copyright (c) 2014-2016 Fedor Indutny
*
* 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.
*
* Parts of this software are based on bitcoin-core/secp256k1:
*
* https://github.com/bitcoin-core/secp256k1
*
* Copyright (c) 2013 Pieter Wuille
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <node.h>
#include <nan.h>
#include <memory>
#include "secp256k1.h"
#include "secp256k1/include/secp256k1.h"
#include "secp256k1/include/secp256k1_ecdh.h"
#include "secp256k1/include/secp256k1_recovery.h"
#include "secp256k1/include/secp256k1_schnorrleg.h"
#include "secp256k1/include/secp256k1_elligator.h"
#include "secp256k1/include/secp256k1_extra.h"
#include "secp256k1/contrib/lax_der_privatekey_parsing.h"
#include "secp256k1/contrib/lax_der_parsing.h"
#define ALLOCATION_FAILURE "allocation failed"
#define RANDOMIZATION_FAILURE "randomization failed"
#define COMPRESSED_TYPE_INVALID "compressed must be a boolean"
#define EC_PRIVATE_KEY_TYPE_INVALID "private key must be a Buffer"
#define EC_PRIVATE_KEY_LENGTH_INVALID "private key length is invalid"
#define EC_PRIVATE_KEY_RANGE_INVALID "private key range is invalid"
#define EC_PRIVATE_KEY_TWEAK_ADD_FAIL \
"tweak out of range or resulting private key is invalid"
#define EC_PRIVATE_KEY_TWEAK_MUL_FAIL "tweak out of range"
#define EC_PRIVATE_KEY_EXPORT_FAIL "couldn't export private key"
#define EC_PRIVATE_KEY_IMPORT_FAIL "couldn't import private key"
#define EC_PUBLIC_KEYS_TYPE_INVALID "public keys must be an Array"
#define EC_PUBLIC_KEYS_LENGTH_INVALID \
"public keys Array must have at least 1 element"
#define EC_PUBLIC_KEY_TYPE_INVALID "public key must be a Buffer"
#define EC_PUBLIC_KEY_LENGTH_INVALID "public key length is invalid"
#define EC_PUBLIC_KEY_PARSE_FAIL \
"the public key could not be parsed or is invalid"
#define EC_PUBLIC_KEY_CREATE_FAIL "private was invalid, try again"
#define EC_PUBLIC_KEY_TWEAK_ADD_FAIL \
"tweak out of range or resulting public key is invalid"
#define EC_PUBLIC_KEY_TWEAK_MUL_FAIL "tweak out of range"
#define EC_PUBLIC_KEY_COMBINE_FAIL "the sum of the public keys is not valid"
#define EC_PUBLIC_KEY_NEGATE_FAIL "public key negation failed"
#define EC_PUBLIC_KEY_INVERT_FAIL "public key inversion failed"
#define EC_PUBLIC_KEY_EXPORT_FAIL "couldn't export public key"
#define EC_PUBLIC_KEY_IMPORT_FAIL "couldn't import public key"
#define ECDH_FAIL "scalar was invalid (zero or overflow)"
#define EC_SIGNATURE_TYPE_INVALID "signature must be a Buffer"
#define EC_SIGNATURE_LENGTH_INVALID "signature length is invalid"
#define EC_SIGNATURE_PARSE_FAIL "couldn't parse signature"
#define EC_SIGNATURE_PARSE_DER_FAIL "couldn't parse DER signature"
#define EC_SIGNATURE_SERIALIZE_DER_FAIL \
"couldn't serialize signature to DER format"
#define EC_SIGN_FAIL \
"nonce generation function failed or private key is invalid"
#define EC_RECOVER_FAIL "couldn't recover public key from signature"
#define MSG_TYPE_INVALID "message must be a Buffer"
#define MSG_LENGTH_INVALID "message length is invalid"
#define RECOVERY_ID_TYPE_INVALID "recovery must be a Number"
#define RECOVERY_ID_VALUE_INVALID "recovery value must be in [0,3]"
#define SIGN_TYPE_INVALID "sign must be a Boolean"
#define COORD_TYPE_INVALID "coordinate must be a Buffer"
#define HINT_TYPE_INVALID "hint must be a Number"
#define TWEAK_TYPE_INVALID "tweak must be a Buffer"
#define TWEAK_LENGTH_INVALID "tweak length is invalid"
#define ENTROPY_TYPE_INVALID "entropy must be a Buffer"
#define ENTROPY_LENGTH_INVALID "entropy length is invalid"
#define BATCH_TYPE_INVALID "batch must be an Array"
#define BATCH_ITEM_TYPE_INVALID "batch item must be an Array"
#define BATCH_ITEM_LENGTH_INVALID "batch item must consist of 3 members"
#define COPY_BUFFER(data, datalen) \
Nan::CopyBuffer((const char *)data, (uint32_t)datalen).ToLocalChecked()
#define UPDATE_COMPRESSED_VALUE(compressed, value, v_true, v_false) { \
if (!value->IsUndefined() && !value->IsNull()) { \
CHECK_TYPE_BOOLEAN(value, COMPRESSED_TYPE_INVALID); \
compressed = Nan::To<bool>(value).FromJust() ? v_true : v_false; \
} \
}
// TypeError
#define CHECK_TYPE_ARRAY(value, message) do { \
if (!value->IsArray()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_BOOLEAN(value, message) do { \
if (!value->IsBoolean() && !value->IsBooleanObject()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_BUFFER(value, message) do { \
if (!node::Buffer::HasInstance(value)) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_FUNCTION(value, message) do { \
if (!value->IsFunction()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_NUMBER(value, message) do { \
if (!value->IsNumber() && !value->IsNumberObject()) \
return Nan::ThrowTypeError(message); \
} while (0)
#define CHECK_TYPE_OBJECT(value, message) do { \
if (!value->IsObject()) \
return Nan::ThrowTypeError(message); \
} while (0)
// RangeError
#define CHECK_BUFFER_LENGTH(buffer, length, message) do { \
if (node::Buffer::Length(buffer) != length) \
return Nan::ThrowRangeError(message); \
} while (0)
#define CHECK_BUFFER_LENGTH2(buffer, length1, length2, message) do { \
if (node::Buffer::Length(buffer) != length1 && \
node::Buffer::Length(buffer) != length2) { \
return Nan::ThrowRangeError(message); \
} \
} while (0)
#define CHECK_BUFFER_LENGTH_GT_ZERO(buffer, message) do { \
if (node::Buffer::Length(buffer) == 0) \
return Nan::ThrowRangeError(message); \
} while (0)
#define CHECK_LENGTH_GT_ZERO(value, message) do { \
if (value->Length() == 0) \
return Nan::ThrowRangeError(message); \
} while (0)
#define CHECK_NUMBER_IN_INTERVAL(number, x, y, message) do { \
if (Nan::To<int64_t>(number).FromJust() <= x || \
Nan::To<int64_t>(number).FromJust() >= y) { \
return Nan::ThrowRangeError(message); \
} \
} while (0)
static Nan::Persistent<v8::FunctionTemplate> secp256k1_constructor;
BSecp256k1::BSecp256k1() {
ctx = NULL;
scratch = NULL;
}
BSecp256k1::~BSecp256k1() {
if (ctx != NULL) {
secp256k1_context_destroy(ctx);
ctx = NULL;
}
if (scratch != NULL) {
secp256k1_scratch_space_destroy(scratch);
scratch = NULL;
}
}
void
BSecp256k1::Init(v8::Local<v8::Object> &target) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl =
Nan::New<v8::FunctionTemplate>(BSecp256k1::New);
secp256k1_constructor.Reset(tpl);
tpl->SetClassName(Nan::New("Secp256k1").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// internal
Nan::SetPrototypeMethod(tpl, "_randomize", BSecp256k1::Randomize);
// secret key
Nan::SetPrototypeMethod(tpl, "privateKeyGenerate", BSecp256k1::PrivateKeyGenerate);
Nan::SetPrototypeMethod(tpl, "privateKeyVerify", BSecp256k1::PrivateKeyVerify);
Nan::SetPrototypeMethod(tpl, "privateKeyExport", BSecp256k1::PrivateKeyExport);
Nan::SetPrototypeMethod(tpl, "privateKeyImport", BSecp256k1::PrivateKeyImport);
Nan::SetPrototypeMethod(tpl, "privateKeyReduce", BSecp256k1::PrivateKeyReduce);
Nan::SetPrototypeMethod(tpl, "privateKeyNegate", BSecp256k1::PrivateKeyNegate);
Nan::SetPrototypeMethod(tpl, "privateKeyInvert", BSecp256k1::PrivateKeyInvert);
Nan::SetPrototypeMethod(tpl, "privateKeyTweakAdd", BSecp256k1::PrivateKeyTweakAdd);
Nan::SetPrototypeMethod(tpl, "privateKeyTweakMul", BSecp256k1::PrivateKeyTweakMul);
// public key
Nan::SetPrototypeMethod(tpl, "publicKeyCreate", BSecp256k1::PublicKeyCreate);
Nan::SetPrototypeMethod(tpl, "publicKeyConvert", BSecp256k1::PublicKeyConvert);
Nan::SetPrototypeMethod(tpl, "publicKeyFromUniform", BSecp256k1::PublicKeyFromUniform);
Nan::SetPrototypeMethod(tpl, "publicKeyToUniform", BSecp256k1::PublicKeyToUniform);
Nan::SetPrototypeMethod(tpl, "publicKeyFromHash", BSecp256k1::PublicKeyFromHash);
Nan::SetPrototypeMethod(tpl, "publicKeyToHash", BSecp256k1::PublicKeyToHash);
Nan::SetPrototypeMethod(tpl, "publicKeyVerify", BSecp256k1::PublicKeyVerify);
Nan::SetPrototypeMethod(tpl, "publicKeyExport", BSecp256k1::PublicKeyExport);
Nan::SetPrototypeMethod(tpl, "publicKeyImport", BSecp256k1::PublicKeyImport);
Nan::SetPrototypeMethod(tpl, "publicKeyTweakAdd", BSecp256k1::PublicKeyTweakAdd);
Nan::SetPrototypeMethod(tpl, "publicKeyTweakMul", BSecp256k1::PublicKeyTweakMul);
Nan::SetPrototypeMethod(tpl, "publicKeyCombine", BSecp256k1::PublicKeyCombine);
Nan::SetPrototypeMethod(tpl, "publicKeyNegate", BSecp256k1::PublicKeyNegate);
// signature
Nan::SetPrototypeMethod(tpl, "signatureNormalize", BSecp256k1::SignatureNormalize);
Nan::SetPrototypeMethod(tpl, "signatureNormalizeDER", BSecp256k1::SignatureNormalizeDER);
Nan::SetPrototypeMethod(tpl, "signatureExport", BSecp256k1::SignatureExport);
Nan::SetPrototypeMethod(tpl, "signatureImport", BSecp256k1::SignatureImport);
Nan::SetPrototypeMethod(tpl, "isLowS", BSecp256k1::IsLowS);
Nan::SetPrototypeMethod(tpl, "isLowDER", BSecp256k1::IsLowDER);
// ecdsa
Nan::SetPrototypeMethod(tpl, "sign", BSecp256k1::Sign);
Nan::SetPrototypeMethod(tpl, "signRecoverable", BSecp256k1::SignRecoverable);
Nan::SetPrototypeMethod(tpl, "signDER", BSecp256k1::SignDER);
Nan::SetPrototypeMethod(tpl, "signRecoverableDER", BSecp256k1::SignRecoverableDER);
Nan::SetPrototypeMethod(tpl, "verify", BSecp256k1::Verify);
Nan::SetPrototypeMethod(tpl, "verifyDER", BSecp256k1::VerifyDER);
Nan::SetPrototypeMethod(tpl, "recover", BSecp256k1::Recover);
Nan::SetPrototypeMethod(tpl, "recoverDER", BSecp256k1::RecoverDER);
// ecdh
Nan::SetPrototypeMethod(tpl, "derive", BSecp256k1::Derive);
// schnorr
Nan::SetPrototypeMethod(tpl, "schnorrSign", BSecp256k1::SchnorrSign);
Nan::SetPrototypeMethod(tpl, "schnorrVerify", BSecp256k1::SchnorrVerify);
Nan::SetPrototypeMethod(tpl, "schnorrVerifyBatch", BSecp256k1::SchnorrVerifyBatch);
v8::Local<v8::FunctionTemplate> ctor =
Nan::New<v8::FunctionTemplate>(secp256k1_constructor);
Nan::Set(target, Nan::New("Secp256k1").ToLocalChecked(),
Nan::GetFunction(ctor).ToLocalChecked());
}
NAN_METHOD(BSecp256k1::New) {
if (!info.IsConstructCall())
return Nan::ThrowError("Could not create Secp256k1 instance.");
secp256k1_context *ctx = secp256k1_context_create(
SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
if (ctx == NULL)
return Nan::ThrowError("Could not create Secp256k1 instance.");
BSecp256k1 *secp = new BSecp256k1();
secp->ctx = ctx;
secp->scratch = NULL;
secp->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(BSecp256k1::Randomize) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> entropy_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(entropy_buf, ENTROPY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(entropy_buf, 32, ENTROPY_LENGTH_INVALID);
const unsigned char *entropy =
(const unsigned char *)node::Buffer::Data(entropy_buf);
if (!secp256k1_context_randomize(secp->ctx, entropy))
return Nan::ThrowError(RANDOMIZATION_FAILURE);
info.GetReturnValue().Set(info.Holder());
}
NAN_METHOD(BSecp256k1::PrivateKeyGenerate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> entropy_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(entropy_buf, ENTROPY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(entropy_buf, 32, ENTROPY_LENGTH_INVALID);
const unsigned char *entropy =
(const unsigned char *)node::Buffer::Data(entropy_buf);
unsigned char out[32];
assert(secp256k1_ec_privkey_generate(secp->ctx, out, entropy));
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyVerify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
if (node::Buffer::Length(priv_buf) != 32)
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
int result = secp256k1_ec_seckey_verify(secp->ctx, priv);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::PrivateKeyExport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char out[32];
if (!secp256k1_ec_privkey_export(secp->ctx, out, priv))
return Nan::ThrowError(EC_PRIVATE_KEY_EXPORT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyImport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PRIVATE_KEY_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
unsigned char priv[32];
if (!secp256k1_ec_privkey_import(secp->ctx, priv, inp, inp_len))
return Nan::ThrowError(EC_PRIVATE_KEY_IMPORT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyReduce) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
unsigned char out[32];
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
size_t priv_len = (size_t)node::Buffer::Length(priv_buf);
if (!secp256k1_ec_privkey_reduce(secp->ctx, out, priv, priv_len))
return Nan::ThrowError(EC_PRIVATE_KEY_RANGE_INVALID);
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyNegate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
if (!secp256k1_ec_privkey_negate_safe(secp->ctx, priv))
return Nan::ThrowError(EC_PRIVATE_KEY_RANGE_INVALID);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyInvert) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
if (!secp256k1_ec_privkey_invert(secp->ctx, priv))
return Nan::ThrowError(EC_PRIVATE_KEY_RANGE_INVALID);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyTweakAdd) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
if (!secp256k1_ec_privkey_tweak_add(secp->ctx, priv, tweak))
return Nan::ThrowError(EC_PRIVATE_KEY_TWEAK_ADD_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PrivateKeyTweakMul) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
unsigned char priv[32];
memcpy(priv, node::Buffer::Data(priv_buf), 32);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
if (!secp256k1_ec_privkey_tweak_mul(secp->ctx, priv, tweak))
return Nan::ThrowError(EC_PRIVATE_KEY_TWEAK_MUL_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(priv, 32));
}
NAN_METHOD(BSecp256k1::PublicKeyCreate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> priv_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_create(secp->ctx, &pub, priv))
return Nan::ThrowError(EC_PUBLIC_KEY_CREATE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyConvert) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyFromUniform) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> data_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(data_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(data_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *data =
(const unsigned char *)node::Buffer::Data(data_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
assert(secp256k1_pubkey_from_uniform(secp->ctx, &pub, data) == 1);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyToUniform) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
v8::Local<v8::Object> hint_object = info[1].As<v8::Object>();
CHECK_TYPE_NUMBER(hint_object, HINT_TYPE_INVALID);
unsigned int hint = (unsigned int)Nan::To<uint32_t>(hint_object).FromJust();
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned char out[32];
if (!secp256k1_pubkey_to_uniform(secp->ctx, out, &pub, hint))
return Nan::ThrowError(EC_PUBLIC_KEY_INVERT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(out, 32));
}
NAN_METHOD(BSecp256k1::PublicKeyFromHash) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> data_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(data_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(data_buf, 64, TWEAK_LENGTH_INVALID);
const unsigned char *data =
(const unsigned char *)node::Buffer::Data(data_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_pubkey_from_hash(secp->ctx, &pub, data))
return Nan::ThrowError(EC_PUBLIC_KEY_COMBINE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyToHash) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
v8::Local<v8::Object> entropy_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(entropy_buf, ENTROPY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(entropy_buf, 32, ENTROPY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
const unsigned char *entropy =
(const unsigned char *)node::Buffer::Data(entropy_buf);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned char out[64];
if (!secp256k1_pubkey_to_hash(secp->ctx, out, &pub, entropy))
return Nan::ThrowError(EC_PUBLIC_KEY_INVERT_FAIL);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::PublicKeyVerify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_pubkey pub;
int result = secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::PublicKeyExport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const uint8_t *inp = (const uint8_t *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_pubkey pub;
uint8_t x[32];
uint8_t y[32];
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_export(secp->ctx, x, y, &pub))
return Nan::ThrowError(EC_PUBLIC_KEY_EXPORT_FAIL);
v8::Local<v8::Array> ret = Nan::New<v8::Array>();
Nan::Set(ret, 0, COPY_BUFFER(x, 32));
Nan::Set(ret, 1, COPY_BUFFER(y, 32));
return info.GetReturnValue().Set(ret);
}
NAN_METHOD(BSecp256k1::PublicKeyImport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
const uint8_t *x = NULL;
size_t x_len = 0;
const uint8_t *y = NULL;
size_t y_len = 0;
int sign = -1;
if (!info[0]->IsUndefined() && !info[0]->IsNull()) {
v8::Local<v8::Object> xbuf = info[0].As<v8::Object>();
if (!node::Buffer::HasInstance(xbuf))
return Nan::ThrowTypeError(COORD_TYPE_INVALID);
x = (const uint8_t *)node::Buffer::Data(xbuf);
x_len = node::Buffer::Length(xbuf);
}
if (!info[1]->IsUndefined() && !info[1]->IsNull()) {
v8::Local<v8::Object> ybuf = info[1].As<v8::Object>();
if (!node::Buffer::HasInstance(ybuf))
return Nan::ThrowTypeError(COORD_TYPE_INVALID);
y = (const uint8_t *)node::Buffer::Data(ybuf);
y_len = node::Buffer::Length(ybuf);
}
if (!info[2]->IsUndefined() && !info[2]->IsNull()) {
if (!info[2]->IsBoolean())
return Nan::ThrowTypeError(SIGN_TYPE_INVALID);
sign = (int)Nan::To<bool>(info[2]).FromJust();
}
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[3], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_import(secp->ctx, &pub, x, x_len, y, y_len, sign))
return Nan::ThrowError(EC_PUBLIC_KEY_IMPORT_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyTweakAdd) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[2], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_tweak_add(secp->ctx, &pub, tweak))
return Nan::ThrowError(EC_PUBLIC_KEY_TWEAK_ADD_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyTweakMul) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
v8::Local<v8::Object> tweak_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(tweak_buf, TWEAK_TYPE_INVALID);
CHECK_BUFFER_LENGTH(tweak_buf, 32, TWEAK_LENGTH_INVALID);
const unsigned char *tweak =
(const unsigned char *)node::Buffer::Data(tweak_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[2], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_tweak_mul(secp->ctx, &pub, tweak))
return Nan::ThrowError(EC_PUBLIC_KEY_TWEAK_MUL_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyCombine) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Array> inp_buffers = info[0].As<v8::Array>();
CHECK_TYPE_ARRAY(inp_buffers, EC_PUBLIC_KEYS_TYPE_INVALID);
CHECK_LENGTH_GT_ZERO(inp_buffers, EC_PUBLIC_KEYS_LENGTH_INVALID);
size_t len = (size_t)inp_buffers->Length();
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey **pubs =
(secp256k1_pubkey **)malloc(len * sizeof(secp256k1_pubkey *));
secp256k1_pubkey *pub_data =
(secp256k1_pubkey *)malloc(len * sizeof(secp256k1_pubkey));
#define FREE_BATCH do { \
if (pubs != NULL) free(pubs); \
if (pub_data != NULL) free(pub_data); \
} while (0)
if (pubs == NULL || pub_data == NULL) {
FREE_BATCH;
return Nan::ThrowError(ALLOCATION_FAILURE);
}
for (size_t i = 0; i < len; i++) {
v8::Local<v8::Object> pub_buf =
Nan::Get(inp_buffers, i).ToLocalChecked().As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t inp_len = node::Buffer::Length(pub_buf);
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub_data[i], inp, inp_len)) {
FREE_BATCH;
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
}
pubs[i] = &pub_data[i];
}
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_combine(secp->ctx, &pub, pubs, len)) {
FREE_BATCH;
return Nan::ThrowError(EC_PUBLIC_KEY_COMBINE_FAIL);
}
FREE_BATCH;
#undef FREE_BATCH
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::PublicKeyNegate) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(inp_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[1], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, inp, inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
if (!secp256k1_ec_pubkey_negate(secp->ctx, &pub))
return Nan::ThrowError(EC_PUBLIC_KEY_NEGATE_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignatureNormalize) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
secp256k1_ecdsa_signature sigin;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sigin, inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
secp256k1_ecdsa_signature sigout;
secp256k1_ecdsa_signature_normalize(secp->ctx, &sigout, &sigin);
unsigned char out[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, out, &sigout);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::SignatureNormalizeDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_ecdsa_signature sigin;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sigin, inp, inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
secp256k1_ecdsa_signature sigout;
secp256k1_ecdsa_signature_normalize(secp->ctx, &sigout, &sigin);
unsigned char out[72];
size_t out_len = 72;
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sigout)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignatureExport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
secp256k1_ecdsa_signature sig;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig, inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
unsigned char out[72];
size_t out_len = 72;
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sig)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignatureImport) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sig, inp, inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
unsigned char out[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, out, &sig);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::IsLowS) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
if (inp_len != 64)
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
secp256k1_ecdsa_signature sig;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig, inp))
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
int result = !secp256k1_ecdsa_signature_normalize(secp->ctx, NULL, &sig);
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::IsLowDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> inp_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(inp_buf, EC_SIGNATURE_TYPE_INVALID);
const unsigned char *inp = (const unsigned char *)node::Buffer::Data(inp_buf);
size_t inp_len = node::Buffer::Length(inp_buf);
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sig, inp, inp_len))
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(false));
int result = !secp256k1_ecdsa_signature_normalize(secp->ctx, NULL, &sig);
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::Sign) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign(secp->ctx, &sig, msg32, priv, noncefn, NULL))
return Nan::ThrowError(EC_SIGN_FAIL);
unsigned char out[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, out, &sig);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::SignRecoverable) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_recoverable_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign_recoverable(secp->ctx, &sig, msg32,
priv, noncefn, NULL)) {
return Nan::ThrowError(EC_SIGN_FAIL);
}
int recid;
unsigned char out[64];
secp256k1_ecdsa_recoverable_signature_serialize_compact(secp->ctx, out,
&recid, &sig);
v8::Local<v8::Array> ret = Nan::New<v8::Array>();
Nan::Set(ret, 0, COPY_BUFFER(out, 64));
Nan::Set(ret, 1, Nan::New<v8::Number>(recid));
info.GetReturnValue().Set(ret);
}
NAN_METHOD(BSecp256k1::SignDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign(secp->ctx, &sig, msg32, priv, noncefn, NULL))
return Nan::ThrowError(EC_SIGN_FAIL);
unsigned char out[72];
size_t out_len = 72;
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sig)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SignRecoverableDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
unsigned char msg32[32];
secp256k1_nonce_function noncefn = secp256k1_nonce_function_rfc6979;
secp256k1_ecdsa_recoverable_signature sig;
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
if (!secp256k1_ecdsa_sign_recoverable(secp->ctx, &sig, msg32,
priv, noncefn, NULL)) {
return Nan::ThrowError(EC_SIGN_FAIL);
}
int recid;
unsigned char out[72];
size_t out_len = 72;
secp256k1_ecdsa_recoverable_signature_serialize_compact(secp->ctx, out,
&recid, &sig);
secp256k1_ecdsa_signature sig_;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig_, out))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
if (!secp256k1_ecdsa_signature_serialize_der(secp->ctx, out,
&out_len, &sig_)) {
return Nan::ThrowError(EC_SIGNATURE_SERIALIZE_DER_FAIL);
}
v8::Local<v8::Array> ret = Nan::New<v8::Array>();
Nan::Set(ret, 0, COPY_BUFFER(out, out_len));
Nan::Set(ret, 1, Nan::New<v8::Number>(recid));
info.GetReturnValue().Set(ret);
}
NAN_METHOD(BSecp256k1::Verify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(sig_inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
v8::Local<v8::Object> pub_buf = info[2].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
secp256k1_ecdsa_signature sig;
if (!secp256k1_ecdsa_signature_parse_compact(secp->ctx, &sig, sig_inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
secp256k1_ecdsa_signature_normalize(secp->ctx, &sig, &sig);
int result = secp256k1_ecdsa_verify(secp->ctx, &sig, msg32, &pub);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::VerifyDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(sig_inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
size_t sig_inp_len = node::Buffer::Length(sig_inp_buf);
v8::Local<v8::Object> pub_buf = info[2].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &sig, sig_inp, sig_inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
secp256k1_ecdsa_signature_normalize(secp->ctx, &sig, &sig);
int result = secp256k1_ecdsa_verify(secp->ctx, &sig, msg32, &pub);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::Recover) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(sig_inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
v8::Local<v8::Object> recid_object = info[2].As<v8::Object>();
CHECK_TYPE_NUMBER(recid_object, RECOVERY_ID_TYPE_INVALID);
CHECK_NUMBER_IN_INTERVAL(recid_object, -1, 4, RECOVERY_ID_VALUE_INVALID);
int recid = (int)Nan::To<int64_t>(recid_object).FromJust();
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[3], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_ecdsa_recoverable_signature sig;
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp->ctx,
&sig,
sig_inp,
recid)) {
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
}
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ecdsa_recover(secp->ctx, &pub, &sig, msg32))
return Nan::ThrowError(EC_RECOVER_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len,
&pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::RecoverDER) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg = (const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH_GT_ZERO(sig_inp_buf, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
size_t sig_inp_len = node::Buffer::Length(sig_inp_buf);
v8::Local<v8::Object> recid_object = info[2].As<v8::Object>();
CHECK_TYPE_NUMBER(recid_object, RECOVERY_ID_TYPE_INVALID);
CHECK_NUMBER_IN_INTERVAL(recid_object, -1, 4, RECOVERY_ID_VALUE_INVALID);
int recid = (int)Nan::To<int64_t>(recid_object).FromJust();
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[3], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
secp256k1_ecdsa_signature orig;
if (!ecdsa_signature_parse_der_lax(secp->ctx, &orig, sig_inp, sig_inp_len))
return Nan::ThrowError(EC_SIGNATURE_PARSE_DER_FAIL);
unsigned char compact[64];
secp256k1_ecdsa_signature_serialize_compact(secp->ctx, compact, &orig);
secp256k1_ecdsa_recoverable_signature sig;
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp->ctx,
&sig,
compact,
recid)) {
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
}
unsigned char msg32[32];
secp256k1_ecdsa_reduce(secp->ctx, msg32, msg, msg_len);
secp256k1_pubkey pub;
if (!secp256k1_ecdsa_recover(secp->ctx, &pub, &sig, msg32))
return Nan::ThrowError(EC_RECOVER_FAIL);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ec_pubkey_serialize(secp->ctx, out, &out_len, &pub, flags);
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
static int
ecdh_hash_function_raw(unsigned char *out,
const unsigned char *x,
const unsigned char *y,
void *data) {
unsigned int flags = *((unsigned int *)data);
if (flags == SECP256K1_EC_COMPRESSED) {
out[0] = 0x02 | (y[31] & 1);
memcpy(out + 1, x, 32);
} else {
out[0] = 0x04;
memcpy(out + 1, x, 32);
memcpy(out + 33, y, 32);
}
return 1;
}
NAN_METHOD(BSecp256k1::Derive) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> pub_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
unsigned int flags = SECP256K1_EC_COMPRESSED;
UPDATE_COMPRESSED_VALUE(flags, info[2], SECP256K1_EC_COMPRESSED,
SECP256K1_EC_UNCOMPRESSED);
unsigned char out[65];
size_t out_len = 65;
secp256k1_ecdh_hash_function hashfp = ecdh_hash_function_raw;
if (!secp256k1_ecdh(secp->ctx, out, &pub, priv, hashfp, &flags))
return Nan::ThrowError(ECDH_FAIL);
if (flags == SECP256K1_EC_COMPRESSED)
out_len = 33;
info.GetReturnValue().Set(COPY_BUFFER(out, out_len));
}
NAN_METHOD(BSecp256k1::SchnorrSign) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg =
(const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> priv_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(priv_buf, EC_PRIVATE_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH(priv_buf, 32, EC_PRIVATE_KEY_LENGTH_INVALID);
const unsigned char *priv =
(const unsigned char *)node::Buffer::Data(priv_buf);
secp256k1_schnorrleg sig;
if (!secp256k1_schnorrleg_sign(secp->ctx, &sig, msg, msg_len, priv))
return Nan::ThrowError(EC_SIGN_FAIL);
unsigned char out[64];
secp256k1_schnorrleg_serialize(secp->ctx, out, &sig);
info.GetReturnValue().Set(COPY_BUFFER(out, 64));
}
NAN_METHOD(BSecp256k1::SchnorrVerify) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
v8::Local<v8::Object> msg_buf = info[0].As<v8::Object>();
CHECK_TYPE_BUFFER(msg_buf, MSG_TYPE_INVALID);
const unsigned char *msg =
(const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
v8::Local<v8::Object> sig_inp_buf = info[1].As<v8::Object>();
CHECK_TYPE_BUFFER(sig_inp_buf, EC_SIGNATURE_TYPE_INVALID);
CHECK_BUFFER_LENGTH(sig_inp_buf, 64, EC_SIGNATURE_LENGTH_INVALID);
const unsigned char *sig_inp =
(const unsigned char *)node::Buffer::Data(sig_inp_buf);
v8::Local<v8::Object> pub_buf = info[2].As<v8::Object>();
CHECK_TYPE_BUFFER(pub_buf, EC_PUBLIC_KEY_TYPE_INVALID);
CHECK_BUFFER_LENGTH2(pub_buf, 33, 65, EC_PUBLIC_KEY_LENGTH_INVALID);
const unsigned char *pub_inp =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_inp_len = node::Buffer::Length(pub_buf);
secp256k1_schnorrleg sig;
if (!secp256k1_schnorrleg_parse(secp->ctx, &sig, sig_inp))
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
secp256k1_pubkey pub;
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub, pub_inp, pub_inp_len))
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
int result = secp256k1_schnorrleg_verify(secp->ctx, &sig, msg, msg_len, &pub);
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
NAN_METHOD(BSecp256k1::SchnorrVerifyBatch) {
BSecp256k1 *secp = ObjectWrap::Unwrap<BSecp256k1>(info.Holder());
if (!info[0]->IsArray())
return Nan::ThrowTypeError(BATCH_TYPE_INVALID);
v8::Local<v8::Array> batch = info[0].As<v8::Array>();
size_t len = (size_t)batch->Length();
if (len == 0)
return info.GetReturnValue().Set(Nan::New<v8::Boolean>(true));
const unsigned char **msgs =
(const unsigned char **)malloc(len * sizeof(unsigned char *));
size_t *msg_lens = (size_t *)malloc(len * sizeof(size_t));
secp256k1_schnorrleg **sigs =
(secp256k1_schnorrleg **)malloc(len * sizeof(secp256k1_schnorrleg *));
secp256k1_pubkey **pubs =
(secp256k1_pubkey **)malloc(len * sizeof(secp256k1_pubkey *));
secp256k1_schnorrleg *sig_data =
(secp256k1_schnorrleg *)malloc(len * sizeof(secp256k1_schnorrleg));
secp256k1_pubkey *pub_data =
(secp256k1_pubkey *)malloc(len * sizeof(secp256k1_pubkey));
#define FREE_BATCH do { \
if (msgs != NULL) free(msgs); \
if (msg_lens != NULL) free(msg_lens); \
if (sigs != NULL) free(sigs); \
if (pubs != NULL) free(pubs); \
if (sig_data != NULL) free(sig_data); \
if (pub_data != NULL) free(pub_data); \
} while (0)
if (msgs == NULL || msg_lens == NULL || sigs == NULL
|| pubs == NULL || sig_data == NULL || pub_data == NULL) {
FREE_BATCH;
return Nan::ThrowError(ALLOCATION_FAILURE);
}
for (size_t i = 0; i < len; i++) {
v8::Local<v8::Value> val = Nan::Get(batch, i).ToLocalChecked();
if (!val->IsArray()) {
FREE_BATCH;
return Nan::ThrowTypeError(BATCH_ITEM_TYPE_INVALID);
}
v8::Local<v8::Array> item = val.As<v8::Array>();
if (item->Length() != 3) {
FREE_BATCH;
return Nan::ThrowTypeError(BATCH_ITEM_LENGTH_INVALID);
}
v8::Local<v8::Object> msg_buf = Nan::Get(item, 0).ToLocalChecked()
.As<v8::Object>();
v8::Local<v8::Object> sig_buf = Nan::Get(item, 1).ToLocalChecked()
.As<v8::Object>();
v8::Local<v8::Object> pub_buf = Nan::Get(item, 2).ToLocalChecked()
.As<v8::Object>();
if (!node::Buffer::HasInstance(msg_buf)) {
FREE_BATCH;
return Nan::ThrowTypeError(MSG_TYPE_INVALID);
}
if (!node::Buffer::HasInstance(sig_buf)) {
FREE_BATCH;
return Nan::ThrowTypeError(EC_SIGNATURE_TYPE_INVALID);
}
if (!node::Buffer::HasInstance(pub_buf)) {
FREE_BATCH;
return Nan::ThrowTypeError(EC_PUBLIC_KEY_TYPE_INVALID);
}
const unsigned char *msg =
(const unsigned char *)node::Buffer::Data(msg_buf);
size_t msg_len = node::Buffer::Length(msg_buf);
const unsigned char *sig =
(const unsigned char *)node::Buffer::Data(sig_buf);
size_t sig_len = node::Buffer::Length(sig_buf);
const unsigned char *pub =
(const unsigned char *)node::Buffer::Data(pub_buf);
size_t pub_len = node::Buffer::Length(pub_buf);
if (sig_len != 64) {
FREE_BATCH;
return Nan::ThrowRangeError(EC_SIGNATURE_LENGTH_INVALID);
}
if (pub_len != 33 && pub_len != 65) {
FREE_BATCH;
return Nan::ThrowRangeError(EC_PUBLIC_KEY_LENGTH_INVALID);
}
if (!secp256k1_schnorrleg_parse(secp->ctx, &sig_data[i], sig)) {
FREE_BATCH;
return Nan::ThrowError(EC_SIGNATURE_PARSE_FAIL);
}
if (!secp256k1_ec_pubkey_parse(secp->ctx, &pub_data[i], pub, pub_len)) {
FREE_BATCH;
return Nan::ThrowError(EC_PUBLIC_KEY_PARSE_FAIL);
}
msgs[i] = msg;
msg_lens[i] = msg_len;
sigs[i] = &sig_data[i];
pubs[i] = &pub_data[i];
}
// Lazy allocation for scratch space. See:
// https://github.com/ElementsProject/secp256k1-zkp/issues/69
// https://github.com/bitcoin-core/secp256k1/pull/638
if (secp->scratch == NULL) {
secp256k1_scratch_space *scratch =
secp256k1_scratch_space_create(secp->ctx, 1024 * 1024);
if (scratch == NULL) {
FREE_BATCH;
return Nan::ThrowError(ALLOCATION_FAILURE);
}
secp->scratch = scratch;
}
int result = secp256k1_schnorrleg_verify_batch(secp->ctx, secp->scratch,
sigs, msgs, msg_lens, pubs,
len);
FREE_BATCH;
#undef FREE_BATCH
info.GetReturnValue().Set(Nan::New<v8::Boolean>(result));
}
| 35.63493 | 91 | 0.698838 | corollari |
c8a212109e888485461402adfa353d639624e2af | 10,044 | cpp | C++ | test/rocprim/test_hip_device_merge_sort.cpp | arsenm/rocPRIM | 02d6006a7951c53ecfd245200d58809d3eee0b48 | [
"MIT"
] | null | null | null | test/rocprim/test_hip_device_merge_sort.cpp | arsenm/rocPRIM | 02d6006a7951c53ecfd245200d58809d3eee0b48 | [
"MIT"
] | null | null | null | test/rocprim/test_hip_device_merge_sort.cpp | arsenm/rocPRIM | 02d6006a7951c53ecfd245200d58809d3eee0b48 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <iostream>
#include <vector>
#include <algorithm>
// Google Test
#include <gtest/gtest.h>
// HIP API
#include <hip/hip_runtime.h>
#include <hip/hip_hcc.h>
// rocPRIM API
#include <rocprim/rocprim.hpp>
#include "test_utils.hpp"
#define HIP_CHECK(error) \
ASSERT_EQ(static_cast<hipError_t>(error),hipSuccess)
namespace rp = rocprim;
// Params for tests
template<
class KeyType,
class ValueType = KeyType
>
struct DeviceSortParams
{
using key_type = KeyType;
using value_type = ValueType;
};
// ---------------------------------------------------------
// Test for reduce ops taking single input value
// ---------------------------------------------------------
template<class Params>
class RocprimDeviceSortTests : public ::testing::Test
{
public:
using key_type = typename Params::key_type;
using value_type = typename Params::value_type;
const bool debug_synchronous = false;
};
typedef ::testing::Types<
DeviceSortParams<int>,
DeviceSortParams<test_utils::custom_test_type<int>>,
DeviceSortParams<unsigned long>,
DeviceSortParams<float, int>,
DeviceSortParams<int, float>,
DeviceSortParams<int, test_utils::custom_test_type<float>>
> RocprimDeviceSortTestsParams;
std::vector<size_t> get_sizes()
{
std::vector<size_t> sizes = {
1, 10, 53, 211,
1024, 2048, 5096,
34567, (1 << 17) - 1220
};
const std::vector<size_t> random_sizes = test_utils::get_random_data<size_t>(2, 1, 16384);
sizes.insert(sizes.end(), random_sizes.begin(), random_sizes.end());
std::sort(sizes.begin(), sizes.end());
return sizes;
}
TYPED_TEST_CASE(RocprimDeviceSortTests, RocprimDeviceSortTestsParams);
TYPED_TEST(RocprimDeviceSortTests, SortKey)
{
using key_type = typename TestFixture::key_type;
const bool debug_synchronous = TestFixture::debug_synchronous;
const std::vector<size_t> sizes = get_sizes();
for(auto size : sizes)
{
hipStream_t stream = 0; // default
SCOPED_TRACE(testing::Message() << "with size = " << size);
// Generate data
std::vector<key_type> input = test_utils::get_random_data<key_type>(size, 0, size);
std::vector<key_type> output(size, 0);
key_type * d_input;
key_type * d_output;
HIP_CHECK(hipMalloc(&d_input, input.size() * sizeof(key_type)));
HIP_CHECK(hipMalloc(&d_output, output.size() * sizeof(key_type)));
HIP_CHECK(
hipMemcpy(
d_input, input.data(),
input.size() * sizeof(key_type),
hipMemcpyHostToDevice
)
);
HIP_CHECK(hipDeviceSynchronize());
// Calculate expected results on host
std::vector<key_type> expected(input);
std::sort(
expected.begin(),
expected.end()
);
// compare function
::rocprim::less<key_type> lesser_op;
// temp storage
size_t temp_storage_size_bytes;
void * d_temp_storage = nullptr;
// Get size of d_temp_storage
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_input, d_output, input.size(),
lesser_op, stream, debug_synchronous
)
);
// temp_storage_size_bytes must be >0
ASSERT_GT(temp_storage_size_bytes, 0);
// allocate temporary storage
HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes));
HIP_CHECK(hipDeviceSynchronize());
// Run
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_input, d_output, input.size(),
lesser_op, stream, debug_synchronous
)
);
HIP_CHECK(hipPeekAtLastError());
HIP_CHECK(hipDeviceSynchronize());
// Copy output to host
HIP_CHECK(
hipMemcpy(
output.data(), d_output,
output.size() * sizeof(key_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
// Check if output values are as expected
for(size_t i = 0; i < output.size(); i++)
{
ASSERT_NO_FATAL_FAILURE(test_utils::assert_near(output[i], expected[i], 0.01f));
}
hipFree(d_input);
hipFree(d_output);
hipFree(d_temp_storage);
}
}
TYPED_TEST(RocprimDeviceSortTests, SortKeyValue)
{
using key_type = typename TestFixture::key_type;
using value_type = typename TestFixture::value_type;
const bool debug_synchronous = TestFixture::debug_synchronous;
const std::vector<size_t> sizes = get_sizes();
for(auto size : sizes)
{
hipStream_t stream = 0; // default
SCOPED_TRACE(testing::Message() << "with size = " << size);
// Generate data
std::vector<key_type> keys_input(size);
std::iota(keys_input.begin(), keys_input.end(), 0);
std::shuffle(
keys_input.begin(),
keys_input.end(),
std::mt19937{std::random_device{}()}
);
std::vector<value_type> values_input = test_utils::get_random_data<value_type>(size, -1000, 1000);
std::vector<key_type> keys_output(size, key_type(0));
std::vector<value_type> values_output(size, value_type(0));
key_type * d_keys_input;
key_type * d_keys_output;
HIP_CHECK(hipMalloc(&d_keys_input, keys_input.size() * sizeof(key_type)));
HIP_CHECK(hipMalloc(&d_keys_output, keys_output.size() * sizeof(key_type)));
HIP_CHECK(
hipMemcpy(
d_keys_input, keys_input.data(),
keys_input.size() * sizeof(key_type),
hipMemcpyHostToDevice
)
);
HIP_CHECK(hipDeviceSynchronize());
value_type * d_values_input;
value_type * d_values_output;
HIP_CHECK(hipMalloc(&d_values_input, values_input.size() * sizeof(value_type)));
HIP_CHECK(hipMalloc(&d_values_output, values_output.size() * sizeof(value_type)));
HIP_CHECK(
hipMemcpy(
d_values_input, values_input.data(),
values_input.size() * sizeof(value_type),
hipMemcpyHostToDevice
)
);
HIP_CHECK(hipDeviceSynchronize());
// Calculate expected results on host
using key_value = std::pair<key_type, value_type>;
std::vector<key_value> expected(size);
for(size_t i = 0; i < size; i++)
{
expected[i] = key_value(keys_input[i], values_input[i]);
}
std::sort(
expected.begin(),
expected.end()
);
// compare function
::rocprim::less<key_type> lesser_op;
// temp storage
size_t temp_storage_size_bytes;
void * d_temp_storage = nullptr;
// Get size of d_temp_storage
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_keys_input, d_keys_output,
d_values_input, d_values_output, keys_input.size(),
lesser_op, stream, debug_synchronous
)
);
// temp_storage_size_bytes must be >0
ASSERT_GT(temp_storage_size_bytes, 0);
// allocate temporary storage
HIP_CHECK(hipMalloc(&d_temp_storage, temp_storage_size_bytes));
HIP_CHECK(hipDeviceSynchronize());
// Run
HIP_CHECK(
rocprim::merge_sort(
d_temp_storage, temp_storage_size_bytes,
d_keys_input, d_keys_output,
d_values_input, d_values_output, keys_input.size(),
lesser_op, stream, debug_synchronous
)
);
HIP_CHECK(hipPeekAtLastError());
HIP_CHECK(hipDeviceSynchronize());
// Copy output to host
HIP_CHECK(
hipMemcpy(
keys_output.data(), d_keys_output,
keys_output.size() * sizeof(key_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(
hipMemcpy(
values_output.data(), d_values_output,
values_output.size() * sizeof(value_type),
hipMemcpyDeviceToHost
)
);
HIP_CHECK(hipDeviceSynchronize());
// Check if output values are as expected
for(size_t i = 0; i < keys_output.size(); i++)
{
ASSERT_EQ(keys_output[i], expected[i].first);
ASSERT_EQ(values_output[i], expected[i].second);
}
hipFree(d_keys_input);
hipFree(d_keys_output);
hipFree(d_values_input);
hipFree(d_values_output);
hipFree(d_temp_storage);
}
}
| 32.504854 | 106 | 0.610812 | arsenm |
c8a4d6760a643413706f15df437e8b4ffd378f0f | 4,568 | cpp | C++ | qt_host_installer/downloadprogress.cpp | CoderBotOrg/installer | 21ceda0b77ee36d1ca70182790532c544087f357 | [
"Libpng"
] | 1 | 2018-01-11T15:09:37.000Z | 2018-01-11T15:09:37.000Z | qt_host_installer/downloadprogress.cpp | CoderBotOrg/installer | 21ceda0b77ee36d1ca70182790532c544087f357 | [
"Libpng"
] | null | null | null | qt_host_installer/downloadprogress.cpp | CoderBotOrg/installer | 21ceda0b77ee36d1ca70182790532c544087f357 | [
"Libpng"
] | null | null | null | /*
* (c) 2014-2015 Sam Nazarko
* email@samnazarko.co.uk
*/
#include "downloadprogress.h"
#include "ui_downloadprogress.h"
#include <QFileInfo>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QString>
#include <QStringList>
#include <QUrl>
#include <QFile>
#include <QDir>
#include <QMessageBox>
#include "utils.h"
#ifdef Q_OS_LINUX
#include <unistd.h>
#endif
/* With thanks to http://qt-project.org/doc/qt-4.8/network-downloadmanager-downloadmanager-cpp.html */
DownloadProgress::DownloadProgress(QWidget *parent) :
QWidget(parent),
ui(new Ui::DownloadProgress)
{
ui->setupUi(this);
}
void DownloadProgress::download(QUrl URL, bool isOnline)
{
QString filelocation(URL.toString());
if (isOnline == false)
{
/* sanitize local filename */
#if defined(Q_OS_MAC) || defined(Q_OS_LINUX)
filelocation.replace("file://","");
#endif
/* Emit and bail! */
emit downloadCompleted(filelocation);
return;
}
utils::writeLog("Downloading " + filelocation);
QStringList urlSeg = filelocation.split("/");
fileName = urlSeg.at((urlSeg.count() - 1));
/* Do we have the file or an uncompressed version? */
bool uncompressed = QFile(QDir::homePath() + "/" + fileName).exists();
bool decompressed = QFile(QDir::homePath() + "/" + QString(fileName).remove(".gz")).exists();
if (uncompressed)
{
if (! utils::promptYesNo(tr("Image found"), tr("Do you want to re-download this image?")))
{
if(decompressed) {
if (! utils::promptYesNo(tr("Image found"), tr("Do you want to extract again?")))
{
emit downloadCompleted(QDir::homePath() + "/" + QString(fileName).remove(".gz"));
return;
}
}
emit downloadCompleted(QDir::homePath() + "/" + fileName);
return;
}
}
else if (decompressed) {
if (! utils::promptYesNo(tr("Uncompressed Image found"), tr("Do you want to re-download this image?")))
{
emit downloadCompleted(QDir::homePath() + "/" + QString(fileName).remove(".gz"));
return;
}
}
fileName = QDir::homePath() + "/" + fileName;
output.setFileName(fileName);
if (!output.open(QIODevice::WriteOnly))
{
utils::writeLog("Can't open file for writing -- is it open by another process?");
failDownload(false);
}
else
{
#ifdef Q_OS_LINUX
// Set the owner and group the same as the home path
QFileInfo info(QDir::homePath());
fchown(output.handle(),info.ownerId(),info.groupId());
#endif
QNetworkRequest request(URL);
currentDownload = manager.get(request);
connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),SLOT(downloadProgress(qint64,qint64)));
connect(currentDownload, SIGNAL(finished()), SLOT(downloadFinished()));
connect(currentDownload, SIGNAL(readyRead()), SLOT(downloadReadyRead()));
downloadTime.start();
}
}
void DownloadProgress::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
/* Download speed */
double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
QString unit;
if (speed < 1024) {
unit = "bytes/sec";
} else if (speed < 1024*1024) {
speed /= 1024;
unit = "kB/s";
} else {
speed /= 1024*1024;
unit = "MB/s";
}
ui->downloadDetailsLabel->setText(QString::fromLatin1("%1 %2").arg(speed, 3, 'f', 1).arg(unit));
/* Update progress */
ui->downloadProgressBar->setMaximum(bytesTotal);
ui->downloadProgressBar->setValue(bytesReceived);
}
void DownloadProgress::downloadFinished()
{
output.close();
if (currentDownload->error()) {
utils::writeLog("Error occured downloading file:");
utils::writeLog(currentDownload->errorString());
failDownload(true);
} else {
utils::writeLog("Download successful");
emit downloadCompleted(fileName);
}
}
void DownloadProgress::downloadReadyRead() { output.write(currentDownload->readAll()); }
void DownloadProgress::failDownload(bool wasNetwork)
{
ui->downloadProgressBar->setValue(0);
if (wasNetwork)
ui->downloadDetailsLabel->setText(tr("Download failed! Please check your network connection"));
else
ui->downloadDetailsLabel->setText(tr("Download failed! Could not write to disk"));
}
DownloadProgress::~DownloadProgress()
{
delete ui;
}
| 31.07483 | 112 | 0.624124 | CoderBotOrg |
c8a5ba2688cab8c1f172ca2ff375164ecc4785df | 7,914 | cpp | C++ | TAO/CIAO/connectors/dds4ccm/tests/Updater/Receiver/Updater_Receiver_exec.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/CIAO/connectors/dds4ccm/tests/Updater/Receiver/Updater_Receiver_exec.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/CIAO/connectors/dds4ccm/tests/Updater/Receiver/Updater_Receiver_exec.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
// $Id: Updater_Receiver_exec.cpp 95859 2012-06-11 12:40:54Z johnnyw $
/**
* Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.3
* TAO and the TAO IDL Compiler have been developed by:
* Center for Distributed Object Computing
* Washington University
* St. Louis, MO
* USA
* http://www.cs.wustl.edu/~schmidt/doc-center.html
* and
* Distributed Object Computing Laboratory
* University of California at Irvine
* Irvine, CA
* USA
* and
* Institute for Software Integrated Systems
* Vanderbilt University
* Nashville, TN
* USA
* http://www.isis.vanderbilt.edu/
*
* Information about TAO is available at:
* http://www.cs.wustl.edu/~schmidt/TAO.html
**/
#include "Updater_Receiver_exec.h"
#include "dds4ccm/impl/dds4ccm_conf.h"
namespace CIAO_Updater_Receiver_Impl
{
/**
* Facet Executor Implementation Class: info_out_data_listener_exec_i
*/
info_out_data_listener_exec_i::info_out_data_listener_exec_i (
::Updater::CCM_Receiver_Context_ptr ctx,
ACE_Thread_ID &thread_id)
: ciao_context_ (
::Updater::CCM_Receiver_Context::_duplicate (ctx))
, thread_id_ (thread_id)
{
}
info_out_data_listener_exec_i::~info_out_data_listener_exec_i (void)
{
}
// Operations from ::Updater::UpdaterConnector::Listener
void
info_out_data_listener_exec_i::on_one_data (const ::TestTopic & datum,
const ::CCM_DDS::ReadInfo & info)
{
ACE_Thread_ID t_id;
this->thread_id_ = t_id;
ACE_DEBUG ((LM_DEBUG, "ListenOneByOneTest_Listener_exec_i::on_one_data: "
"key <%C> - iteration <%d>\n",
datum.key.in (),
datum.x));
if (::DDS::HANDLE_NIL == info.instance_handle)
{
ACE_ERROR ((LM_ERROR, "ERROR: ListenOneByOneTest_Listener_exec_i::on_one_data: "
"instance handle seems to be invalid "
"key <%C> - iteration <%d>\n",
datum.key.in (),
datum.x));
}
if (info.source_timestamp.sec == 0 &&
info.source_timestamp.nanosec == 0)
{
ACE_ERROR ((LM_ERROR, "ERROR: ListenOneByOneTest_Listener_exec_i::on_one_data: "
"source timestamp seems to be invalid (nil) "
"key <%C> - iteration <%d>\n",
datum.key.in (),
datum.x));
}
}
void
info_out_data_listener_exec_i::on_many_data (const ::TestTopicSeq & /* data */,
const ::CCM_DDS::ReadInfoSeq & /* infos */)
{
/* Your code here. */
}
/**
* Facet Executor Implementation Class: info_out_status_exec_i
*/
info_out_status_exec_i::info_out_status_exec_i (
::Updater::CCM_Receiver_Context_ptr ctx)
: ciao_context_ (
::Updater::CCM_Receiver_Context::_duplicate (ctx))
{
}
info_out_status_exec_i::~info_out_status_exec_i (void)
{
}
// Operations from ::CCM_DDS::PortStatusListener
void
info_out_status_exec_i::on_requested_deadline_missed (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::RequestedDeadlineMissedStatus & /* status */)
{
/* Your code here. */
}
void
info_out_status_exec_i::on_sample_lost (::DDS::DataReader_ptr /* the_reader */,
const ::DDS::SampleLostStatus & /* status */)
{
/* Your code here. */
}
/**
* Component Executor Implementation Class: Receiver_exec_i
*/
Receiver_exec_i::Receiver_exec_i (void)
: thread_id_listener_ (0, 0)
{
}
Receiver_exec_i::~Receiver_exec_i (void)
{
}
// Supported operations and attributes.
// Component attributes and port operations.
::Updater::UpdaterConnector::CCM_Listener_ptr
Receiver_exec_i::get_info_out_data_listener (void)
{
if ( ::CORBA::is_nil (this->ciao_info_out_data_listener_.in ()))
{
info_out_data_listener_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
info_out_data_listener_exec_i (
this->ciao_context_.in (),
this->thread_id_listener_),
::Updater::UpdaterConnector::CCM_Listener::_nil ());
this->ciao_info_out_data_listener_ = tmp;
}
return
::Updater::UpdaterConnector::CCM_Listener::_duplicate (
this->ciao_info_out_data_listener_.in ());
}
::CCM_DDS::CCM_PortStatusListener_ptr
Receiver_exec_i::get_info_out_status (void)
{
if ( ::CORBA::is_nil (this->ciao_info_out_status_.in ()))
{
info_out_status_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
info_out_status_exec_i (
this->ciao_context_.in ()),
::CCM_DDS::CCM_PortStatusListener::_nil ());
this->ciao_info_out_status_ = tmp;
}
return
::CCM_DDS::CCM_PortStatusListener::_duplicate (
this->ciao_info_out_status_.in ());
}
// Operations from Components::SessionComponent.
void
Receiver_exec_i::set_session_context (
::Components::SessionContext_ptr ctx)
{
this->ciao_context_ =
::Updater::CCM_Receiver_Context::_narrow (ctx);
if ( ::CORBA::is_nil (this->ciao_context_.in ()))
{
throw ::CORBA::INTERNAL ();
}
}
void
Receiver_exec_i::configuration_complete (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_activate (void)
{
::CCM_DDS::DataListenerControl_var dlc =
this->ciao_context_->get_connection_info_out_data_control ();
dlc->mode (::CCM_DDS::ONE_BY_ONE);
}
void
Receiver_exec_i::ccm_passivate (void)
{
/* Your code here. */
}
void
Receiver_exec_i::ccm_remove (void)
{
char ccm_buf [65];
ACE_Thread_ID ccm_thread_id;
ccm_thread_id.to_string (ccm_buf);
char list_buf [65];
this->thread_id_listener_.to_string(list_buf);
if (this->thread_id_listener_.id() == 0)
{
ACE_ERROR ((LM_ERROR, "ERROR: "
"Thread ID for ReaderListener not set!\n"));
}
#if (CIAO_DDS4CCM_CONTEXT_SWITCH == 1)
else if (this->thread_id_listener_ == ccm_thread_id)
{
ACE_DEBUG ((LM_DEBUG, "ONE_BY_ONE: "
"Thread switch for ReaderListener seems OK. "
"(DDS uses the CCM thread for its callback) "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
else
{
ACE_ERROR ((LM_ERROR, "ERROR: ONE_BY_ONE: "
"Thread switch for ReaderListener "
"doesn't seem to work! "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
#else
else if (this->thread_id_listener_ == ccm_thread_id)
{
ACE_ERROR ((LM_ERROR, "ERROR: ONE_BY_ONE: ReaderListener: "
"DDS seems to use a CCM thread for its callback: "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
else
{
ACE_DEBUG ((LM_DEBUG, "ONE_BY_ONE: ReaderListener: "
"DDS seems to use its own thread for its callback: "
"listener <%C> - component <%C>\n",
list_buf,
ccm_buf));
}
#endif
}
extern "C" RECEIVER_EXEC_Export ::Components::EnterpriseComponent_ptr
create_Updater_Receiver_Impl (void)
{
::Components::EnterpriseComponent_ptr retval =
::Components::EnterpriseComponent::_nil ();
ACE_NEW_NORETURN (
retval,
Receiver_exec_i);
return retval;
}
}
| 28.163701 | 95 | 0.579732 | cflowe |
c8a7598d88461602144d32c434825b47581394da | 29,832 | hpp | C++ | far/config.hpp | data-man/FarAS | 8bd1725cdd2aaee90081ae35c492738e0be470a3 | [
"BSD-3-Clause"
] | 1 | 2020-12-05T17:33:05.000Z | 2020-12-05T17:33:05.000Z | far/config.hpp | data-man/FarAS | 8bd1725cdd2aaee90081ae35c492738e0be470a3 | [
"BSD-3-Clause"
] | 1 | 2021-02-23T13:01:10.000Z | 2021-02-23T13:01:10.000Z | far/config.hpp | data-man/FarAS | 8bd1725cdd2aaee90081ae35c492738e0be470a3 | [
"BSD-3-Clause"
] | null | null | null | #ifndef CONFIG_HPP_E468759B_688C_4D45_A5BA_CF1D4FCC9A08
#define CONFIG_HPP_E468759B_688C_4D45_A5BA_CF1D4FCC9A08
#pragma once
/*
config.hpp
Конфигурация
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR 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.
*/
// Internal:
#include "palette.hpp"
#include "plugin.hpp"
// Platform:
// Common:
#include "common/multifunction.hpp"
#include "common/monitored.hpp"
#include "common/utility.hpp"
// External:
//----------------------------------------------------------------------------
struct FarSettingsItem;
class GeneralConfig;
class RegExp;
struct PanelViewSettings;
struct hash_icase_t;
struct equal_icase_t;
struct column;
struct FARConfigItem;
enum class panel_sort: int
{
UNSORTED,
BY_NAME,
BY_EXT,
BY_MTIME,
BY_CTIME,
BY_ATIME,
BY_SIZE,
BY_DIZ,
BY_OWNER,
BY_COMPRESSEDSIZE,
BY_NUMLINKS,
BY_NUMSTREAMS,
BY_STREAMSSIZE,
BY_NAMEONLY,
BY_CHTIME,
COUNT,
BY_USER = 100000
};
enum class sort_order: int
{
first,
flip_or_default = first,
keep,
ascend,
descend,
last = descend
};
enum
{
CASR_PANEL = 0_bit,
CASR_EDITOR = 1_bit,
CASR_VIEWER = 2_bit,
CASR_HELP = 3_bit,
CASR_DIALOG = 4_bit,
};
enum ExcludeCmdHistoryType
{
EXCLUDECMDHISTORY_NOTWINASS = 0_bit, // не помещать в историю команды ассоциаций Windows
EXCLUDECMDHISTORY_NOTFARASS = 1_bit, // не помещать в историю команды выполнения ассоциаций файлов
EXCLUDECMDHISTORY_NOTPANEL = 2_bit, // не помещать в историю команды выполнения с панели
EXCLUDECMDHISTORY_NOTCMDLINE = 3_bit, // не помещать в историю команды выполнения с ком.строки
//EXCLUDECMDHISTORY_NOTAPPLYCMD = 4_bit, // не помещать в историю команды выполнения из "Apply Command"
};
enum QUOTEDNAMETYPE
{
QUOTEDNAME_INSERT = 0_bit, // кавычить при сбросе в командную строку, в диалогах и редакторе
QUOTEDNAME_CLIPBOARD = 1_bit, // кавычить при помещении в буфер обмена
};
enum
{
DMOUSEBUTTON_LEFT = 0_bit,
DMOUSEBUTTON_RIGHT = 1_bit,
};
enum
{
VMENUCLICK_IGNORE = 0,
VMENUCLICK_CANCEL = 1,
VMENUCLICK_APPLY = 2,
};
enum DIZUPDATETYPE
{
DIZ_NOT_UPDATE,
DIZ_UPDATE_IF_DISPLAYED,
DIZ_UPDATE_ALWAYS
};
enum disk_menu_mode
{
DRIVE_SHOW_TYPE = 0_bit,
DRIVE_SHOW_ASSOCIATED_PATH = 1_bit,
DRIVE_SHOW_LABEL = 2_bit,
DRIVE_SHOW_FILESYSTEM = 3_bit,
DRIVE_SHOW_SIZE = 4_bit,
DRIVE_SHOW_REMOVABLE = 5_bit,
DRIVE_SHOW_PLUGINS = 6_bit,
DRIVE_SHOW_CDROM = 7_bit,
DRIVE_SHOW_SIZE_FLOAT = 8_bit,
DRIVE_SHOW_REMOTE = 9_bit,
DRIVE_SORT_PLUGINS_BY_HOTKEY = 10_bit,
DRIVE_SHOW_LABEL_USE_SHELL = 11_bit,
DRIVE_SHOW_VIRTUAL = 12_bit,
DRIVE_SHOW_UNMOUNTED_VOLUMES = 13_bit,
};
class Option
{
public:
virtual ~Option() = default;
[[nodiscard]]
virtual string toString() const = 0;
[[nodiscard]]
virtual bool TryParse(const string& value) = 0;
[[nodiscard]]
virtual string ExInfo() const = 0;
[[nodiscard]]
virtual string_view GetType() const = 0;
[[nodiscard]]
virtual bool IsDefault(const std::any& Default) const = 0;
virtual void SetDefault(const std::any& Default) = 0;
[[nodiscard]]
virtual bool Edit(class DialogBuilder* Builder, int Width, int Param) = 0;
virtual void Export(FarSettingsItem& To) const = 0;
[[nodiscard]]
bool Changed() const { return m_Value.touched(); }
protected:
COPY_CONSTRUCTIBLE(Option);
COPY_ASSIGNABLE_DEFAULT(Option);
template<class T>
explicit Option(const T& Value): m_Value(Value) {}
template<class T>
[[nodiscard]]
const T& GetT() const { return std::any_cast<const T&>(m_Value.value().value); }
template<class T>
void SetT(const T& NewValue) { if (GetT<T>() != NewValue) m_Value = NewValue; }
private:
friend class Options;
virtual void StoreValue(GeneralConfig* Storage, string_view KeyName, string_view ValueName, bool always) const = 0;
virtual bool ReceiveValue(const GeneralConfig* Storage, string_view KeyName, string_view ValueName, const std::any& Default) = 0;
void MakeUnchanged() { m_Value.forget(); }
// Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91630
struct any
{
std::any value;
template<typename T>
any(T&& Value):
value(FWD(Value))
{
}
template<typename T>
auto& operator=(T&& Value)
{
value = FWD(Value);
}
};
monitored<any> m_Value;
};
namespace option
{
class validator_tag{};
class notifier_tag{};
template<typename callable>
auto validator(callable&& Callable)
{
return overload
{
[Callable = FWD(Callable)](validator_tag, const auto& Value){ return Callable(Value); },
[](notifier_tag, const auto&){}
};
}
template<typename callable>
auto notifier(callable&& Callable)
{
return overload
{
[](validator_tag, const auto& Value){ return Value; },
[Callable = FWD(Callable)](notifier_tag, const auto& Value){ Callable(Value); }
};
}
}
namespace detail
{
template<class base_type, class derived>
class OptionImpl: public Option
{
public:
using underlying_type = base_type;
using impl_type = OptionImpl<base_type, derived>;
using callback_type = multifunction<
base_type(option::validator_tag, const base_type&),
void(option::notifier_tag, const base_type&)
>;
void SetCallback(const callback_type& Callback)
{
assert(!m_Callback);
m_Callback = Callback;
}
[[nodiscard]]
const auto& Get() const { return GetT<base_type>(); }
void Set(const base_type& Value) { SetT(Validate(Value)); Notify(); }
[[nodiscard]]
bool TrySet(const base_type& Value)
{
if (Validate(Value) != Value)
{
return false;
}
SetT(Value);
Notify();
return true;
}
[[nodiscard]]
string ExInfo() const override { return {}; }
[[nodiscard]]
bool IsDefault(const std::any& Default) const override { return Get() == std::any_cast<base_type>(Default); }
void SetDefault(const std::any& Default) override { Set(std::any_cast<base_type>(Default)); }
[[nodiscard]]
bool ReceiveValue(const GeneralConfig* Storage, string_view KeyName, string_view ValueName, const std::any& Default) override;
void StoreValue(GeneralConfig* Storage, string_view KeyName, string_view ValueName, bool always) const override;
//operator const base_type&() const { return Get(); }
protected:
OptionImpl():
Option(base_type())
{
static_assert(std::is_base_of_v<OptionImpl, derived>);
}
auto& operator=(const base_type& Value)
{
Set(Value);
return static_cast<derived&>(*this);
}
private:
[[nodiscard]]
base_type Validate(const base_type& Value) const
{
return m_Callback?
m_Callback(option::validator_tag{}, Value) :
Value;
}
void Notify() const
{
if (m_Callback)
m_Callback(option::notifier_tag{}, Get());
}
callback_type m_Callback;
};
}
class BoolOption: public detail::OptionImpl<bool, BoolOption>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override { return Get() ? L"true"s : L"false"s; }
[[nodiscard]]
bool TryParse(const string& value) override;
[[nodiscard]]
string_view GetType() const override { return L"boolean"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
[[nodiscard]]
operator bool() const { return Get(); }
};
class Bool3Option: public detail::OptionImpl<long long, Bool3Option>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override { const auto v = Get(); return v == BSTATE_CHECKED? L"true"s : v == BSTATE_UNCHECKED? L"false"s : L"other"s; }
[[nodiscard]]
bool TryParse(const string& value) override;
[[nodiscard]]
string_view GetType() const override { return L"3-state"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
[[nodiscard]]
operator FARCHECKEDSTATE() const { return static_cast<FARCHECKEDSTATE>(Get()); }
};
class IntOption: public detail::OptionImpl<long long, IntOption>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override;
[[nodiscard]]
bool TryParse(const string& value) override;
[[nodiscard]]
string ExInfo() const override;
[[nodiscard]]
string_view GetType() const override { return L"integer"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
IntOption& operator|=(long long Value){Set(Get()|Value); return *this;}
IntOption& operator&=(long long Value){Set(Get()&Value); return *this;}
IntOption& operator%=(long long Value){Set(Get()%Value); return *this;}
IntOption& operator^=(long long Value){Set(Get()^Value); return *this;}
IntOption& operator--(){Set(Get()-1); return *this;}
IntOption& operator++(){Set(Get()+1); return *this;}
[[nodiscard]]
operator long long() const { return Get(); }
};
class StringOption: public detail::OptionImpl<string, StringOption>
{
public:
using impl_type::OptionImpl;
using impl_type::operator=;
[[nodiscard]]
string toString() const override { return Get(); }
[[nodiscard]]
bool TryParse(const string& value) override { Set(value); return true; }
[[nodiscard]]
string_view GetType() const override { return L"string"sv; }
[[nodiscard]]
bool Edit(class DialogBuilder* Builder, int Width, int Param) override;
void Export(FarSettingsItem& To) const override;
StringOption& operator+=(const string& Value) {Set(Get()+Value); return *this;}
[[nodiscard]]
wchar_t operator[] (size_t index) const { return Get()[index]; }
[[nodiscard]]
const wchar_t* c_str() const { return Get().c_str(); }
void clear() { Set({}); }
[[nodiscard]]
bool empty() const { return Get().empty(); }
[[nodiscard]]
size_t size() const { return Get().size(); }
[[nodiscard]]
operator const string&() const { return Get(); }
[[nodiscard]]
operator string_view() const { return Get(); }
};
class Options: noncopyable
{
enum class config_type
{
roaming,
local,
};
public:
struct ViewerOptions;
struct EditorOptions;
Options();
~Options();
void ShellOptions(bool LastCommand, const MOUSE_EVENT_RECORD *MouseEvent);
using overrides = std::unordered_map<string, string, hash_icase_t, equal_icase_t>;
void Load(overrides&& Overrides);
void Save(bool Manual);
const Option* GetConfigValue(string_view Key, string_view Name) const;
const Option* GetConfigValue(size_t Root, string_view Name) const;
bool AdvancedConfig(config_type Mode = config_type::roaming);
void LocalViewerConfig(ViewerOptions &ViOptRef) {return ViewerConfig(ViOptRef, true);}
void LocalEditorConfig(EditorOptions &EdOptRef) {return EditorConfig(EdOptRef, true);}
void SetSearchColumns(string_view Columns, string_view Widths);
struct SortingOptions
{
enum class collation
{
ordinal = 0,
invariant = 1,
linguistic = 2,
};
IntOption Collation;
BoolOption DigitsAsNumbers;
BoolOption CaseSensitive;
};
struct PanelOptions
{
IntOption m_Type;
BoolOption Visible;
IntOption ViewMode;
IntOption SortMode;
BoolOption ReverseSortOrder;
BoolOption SortGroups;
BoolOption ShowShortNames;
BoolOption SelectedFirst;
BoolOption DirectoriesFirst;
StringOption Folder;
StringOption CurFile;
};
struct AutoCompleteOptions
{
BoolOption ShowList;
BoolOption ModalList;
BoolOption AppendCompletion;
Bool3Option UseFilesystem;
Bool3Option UseHistory;
Bool3Option UsePath;
Bool3Option UseEnvironment;
};
struct PluginConfirmation
{
Bool3Option OpenFilePlugin;
BoolOption StandardAssociation;
BoolOption EvenIfOnlyOnePlugin;
BoolOption SetFindList;
BoolOption Prefix;
};
struct Confirmation
{
BoolOption Copy;
BoolOption Move;
BoolOption RO;
BoolOption Drag;
BoolOption Delete;
BoolOption DeleteFolder;
BoolOption Exit;
BoolOption Esc;
BoolOption EscTwiceToInterrupt;
BoolOption RemoveConnection;
BoolOption AllowReedit;
BoolOption HistoryClear;
BoolOption RemoveSUBST;
BoolOption RemoveHotPlug;
BoolOption DetachVHD;
};
struct DizOptions
{
StringOption strListNames;
BoolOption ROUpdate;
IntOption UpdateMode;
BoolOption SetHidden;
IntOption StartPos;
BoolOption AnsiByDefault;
BoolOption SaveInUTF;
};
struct CodeXLAT
{
HKL Layouts[10]{};
StringOption strLayouts;
StringOption Rules[3]; // правила:
// [0] "если предыдущий символ латинский"
// [1] "если предыдущий символ нелатинский символ"
// [2] "если предыдущий символ не рус/lat"
StringOption Table[2]; // [0] non-english буквы, [1] english буквы
StringOption strWordDivForXlat;
IntOption Flags;
mutable int CurrentLayout{};
};
struct EditorOptions
{
IntOption TabSize;
IntOption ExpandTabs;
BoolOption PersistentBlocks;
BoolOption DelRemovesBlocks;
BoolOption AutoIndent;
BoolOption AutoDetectCodePage;
IntOption DefaultCodePage;
StringOption strF8CPs;
BoolOption CursorBeyondEOL;
BoolOption BSLikeDel;
IntOption CharCodeBase;
BoolOption SavePos;
BoolOption SaveShortPos;
BoolOption AllowEmptySpaceAfterEof;
IntOption ReadOnlyLock;
IntOption UndoSize;
BoolOption UseExternalEditor;
IntOption FileSizeLimit;
BoolOption ShowKeyBar;
BoolOption ShowTitleBar;
BoolOption ShowScrollBar;
BoolOption EditOpenedForWrite;
BoolOption SearchSelFound;
BoolOption SearchCursorAtEnd;
BoolOption SearchRegexp;
Bool3Option ShowWhiteSpace;
StringOption strWordDiv;
BoolOption KeepEOL;
BoolOption AddUnicodeBOM;
BoolOption NewFileUnixEOL;
BoolOption SaveSafely;
BoolOption CreateBackups;
};
struct ViewerOptions
{
enum
{
eMinLineSize = 1*1000,
eDefLineSize = 10*1000,
eMaxLineSize = 100*1000
};
BoolOption AutoDetectCodePage;
BoolOption DetectDumpMode;
IntOption DefaultCodePage;
StringOption strF8CPs;
IntOption MaxLineSize; // 1000..100000, default=10000
BoolOption PersistentBlocks;
BoolOption SaveCodepage;
BoolOption SavePos;
BoolOption SaveShortPos;
BoolOption SaveViewMode;
BoolOption SaveWrapMode;
BoolOption SearchEditFocus; // auto-focus on edit text/hex window
BoolOption SearchRegexp;
Bool3Option SearchWrapStop; // [NonStop] / {Start-End} / [Full Cycle]
BoolOption ShowArrows;
BoolOption ShowKeyBar;
BoolOption ShowScrollbar;
BoolOption ShowTitleBar;
IntOption TabSize;
BoolOption UseExternalViewer;
BoolOption ViewerIsWrap; // (Wrap|WordWarp)=1 | UnWrap=0
BoolOption ViewerWrap; // Wrap=0|WordWarp=1
BoolOption Visible0x00;
IntOption ZeroChar;
};
struct PoliciesOptions
{
BoolOption ShowHiddenDrives; // показывать скрытые логические диски
};
struct DialogsOptions
{
BoolOption EditBlock; // Постоянные блоки в строках ввода
BoolOption EditHistory; // Добавлять в историю?
BoolOption AutoComplete; // Разрешено автодополнение?
BoolOption EULBsClear; // = 1 - BS в диалогах для UnChanged строки удаляет такую строку также, как и Del
IntOption MouseButton; // Отключение восприятие правой/левой кнопки мыши как команд закрытия окна диалога
BoolOption DelRemovesBlocks;
IntOption CBoxMaxHeight; // максимальный размер открываемого списка (по умолчанию=8)
};
struct VMenuOptions
{
IntOption LBtnClick;
IntOption RBtnClick;
IntOption MBtnClick;
};
struct CommandLineOptions
{
BoolOption EditBlock;
BoolOption DelRemovesBlocks;
BoolOption AutoComplete;
BoolOption UsePromptFormat;
StringOption strPromptFormat;
};
struct NowellOptions
{
// перед операцией Move снимать R/S/H атрибуты, после переноса - выставлять обратно
BoolOption MoveRO;
};
struct ScreenSizes
{
// на сколько поз. изменить размеры для распахнутого экрана
IntOption DeltaX;
IntOption DeltaY;
};
struct LoadPluginsOptions
{
// путь для поиска плагинов, указанный в /p
string strCustomPluginsPath;
string strPersonalPluginsPath;
// true - использовать стандартный путь к основным плагинам
bool MainPluginDir{};
// set by '/co' switch, not saved
bool PluginsCacheOnly{};
bool PluginsPersonal{};
#ifndef NO_WRAPPER
BoolOption OEMPluginsSupport;
#endif // NO_WRAPPER
BoolOption ScanSymlinks;
};
struct FindFileOptions
{
IntOption FileSearchMode;
BoolOption FindFolders;
BoolOption FindSymLinks;
BoolOption UseFilter;
BoolOption FindAlternateStreams;
StringOption strSearchInFirstSize;
StringOption strSearchOutFormat;
StringOption strSearchOutFormatWidth;
std::vector<column> OutColumns;
};
struct InfoPanelOptions
{
IntOption ComputerNameFormat;
IntOption UserNameFormat;
BoolOption ShowPowerStatus;
StringOption strShowStatusInfo;
StringOption strFolderInfoFiles;
BoolOption ShowCDInfo;
};
struct TreeOptions
{
BoolOption TurnOffCompletely; // Turn OFF SlowlyAndBuglyTreeView
IntOption MinTreeCount; // Минимальное количество папок для сохранения дерева в файле.
BoolOption AutoChangeFolder; // Автосмена папок при перемещении по дереву
IntOption TreeFileAttr; // Файловые атрибуты для файлов-деревях
#if defined(TREEFILE_PROJECT)
BoolOption LocalDisk; // Хранить файл структуры папок для локальных дисков
BoolOption NetDisk; // Хранить файл структуры папок для сетевых дисков
BoolOption NetPath; // Хранить файл структуры папок для сетевых путей
BoolOption RemovableDisk; // Хранить файл структуры папок для сменных дисков
BoolOption CDDisk; // Хранить файл структуры папок для CD/DVD/BD/etc дисков
StringOption strLocalDisk; // шаблон имени файла-деревяхи для локальных дисков
StringOption strNetDisk; // шаблон имени файла-деревяхи для сетевых дисков
StringOption strNetPath; // шаблон имени файла-деревяхи для сетевых путей
StringOption strRemovableDisk; // шаблон имени файла-деревяхи для сменных дисков
StringOption strCDDisk; // шаблон имени файла-деревяхи для CD/DVD/BD/etc дисков
StringOption strExceptPath; // для перечисленных здесь не хранить
StringOption strSaveLocalPath; // сюда сохраняем локальные диски
StringOption strSaveNetPath; // сюда сохраняем сетевые диски
#endif
};
struct CopyMoveOptions
{
BoolOption UseSystemCopy; // использовать системную функцию копирования
BoolOption CopyOpened; // копировать открытые на запись файлы
BoolOption CopyShowTotal; // показать общий индикатор копирования
BoolOption MultiCopy; // "разрешить мультикопирование/перемещение/создание связей"
BoolOption PreserveTimestamps;
IntOption CopySecurityOptions; // для операции Move - что делать с опцией "Copy access rights"
IntOption CopyTimeRule; // $ 30.01.2001 VVM Показывает время копирования,оставшееся время и среднюю скорость
IntOption BufferSize;
};
struct DeleteOptions
{
BoolOption ShowTotal; // показать общий индикатор удаления
BoolOption HighlightSelected;
IntOption ShowSelected;
};
struct MacroOptions
{
// параметры /m или /ma или /m....
int DisableMacro{};
// config
StringOption strKeyMacroCtrlDot, strKeyMacroRCtrlDot; // аля KEY_CTRLDOT/KEY_RCTRLDOT
StringOption strKeyMacroCtrlShiftDot, strKeyMacroRCtrlShiftDot; // аля KEY_CTRLSHIFTDOT/KEY_RCTRLSHIFTDOT
// internal
unsigned
KeyMacroCtrlDot{},
KeyMacroRCtrlDot{},
KeyMacroCtrlShiftDot{},
KeyMacroRCtrlShiftDot{};
StringOption strDateFormat; // Для $Date
BoolOption ShowPlayIndicator; // показать вывод 'P' во время проигрывания макроса
};
struct KnownModulesIDs
{
struct UuidOption
{
UUID Id{};
StringOption StrId;
string_view Default;
}
Network,
Emenu,
Arclite,
Luamacro,
Netbox,
ProcList,
TmpPanel;
};
struct ExecuteOptions
{
BoolOption RestoreCPAfterExecute;
BoolOption ExecuteUseAppPath;
BoolOption ExecuteFullTitle;
StringOption strExecuteBatchType;
StringOption strExcludeCmds;
StringOption Comspec;
StringOption ComspecArguments;
struct
{
string Pattern;
std::unique_ptr<RegExp> Re;
}
ComspecConditionRe;
StringOption ComspecCondition;
BoolOption UseHomeDir; // cd ~
StringOption strHomeDir; // cd ~
};
SortingOptions Sort;
palette Palette;
BoolOption Clock;
BoolOption Mouse;
BoolOption ShowKeyBar;
BoolOption ScreenSaver;
IntOption ScreenSaverTime;
BoolOption ShowHidden;
BoolOption ShortcutAlwaysChdir;
BoolOption Highlight;
BoolOption RightClickSelect;
BoolOption ShowBytes;
BoolOption SelectFolders;
BoolOption AllowReverseSort;
BoolOption ReverseSortCharCompat;
BoolOption SortFolderExt;
BoolOption DeleteToRecycleBin;
IntOption WipeSymbol; // символ заполнитель для "ZAP-операции"
CopyMoveOptions CMOpt;
DeleteOptions DelOpt;
BoolOption MultiMakeDir; // Опция создания нескольких каталогов за один сеанс
BoolOption UseRegisteredTypes;
BoolOption ViewerEditorClock;
BoolOption SaveViewHistory;
IntOption ViewHistoryCount;
IntOption ViewHistoryLifetime;
StringOption strExternalEditor;
EditorOptions EdOpt;
StringOption strExternalViewer;
ViewerOptions ViOpt;
// alias for EdOpt.strWordDiv
StringOption& strWordDiv;
StringOption strQuotedSymbols;
IntOption QuotedName;
BoolOption AutoSaveSetup;
IntOption ChangeDriveMode;
BoolOption ChangeDriveDisconnectMode;
BoolOption SaveHistory;
IntOption HistoryCount;
IntOption HistoryLifetime;
BoolOption SaveFoldersHistory;
IntOption FoldersHistoryCount;
IntOption FoldersHistoryLifetime;
IntOption DialogsHistoryCount;
IntOption DialogsHistoryLifetime;
FindFileOptions FindOpt;
IntOption LeftHeightDecrement;
IntOption RightHeightDecrement;
IntOption WidthDecrement;
BoolOption ShowColumnTitles;
BoolOption ShowPanelStatus;
BoolOption ShowPanelTotals;
BoolOption ShowPanelFree;
BoolOption PanelDetailedJunction;
BoolOption ShowUnknownReparsePoint;
BoolOption ShowPanelScrollbar;
BoolOption ShowMenuScrollbar;
Bool3Option ShowScreensNumber;
BoolOption ShowSortMode;
BoolOption ShowMenuBar;
StringOption FormatNumberSeparators;
Confirmation Confirm;
PluginConfirmation PluginConfirm;
DizOptions Diz;
BoolOption ShellRightLeftArrowsRule;
PanelOptions LeftPanel;
PanelOptions RightPanel;
BoolOption LeftFocus;
AutoCompleteOptions AutoComplete;
// выше этого количество автоматически не обновлять панели.
IntOption AutoUpdateLimit;
BoolOption AutoUpdateRemoteDrive;
StringOption strLanguage;
BoolOption SetIcon;
IntOption IconIndex;
BoolOption SetAdminIcon;
IntOption PanelRightClickRule;
IntOption PanelCtrlAltShiftRule;
// поведение Ctrl-F. Если = 0, то штампуется файл как есть, иначе - с учетом отображения на панели
BoolOption PanelCtrlFRule;
/*
поведение Ctrl-Alt-Shift
бит установлен - функция включена:
0 - Panel
1 - Edit
2 - View
3 - Help
4 - Dialog
*/
IntOption AllCtrlAltShiftRule;
IntOption CASRule; // 18.12.2003 - Пробуем различать левый и правый CAS (попытка #1).
/*
задает поведение Esc для командной строки:
=1 - Не изменять положение в History, если после Ctrl-E/Ctrl/-X
нажали ESC (поведение - аля VC).
=0 - поведение как и было - изменять положение в History
*/
BoolOption CmdHistoryRule;
IntOption ExcludeCmdHistory;
BoolOption SubstPluginPrefix; // 1 = подстанавливать префикс плагина (для Ctrl-[ и ему подобные)
BoolOption SetAttrFolderRules;
BoolOption ExceptUsed;
StringOption strExceptEventSvc;
IntOption CursorSize[4];
CodeXLAT XLat;
StringOption ConsoleDetachKey; // Комбинация клавиш для детача Far'овской консоли от длятельного неинтерактивного процесса в ней запущенного.
StringOption strHelpLanguage;
BoolOption FullScreenHelp;
IntOption HelpTabSize;
IntOption HelpURLRules; // =0 отключить возможность запуска URL-приложений
BoolOption HelpSearchRegexp;
// запоминать логические диски и не опрашивать каждый раз. Для предотвращения "просыпания" "зеленых" винтов.
BoolOption RememberLogicalDrives;
BoolOption FlagPosixSemantics;
IntOption MsWheelDelta; // задает смещение для прокрутки
IntOption MsWheelDeltaView;
IntOption MsWheelDeltaEdit;
IntOption MsWheelDeltaHelp;
// горизонтальная прокрутка
IntOption MsHWheelDelta;
IntOption MsHWheelDeltaView;
IntOption MsHWheelDeltaEdit;
/*
битовая маска:
0 - если установлен, то опрашивать сменные диски при GetSubstName()
1 - если установлен, то опрашивать все остальные при GetSubstName()
*/
IntOption SubstNameRule;
/* $ 23.05.2001 AltF9
+ Флаг позволяет выбрать механизм работы комбинации Alt-F9
(Изменение размера экрана) в оконном режиме. По умолчанию - 1.
0 - использовать механизм, совместимый с FAR версии 1.70 beta 3 и
ниже, т.е. переключение 25/50 линий.
1 - использовать усовершенствованный механизм - окно FAR Manager
будет переключаться с нормального на максимально доступный размер
консольного окна и обратно.*/
BoolOption AltF9;
BoolOption VirtualTerminalRendering;
Bool3Option ClearType;
Bool3Option PgUpChangeDisk;
BoolOption ShowDotsInRoot;
BoolOption ShowCheckingFile;
BoolOption UpdateEnvironment;
ExecuteOptions Exec;
IntOption PluginMaxReadData;
BoolOption ScanJunction;
IntOption RedrawTimeout;
LoadPluginsOptions LoadPlug;
DialogsOptions Dialogs;
VMenuOptions VMenu;
CommandLineOptions CmdLine;
PoliciesOptions Policies;
NowellOptions Nowell;
ScreenSizes ScrSize;
MacroOptions Macro;
IntOption FindCodePage;
TreeOptions Tree;
InfoPanelOptions InfoPanel;
BoolOption CPMenuMode;
StringOption strNoAutoDetectCP;
// Перечисленные здесь кодовые страницы будут исключены из детектирования nsUniversalDetectorEx.
// Автодетект юникодных страниц от этого не зависит, поэтому UTF-8 будет определяться даже если
// 65001 здесь присутствует. Если UniversalDetector выдаст страницу из этого списка, она будет
// заменена на умолчательную ANSI или OEM, в зависимости от настроек.
// пример: L"1250,1252,1253,1255,855,10005,28592,28595,28597,28598,38598,65001"
// Если строка пустая никакой фильтрации кодовых страниц в UCD детекте не будет.
// Если "-1", то в зависимости от CPMenuMode (Ctrl-H в меню кодовых страниц) фильтрация UCD либо будет
// отключена, либо будут разрешенны только избранные и системные (OEM ANSI) кодовые страницы.
StringOption strTitleAddons;
StringOption strEditorTitleFormat;
StringOption strViewerTitleFormat;
IntOption StoredElevationMode;
BoolOption StoredWindowMode;
string ProfilePath;
string LocalProfilePath;
string TemplateProfilePath;
string GlobalUserMenuDir;
KnownModulesIDs KnownIDs;
StringOption strBoxSymbols;
BoolOption SmartFolderMonitor; // def: 0=always monitor panel folder(s), 1=only when FAR has input focus
int ReadOnlyConfig{-1};
int UseExceptionHandler{};
long long ElevationMode{};
int WindowMode{-1};
BoolOption WindowModeStickyX;
BoolOption WindowModeStickyY;
std::vector<std::vector<std::pair<panel_sort, sort_order>>> PanelSortLayers;
const std::vector<PanelViewSettings>& ViewSettings;
class farconfig;
private:
void InitConfigs();
void InitConfigsData();
farconfig& GetConfig(config_type Type);
const farconfig& GetConfig(config_type Type) const;
static intptr_t AdvancedConfigDlgProc(class Dialog* Dlg, intptr_t Msg, intptr_t Param1, void* Param2);
void SystemSettings();
void PanelSettings();
void InterfaceSettings();
void DialogSettings();
void VMenuSettings();
void CmdlineSettings();
void SetConfirmations();
void PluginsManagerSettings();
void SetDizConfig();
void ViewerConfig(ViewerOptions &ViOptRef, bool Local = false);
void EditorConfig(EditorOptions &EdOptRef, bool Local = false);
void SetFolderInfoFiles();
void InfoPanelSettings();
static void MaskGroupsSettings();
void AutoCompleteSettings();
void TreeSettings();
void SetFilePanelModes();
void SetViewSettings(size_t Index, PanelViewSettings&& Data);
void AddViewSettings(size_t Index, PanelViewSettings&& Data);
void DeleteViewSettings(size_t Index);
void ReadPanelModes();
void SavePanelModes(bool always);
void SetDriveMenuHotkeys();
void ReadSortLayers();
void SaveSortLayers(bool Always);
std::vector<farconfig> m_Configs;
std::vector<PanelViewSettings> m_ViewSettings;
bool m_ViewSettingsChanged{};
};
string GetFarIniString(string_view AppName, string_view KeyName, string_view Default);
int GetFarIniInt(string_view AppName, string_view KeyName, int Default);
std::chrono::steady_clock::duration GetRedrawTimeout() noexcept;
#endif // CONFIG_HPP_E468759B_688C_4D45_A5BA_CF1D4FCC9A08
| 27.144677 | 144 | 0.754257 | data-man |
c8a911d1ece0e478a56fd7421bb06f8e53b8633f | 2,377 | cc | C++ | source/extensions/filters/common/original_src/original_src_socket_option.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 17,703 | 2017-09-14T18:23:43.000Z | 2022-03-31T22:04:17.000Z | source/extensions/filters/common/original_src/original_src_socket_option.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 15,957 | 2017-09-14T16:38:22.000Z | 2022-03-31T23:56:30.000Z | source/extensions/filters/common/original_src/original_src_socket_option.cc | dcillera/envoy | cb54ba8eec26f768f8c1ae412113b07bacde7321 | [
"Apache-2.0"
] | 3,780 | 2017-09-14T18:58:47.000Z | 2022-03-31T17:10:47.000Z | #include "source/extensions/filters/common/original_src/original_src_socket_option.h"
#include "envoy/config/core/v3/base.pb.h"
#include "source/common/common/assert.h"
namespace Envoy {
namespace Extensions {
namespace Filters {
namespace Common {
namespace OriginalSrc {
OriginalSrcSocketOption::OriginalSrcSocketOption(
Network::Address::InstanceConstSharedPtr src_address)
: src_address_(std::move(src_address)) {
// Source transparency only works on IP connections.
ASSERT(src_address_->type() == Network::Address::Type::Ip);
}
bool OriginalSrcSocketOption::setOption(
Network::Socket& socket, envoy::config::core::v3::SocketOption::SocketState state) const {
if (state == envoy::config::core::v3::SocketOption::STATE_PREBIND) {
socket.connectionInfoProvider().setLocalAddress(src_address_);
}
return true;
}
/**
* Inserts an address, already in network order, to a byte array.
*/
template <typename T> void addressIntoVector(std::vector<uint8_t>& vec, const T& address) {
const uint8_t* byte_array = reinterpret_cast<const uint8_t*>(&address);
vec.insert(vec.end(), byte_array, byte_array + sizeof(T));
}
void OriginalSrcSocketOption::hashKey(std::vector<uint8_t>& key) const {
// Note: we're assuming that there cannot be a conflict between IPv6 addresses here. If an IPv4
// address is mapped into an IPv6 address using an IPv4-Mapped IPv6 Address (RFC4921), then it's
// possible the hashes will be different despite the IP address used by the connection being
// the same.
if (src_address_->ip()->version() == Network::Address::IpVersion::v4) {
// note raw_address is already in network order
uint32_t raw_address = src_address_->ip()->ipv4()->address();
addressIntoVector(key, raw_address);
} else if (src_address_->ip()->version() == Network::Address::IpVersion::v6) {
// note raw_address is already in network order
absl::uint128 raw_address = src_address_->ip()->ipv6()->address();
addressIntoVector(key, raw_address);
}
}
absl::optional<Network::Socket::Option::Details> OriginalSrcSocketOption::getOptionDetails(
const Network::Socket&, envoy::config::core::v3::SocketOption::SocketState) const {
// no details for this option.
return absl::nullopt;
}
} // namespace OriginalSrc
} // namespace Common
} // namespace Filters
} // namespace Extensions
} // namespace Envoy
| 36.015152 | 98 | 0.734539 | dcillera |
c8a989650ffbb675ae69c6f01486a9ef2c707fd5 | 3,251 | cpp | C++ | core/test/pick_ur5.cpp | gavanderhoorn/moveit_task_constructor | 6eb8b0d64c82240c1a04149e01cd3a136c549232 | [
"BSD-3-Clause"
] | 27 | 2020-03-02T14:32:50.000Z | 2021-10-21T13:12:02.000Z | core/test/pick_ur5.cpp | tylerjw/moveit_task_constructor | 145bec1ed3b6639d0b937b155e362e063860f4b3 | [
"BSD-3-Clause"
] | 3 | 2021-07-16T09:46:09.000Z | 2021-09-09T20:05:36.000Z | core/test/pick_ur5.cpp | tylerjw/moveit_task_constructor | 145bec1ed3b6639d0b937b155e362e063860f4b3 | [
"BSD-3-Clause"
] | 8 | 2020-03-13T20:52:23.000Z | 2022-01-12T11:15:47.000Z | #include <moveit/task_constructor/task.h>
#include <moveit/task_constructor/stages/current_state.h>
#include <moveit/task_constructor/stages/generate_grasp_pose.h>
#include <moveit/task_constructor/stages/simple_grasp.h>
#include <moveit/task_constructor/stages/pick.h>
#include <moveit/task_constructor/stages/connect.h>
#include <moveit/task_constructor/solvers/pipeline_planner.h>
#include <ros/ros.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <gtest/gtest.h>
using namespace moveit::task_constructor;
void spawnObject() {
moveit::planning_interface::PlanningSceneInterface psi;
moveit_msgs::CollisionObject o;
o.id = "object";
o.header.frame_id = "table_top";
o.primitive_poses.resize(1);
o.primitive_poses[0].position.x = -0.2;
o.primitive_poses[0].position.y = 0.13;
o.primitive_poses[0].position.z = 0.12;
o.primitive_poses[0].orientation.w = 1.0;
o.primitives.resize(1);
o.primitives[0].type = shape_msgs::SolidPrimitive::CYLINDER;
o.primitives[0].dimensions.resize(2);
o.primitives[0].dimensions[0] = 0.23;
o.primitives[0].dimensions[1] = 0.03;
psi.applyCollisionObject(o);
}
TEST(UR5, pick) {
Task t;
Stage* initial_stage = nullptr;
auto initial = std::make_unique<stages::CurrentState>("current state");
initial_stage = initial.get();
t.add(std::move(initial));
// planner used for connect
auto pipeline = std::make_shared<solvers::PipelinePlanner>();
pipeline->setPlannerId("RRTConnectkConfigDefault");
// connect to pick
stages::Connect::GroupPlannerVector planners = { { "arm", pipeline }, { "gripper", pipeline } };
auto connect = std::make_unique<stages::Connect>("connect", planners);
connect->properties().configureInitFrom(Stage::PARENT);
t.add(std::move(connect));
// grasp generator
auto grasp_generator = new stages::GenerateGraspPose("generate grasp pose");
grasp_generator->setAngleDelta(.2);
grasp_generator->setPreGraspPose("open");
grasp_generator->setGraspPose("closed");
grasp_generator->setMonitoredStage(initial_stage);
auto grasp = std::make_unique<stages::SimpleGrasp>(std::unique_ptr<MonitoringGenerator>(grasp_generator));
grasp->setIKFrame(Eigen::Translation3d(.03, 0, 0), "s_model_tool0");
grasp->setMaxIKSolutions(8);
auto pick = std::make_unique<stages::Pick>(std::move(grasp));
pick->setProperty("eef", std::string("gripper"));
pick->setProperty("object", std::string("object"));
geometry_msgs::TwistStamped approach;
approach.header.frame_id = "s_model_tool0";
approach.twist.linear.x = 1.0;
pick->setApproachMotion(approach, 0.03, 0.1);
geometry_msgs::TwistStamped lift;
lift.header.frame_id = "world";
lift.twist.linear.z = 1.0;
pick->setLiftMotion(lift, 0.03, 0.05);
t.add(std::move(pick));
try {
spawnObject();
t.plan();
} catch (const InitStageException& e) {
ADD_FAILURE() << "planning failed with exception" << std::endl << e << t;
}
auto solutions = t.solutions().size();
EXPECT_GE(solutions, 30u);
EXPECT_LE(solutions, 60u);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "ur5");
ros::AsyncSpinner spinner(1);
spinner.start();
// wait some time for move_group to come up
ros::WallDuration(5.0).sleep();
return RUN_ALL_TESTS();
}
| 32.188119 | 107 | 0.738234 | gavanderhoorn |
c8a9c8db8cf4320cbf83579fe874d74865af94a1 | 489 | cpp | C++ | 17.2. Classes II/main.cpp | joaovmalheiros/Exercicios-Para-Revisao-Cplusplus | b9d523f863fd112b2b7fe72142a7128d5d95badc | [
"MIT"
] | null | null | null | 17.2. Classes II/main.cpp | joaovmalheiros/Exercicios-Para-Revisao-Cplusplus | b9d523f863fd112b2b7fe72142a7128d5d95badc | [
"MIT"
] | null | null | null | 17.2. Classes II/main.cpp | joaovmalheiros/Exercicios-Para-Revisao-Cplusplus | b9d523f863fd112b2b7fe72142a7128d5d95badc | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
//The keyword this: represents a pointer to the object whose member function is being executed. It is used within a class's
//member function to refer to the object itself.
class Dummy {
public:
bool isitme (Dummy& param);
};
bool Dummy::isitme (Dummy& param)
{
if(¶m == this) return true;
else return false;
}
int main()
{
Dummy a;
Dummy* b = &a;
if(b->isitme(a))
cout << "yes, &a is b\n";
return 0;
}
| 18.111111 | 123 | 0.642127 | joaovmalheiros |
c8aa4964293a897fbcd950414fac7436b4e8f971 | 4,189 | cpp | C++ | Libraries/FreeImage-3170/Source/OpenEXR/IlmThread/IlmThreadSemaphoreWin32.cpp | QuaternionMark/COMP371-FinalProject | ac750a5bb4896f4800d8fbc08fac9ef9a002ed44 | [
"Zlib"
] | 1 | 2022-03-27T02:56:21.000Z | 2022-03-27T02:56:21.000Z | Libraries/FreeImage-3170/Source/OpenEXR/IlmThread/IlmThreadSemaphoreWin32.cpp | MergeCommits/COMP371-FinalProject | ac750a5bb4896f4800d8fbc08fac9ef9a002ed44 | [
"Zlib"
] | null | null | null | Libraries/FreeImage-3170/Source/OpenEXR/IlmThread/IlmThreadSemaphoreWin32.cpp | MergeCommits/COMP371-FinalProject | ac750a5bb4896f4800d8fbc08fac9ef9a002ed44 | [
"Zlib"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2005-2012, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// class Semaphore -- implementation for Windows
//
//-----------------------------------------------------------------------------
#include "IlmBaseConfig.h"
#if defined(_WIN32) && !defined(HAVE_PTHREAD) && !defined(HAVE_POSIX_SEMAPHORES)
#include "IlmThreadSemaphore.h"
#include "Iex.h"
#include <string>
#include <assert.h>
#include <iostream>
ILMTHREAD_INTERNAL_NAMESPACE_SOURCE_ENTER
using namespace IEX_NAMESPACE;
namespace {
std::string
errorString ()
{
LPSTR messageBuffer;
DWORD bufferLength;
std::string message;
//
// Call FormatMessage() to allow for message
// text to be acquired from the system.
//
if (bufferLength = FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM,
0,
GetLastError (),
MAKELANGID (LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR) &messageBuffer,
0,
NULL))
{
message = messageBuffer;
LocalFree (messageBuffer);
}
return message;
}
} // namespace
Semaphore::Semaphore (unsigned int value)
{
if ((_semaphore = ::CreateSemaphore (0, value, 0x7fffffff, 0)) == 0)
{
THROW (LogicExc, "Could not create semaphore "
"(" << errorString() << ").");
}
}
Semaphore::~Semaphore()
{
bool ok = ::CloseHandle (_semaphore) != FALSE;
assert (ok);
}
void
Semaphore::wait()
{
if (::WaitForSingleObject (_semaphore, INFINITE) != WAIT_OBJECT_0)
{
THROW (LogicExc, "Could not wait on semaphore "
"(" << errorString() << ").");
}
}
bool
Semaphore::tryWait()
{
return ::WaitForSingleObject (_semaphore, 0) == WAIT_OBJECT_0;
}
void
Semaphore::post()
{
if (!::ReleaseSemaphore (_semaphore, 1, 0))
{
THROW (LogicExc, "Could not post on semaphore "
"(" << errorString() << ").");
}
}
int
Semaphore::value() const
{
LONG v = -1;
if (!::ReleaseSemaphore (_semaphore, 0, &v) || v < 0)
{
THROW (LogicExc, "Could not get value of semaphore "
"(" << errorString () << ").");
}
return v;
}
ILMTHREAD_INTERNAL_NAMESPACE_SOURCE_EXIT
#endif
| 27.201299 | 81 | 0.606111 | QuaternionMark |
c8acd14f7ec2d740f9aac4cd47f44925b765a972 | 390 | cpp | C++ | 01/ex8.cpp | Sadik326-ctrl/computer_programming | cbae264ffa04fc487008fa6a0a32e0a1a316e01e | [
"MIT"
] | null | null | null | 01/ex8.cpp | Sadik326-ctrl/computer_programming | cbae264ffa04fc487008fa6a0a32e0a1a316e01e | [
"MIT"
] | null | null | null | 01/ex8.cpp | Sadik326-ctrl/computer_programming | cbae264ffa04fc487008fa6a0a32e0a1a316e01e | [
"MIT"
] | null | null | null | // Circumference and area of a circle with radius 2.5
#include <iostream>
using namespace std;
const double pi = 3.141593;
int main()
{
double area, circuit, radius = 1.5;
area = pi * radius * radius;
circuit = 2 * pi * radius;
cout << "\nTo Evaluate a Circle\n" << endl;
cout << "Radius:
" << radius
<< "Circumference: " << circuit
<< "Area:
" << area
<< endl
<< endl
<< endl;
return 0;
}
| 18.571429 | 53 | 0.638462 | Sadik326-ctrl |
c8ae93097b8d059966fc3ef47ac6c42b64b4bab2 | 6,494 | cpp | C++ | Code/EditorPlugins/ProcGen/EditorPluginProcGen/ProcGenGraphAsset/ProcGenGraphQt.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | 1 | 2021-06-23T14:44:02.000Z | 2021-06-23T14:44:02.000Z | Code/EditorPlugins/ProcGen/EditorPluginProcGen/ProcGenGraphAsset/ProcGenGraphQt.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | Code/EditorPlugins/ProcGen/EditorPluginProcGen/ProcGenGraphAsset/ProcGenGraphQt.cpp | fereeh/ezEngine | 14e46cb2a1492812888602796db7ddd66e2b7110 | [
"MIT"
] | null | null | null | #include <EditorPluginProcGenPCH.h>
#include <EditorEngineProcessFramework/EngineProcess/EngineProcessMessages.h>
#include <EditorPluginProcGen/ProcGenGraphAsset/ProcGenGraphAsset.h>
#include <EditorPluginProcGen/ProcGenGraphAsset/ProcGenGraphQt.h>
#include <Foundation/Strings/StringBuilder.h>
#include <Foundation/Strings/TranslationLookup.h>
#include <GameEngine/VisualScript/VisualScriptInstance.h>
#include <GuiFoundation/NodeEditor/Pin.h>
#include <GuiFoundation/UIServices/UIServices.moc.h>
#include <ToolsFoundation/Command/NodeCommands.h>
#include <QAction>
#include <QMenu>
#include <QPainter>
#include <QTimer>
namespace
{
static ezColorGammaUB CategoryColor(const char* szCategory)
{
if (ezStringUtils::IsEqual(szCategory, "Input"))
return ezColorGammaUB(38, 105, 0);
else if (ezStringUtils::IsEqual(szCategory, "Output"))
return ezColorGammaUB(0, 101, 105);
else if (ezStringUtils::IsEqual(szCategory, "Math"))
return ezColorGammaUB(0, 53, 91);
return ezColor::DarkOliveGreen;
}
} // namespace
//////////////////////////////////////////////////////////////////////////
ezQtProcGenNode::ezQtProcGenNode()
{
// this costs too much performance :-(
EnableDropShadow(false);
}
void ezQtProcGenNode::InitNode(const ezDocumentNodeManager* pManager, const ezDocumentObject* pObject)
{
ezQtNode::InitNode(pManager, pObject);
const ezRTTI* pRtti = pObject->GetType();
if (const ezCategoryAttribute* pAttr = pRtti->GetAttributeByType<ezCategoryAttribute>())
{
ezColorGammaUB color = CategoryColor(pAttr->GetCategory());
m_HeaderColor = qRgb(color.r, color.g, color.b);
}
}
void ezQtProcGenNode::UpdateState()
{
ezStringBuilder sTitle;
const ezRTTI* pRtti = GetObject()->GetType();
auto& typeAccessor = GetObject()->GetTypeAccessor();
if (const ezTitleAttribute* pAttr = pRtti->GetAttributeByType<ezTitleAttribute>())
{
ezStringBuilder temp;
ezStringBuilder temp2;
ezHybridArray<ezAbstractProperty*, 32> properties;
GetObject()->GetType()->GetAllProperties(properties);
sTitle = pAttr->GetTitle();
for (const auto& pin : GetInputPins())
{
temp.Set("{", pin->GetPin()->GetName(), "}");
if (pin->HasAnyConnections())
{
sTitle.ReplaceAll(temp, pin->GetPin()->GetName());
}
else
{
temp2.Set("{Input", pin->GetPin()->GetName(), "}");
sTitle.ReplaceAll(temp, temp2);
}
}
ezVariant val;
ezStringBuilder sVal;
ezStringBuilder sEnumVal;
for (const auto& prop : properties)
{
if (prop->GetCategory() == ezPropertyCategory::Set)
{
sVal = "{";
ezHybridArray<ezVariant, 16> values;
typeAccessor.GetValues(prop->GetPropertyName(), values);
for (auto& setVal : values)
{
if (sVal.GetElementCount() > 1)
{
sVal.Append(", ");
}
sVal.Append(setVal.ConvertTo<ezString>().GetView());
}
sVal.Append("}");
}
else
{
val = typeAccessor.GetValue(prop->GetPropertyName());
if (prop->GetSpecificType()->IsDerivedFrom<ezEnumBase>() || prop->GetSpecificType()->IsDerivedFrom<ezBitflagsBase>())
{
ezReflectionUtils::EnumerationToString(prop->GetSpecificType(), val.ConvertTo<ezInt64>(), sEnumVal);
sVal = ezTranslate(sEnumVal);
}
else if (prop->GetSpecificType() == ezGetStaticRTTI<bool>())
{
sVal = val.Get<bool>() ? "[x]" : "[ ]";
if (ezStringUtils::IsEqual(prop->GetPropertyName(), "Active"))
{
SetActive(val.Get<bool>());
}
}
else if (val.CanConvertTo<ezString>())
{
sVal = val.ConvertTo<ezString>();
}
}
temp.Set("{", prop->GetPropertyName(), "}");
sTitle.ReplaceAll(temp, sVal);
}
}
else
{
sTitle = pRtti->GetTypeName();
if (sTitle.StartsWith_NoCase("ezProcGen"))
{
sTitle.Shrink(9, 0);
}
}
m_pLabel->setPlainText(sTitle.GetData());
}
//////////////////////////////////////////////////////////////////////////
ezQtProcGenPin::ezQtProcGenPin() = default;
ezQtProcGenPin::~ezQtProcGenPin() = default;
void ezQtProcGenPin::ExtendContextMenu(QMenu& menu)
{
QAction* pAction = new QAction("Debug", &menu);
pAction->setCheckable(true);
pAction->setChecked(m_bDebug);
pAction->connect(pAction, &QAction::triggered, [this](bool bChecked) { SetDebug(bChecked); });
menu.addAction(pAction);
}
void ezQtProcGenPin::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_D || event->key() == Qt::Key_F9)
{
SetDebug(!m_bDebug);
}
}
void ezQtProcGenPin::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
ezQtPin::paint(painter, option, widget);
painter->save();
painter->setPen(QPen(QColor(220, 0, 0), 3.5f, Qt::DotLine));
painter->setBrush(Qt::NoBrush);
if (m_bDebug)
{
float pad = 3.5f;
QRectF bounds = path().boundingRect().adjusted(-pad, -pad, pad, pad);
painter->drawEllipse(bounds);
}
painter->restore();
}
QRectF ezQtProcGenPin::boundingRect() const
{
QRectF bounds = ezQtPin::boundingRect();
return bounds.adjusted(-6, -6, 6, 6);
}
void ezQtProcGenPin::SetDebug(bool bDebug)
{
if (m_bDebug != bDebug)
{
m_bDebug = bDebug;
auto pScene = static_cast<ezQtProcGenScene*>(scene());
pScene->SetDebugPin(bDebug ? this : nullptr);
update();
}
}
//////////////////////////////////////////////////////////////////////////
ezQtProcGenScene::ezQtProcGenScene(QObject* parent /*= nullptr*/)
: ezQtNodeScene(parent)
{
}
ezQtProcGenScene::~ezQtProcGenScene() = default;
void ezQtProcGenScene::SetDebugPin(ezQtProcGenPin* pDebugPin)
{
if (m_pDebugPin == pDebugPin)
return;
if (m_pDebugPin != nullptr)
{
m_pDebugPin->SetDebug(false);
}
m_pDebugPin = pDebugPin;
if (ezQtDocumentWindow* window = qobject_cast<ezQtDocumentWindow*>(parent()))
{
auto document = static_cast<ezProcGenGraphAssetDocument*>(window->GetDocument());
document->SetDebugPin(pDebugPin != nullptr ? pDebugPin->GetPin() : nullptr);
}
}
ezStatus ezQtProcGenScene::RemoveNode(ezQtNode* pNode)
{
auto pins = pNode->GetInputPins();
pins.PushBackRange(pNode->GetOutputPins());
for (auto pPin : pins)
{
if (pPin == m_pDebugPin)
{
m_pDebugPin->SetDebug(false);
}
}
return ezQtNodeScene::RemoveNode(pNode);
}
| 25.667984 | 125 | 0.636126 | fereeh |
c8af271e5fc97b803c63ecb353f0182142c24332 | 6,819 | cc | C++ | iocore/net/Net.cc | zhaorun/trafficserver | 757256129811441f29eea288b1d7e19bc54fab9c | [
"Apache-2.0"
] | 1 | 2019-10-28T04:36:50.000Z | 2019-10-28T04:36:50.000Z | iocore/net/Net.cc | zhaorun/trafficserver | 757256129811441f29eea288b1d7e19bc54fab9c | [
"Apache-2.0"
] | 2 | 2019-12-13T00:55:32.000Z | 2019-12-13T20:16:47.000Z | iocore/net/Net.cc | zhaorun/trafficserver | 757256129811441f29eea288b1d7e19bc54fab9c | [
"Apache-2.0"
] | 1 | 2020-03-13T00:17:20.000Z | 2020-03-13T00:17:20.000Z | /** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/************************************************************************
Net.cc
************************************************************************/
#include "P_Net.h"
#include <utility>
RecRawStatBlock *net_rsb = nullptr;
// All in milli-seconds
int net_config_poll_timeout = -1; // This will get set via either command line or records.config.
int net_event_period = 10;
int net_accept_period = 10;
int net_retry_delay = 10;
int net_throttle_delay = 50; /* milliseconds */
// For the in/out congestion control: ToDo: this probably would be better as ports: specifications
std::string_view net_ccp_in;
std::string_view net_ccp_out;
static inline void
configure_net()
{
REC_RegisterConfigUpdateFunc("proxy.config.net.connections_throttle", change_net_connections_throttle, nullptr);
REC_ReadConfigInteger(fds_throttle, "proxy.config.net.connections_throttle");
REC_EstablishStaticConfigInt32(net_retry_delay, "proxy.config.net.retry_delay");
REC_EstablishStaticConfigInt32(net_throttle_delay, "proxy.config.net.throttle_delay");
// These are not reloadable
REC_ReadConfigInteger(net_event_period, "proxy.config.net.event_period");
REC_ReadConfigInteger(net_accept_period, "proxy.config.net.accept_period");
// This is kinda fugly, but better than it was before (on every connection in and out)
// Note that these would need to be ats_free()'d if we ever want to clean that up, but
// we have no good way of dealing with that on such globals I think?
RecString ccp;
REC_ReadConfigStringAlloc(ccp, "proxy.config.net.tcp_congestion_control_in");
if (ccp && *ccp != '\0') {
net_ccp_in = ccp;
}
REC_ReadConfigStringAlloc(ccp, "proxy.config.net.tcp_congestion_control_out");
if (ccp && *ccp != '\0') {
net_ccp_out = ccp;
}
}
static inline void
register_net_stats()
{
const std::pair<const char *, Net_Stats> persistent[] = {
{"proxy.process.net.calls_to_read", net_calls_to_read_stat},
{"proxy.process.net.calls_to_read_nodata", net_calls_to_read_nodata_stat},
{"proxy.process.net.calls_to_readfromnet", net_calls_to_readfromnet_stat},
{"proxy.process.net.calls_to_readfromnet_afterpoll", net_calls_to_readfromnet_afterpoll_stat},
{"proxy.process.net.calls_to_write", net_calls_to_write_stat},
{"proxy.process.net.calls_to_write_nodata", net_calls_to_write_nodata_stat},
{"proxy.process.net.calls_to_writetonet", net_calls_to_writetonet_stat},
{"proxy.process.net.calls_to_writetonet_afterpoll", net_calls_to_writetonet_afterpoll_stat},
{"proxy.process.net.inactivity_cop_lock_acquire_failure", inactivity_cop_lock_acquire_failure_stat},
{"proxy.process.net.net_handler_run", net_handler_run_stat},
{"proxy.process.net.read_bytes", net_read_bytes_stat},
{"proxy.process.net.write_bytes", net_write_bytes_stat},
{"proxy.process.net.fastopen_out.attempts", net_fastopen_attempts_stat},
{"proxy.process.net.fastopen_out.successes", net_fastopen_successes_stat},
{"proxy.process.socks.connections_successful", socks_connections_successful_stat},
{"proxy.process.socks.connections_unsuccessful", socks_connections_unsuccessful_stat},
};
const std::pair<const char *, Net_Stats> non_persistent[] = {
{"proxy.process.net.accepts_currently_open", net_accepts_currently_open_stat},
{"proxy.process.net.connections_currently_open", net_connections_currently_open_stat},
{"proxy.process.net.default_inactivity_timeout_applied", default_inactivity_timeout_stat},
{"proxy.process.net.dynamic_keep_alive_timeout_in_count", keep_alive_queue_timeout_count_stat},
{"proxy.process.net.dynamic_keep_alive_timeout_in_total", keep_alive_queue_timeout_total_stat},
{"proxy.process.socks.connections_currently_open", socks_connections_currently_open_stat},
};
for (auto &p : persistent) {
RecRegisterRawStat(net_rsb, RECT_PROCESS, p.first, RECD_INT, RECP_PERSISTENT, p.second, RecRawStatSyncSum);
}
for (auto &p : non_persistent) {
RecRegisterRawStat(net_rsb, RECT_PROCESS, p.first, RECD_INT, RECP_NON_PERSISTENT, p.second, RecRawStatSyncSum);
}
NET_CLEAR_DYN_STAT(net_handler_run_stat);
NET_CLEAR_DYN_STAT(net_connections_currently_open_stat);
NET_CLEAR_DYN_STAT(net_accepts_currently_open_stat);
NET_CLEAR_DYN_STAT(net_calls_to_readfromnet_stat);
NET_CLEAR_DYN_STAT(net_calls_to_readfromnet_afterpoll_stat);
NET_CLEAR_DYN_STAT(net_calls_to_read_stat);
NET_CLEAR_DYN_STAT(net_calls_to_read_nodata_stat);
NET_CLEAR_DYN_STAT(net_calls_to_writetonet_stat);
NET_CLEAR_DYN_STAT(net_calls_to_writetonet_afterpoll_stat);
NET_CLEAR_DYN_STAT(net_calls_to_write_stat);
NET_CLEAR_DYN_STAT(net_calls_to_write_nodata_stat);
NET_CLEAR_DYN_STAT(socks_connections_currently_open_stat);
NET_CLEAR_DYN_STAT(keep_alive_queue_timeout_total_stat);
NET_CLEAR_DYN_STAT(keep_alive_queue_timeout_count_stat);
NET_CLEAR_DYN_STAT(default_inactivity_timeout_stat);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.tcp.total_accepts", RECD_INT, RECP_NON_PERSISTENT,
static_cast<int>(net_tcp_accept_stat), RecRawStatSyncSum);
NET_CLEAR_DYN_STAT(net_tcp_accept_stat);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.net.connections_throttled_in", RECD_INT, RECP_PERSISTENT,
(int)net_connections_throttled_in_stat, RecRawStatSyncSum);
RecRegisterRawStat(net_rsb, RECT_PROCESS, "proxy.process.net.connections_throttled_out", RECD_INT, RECP_PERSISTENT,
(int)net_connections_throttled_out_stat, RecRawStatSyncSum);
}
void
ink_net_init(ts::ModuleVersion version)
{
static int init_called = 0;
ink_release_assert(version.check(NET_SYSTEM_MODULE_INTERNAL_VERSION));
if (!init_called) {
// do one time stuff
// create a stat block for NetStats
net_rsb = RecAllocateRawStatBlock(static_cast<int>(Net_Stat_Count));
configure_net();
register_net_stats();
}
init_called = 1;
}
| 43.433121 | 117 | 0.767121 | zhaorun |
c8af53bfba0b6fe26b56d9c2cf715aba024f6d22 | 3,002 | cpp | C++ | pin-2.11/source/tools/Probes/exception_in_probed_call_cpp_app.cpp | swchoi1994/Project | e46fa191afe54d6676016d41534c3531eb51ff79 | [
"Intel"
] | 3 | 2020-06-26T09:35:19.000Z | 2021-01-03T16:58:11.000Z | pin-2.11/source/tools/Probes/exception_in_probed_call_cpp_app.cpp | swchoi1994/Project | e46fa191afe54d6676016d41534c3531eb51ff79 | [
"Intel"
] | null | null | null | pin-2.11/source/tools/Probes/exception_in_probed_call_cpp_app.cpp | swchoi1994/Project | e46fa191afe54d6676016d41534c3531eb51ff79 | [
"Intel"
] | 2 | 2020-12-27T03:58:38.000Z | 2020-12-27T03:58:38.000Z | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2012 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:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS 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.
END_LEGAL */
/*
This application causes exception in indirect call instruction and catches it in caller.
The call instruction is located in code region being replaced by Pin probe.
Pin translation should not affect propagation of the exception to the C++ exception handler.
*/
#ifndef TARGET_LINUX
#include <windows.h>
#endif
#include <stdio.h>
#ifndef TARGET_LINUX
#define FASTCALL __fastcall
#define DLLEXPORT __declspec(dllexport)
#else
#define FASTCALL
#define DLLEXPORT
#endif
bool destructed = false;
// cpp exceptions - Exercise windows exception mechanism
class MyClass
{
public:
~MyClass()
{
destructed = true;
}
};
static int (*pBar)() = 0;
int bar()
{
return 0;
}
extern "C"
DLLEXPORT
int foo()
{
#ifdef TARGET_LINUX
if (!pBar) throw(0);
#endif
// May cause exception due to NULL pointer
return pBar();
}
int main()
{
int i = 2;
int local = 1;
try
{
MyClass ins;
i = foo();
local = 0;
}
catch(...)
{
// If Pin translated probed code properly, exception will reach the handler
printf("Exception\n");
}
// Check that destructor was called and local var value was not changed when exception was handled
if (!destructed || (local != 1))
{
return 1;
}
pBar = bar;
try
{
i = foo();
}
catch(...)
{
// No exception expected
printf("Exception\n");
}
return i;
}
| 25.440678 | 102 | 0.717522 | swchoi1994 |
c8af73a3b4416602290a0e2720f6fce8fe15c7b0 | 42,436 | cpp | C++ | lib/CodeGen/SelectionDAG/InstrEmitter.cpp | kpdev/llvm-tnt | d81ccf6fad01597f0143a1598d94d7d29002cf41 | [
"MIT"
] | 1,073 | 2017-06-28T05:11:54.000Z | 2022-03-31T12:52:07.000Z | lib/CodeGen/SelectionDAG/InstrEmitter.cpp | kpdev/llvm-tnt | d81ccf6fad01597f0143a1598d94d7d29002cf41 | [
"MIT"
] | 23 | 2017-07-01T02:22:04.000Z | 2020-10-16T09:42:03.000Z | lib/CodeGen/SelectionDAG/InstrEmitter.cpp | kpdev/llvm-tnt | d81ccf6fad01597f0143a1598d94d7d29002cf41 | [
"MIT"
] | 244 | 2017-06-28T05:08:57.000Z | 2022-03-13T05:03:12.000Z | //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements the Emit routines for the SelectionDAG class, which creates
// MachineInstrs based on the decisions of the SelectionDAG instruction
// selection.
//
//===----------------------------------------------------------------------===//
#include "InstrEmitter.h"
#include "SDNodeDbgValue.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#define DEBUG_TYPE "instr-emitter"
/// MinRCSize - Smallest register class we allow when constraining virtual
/// registers. If satisfying all register class constraints would require
/// using a smaller register class, emit a COPY to a new virtual register
/// instead.
const unsigned MinRCSize = 4;
/// CountResults - The results of target nodes have register or immediate
/// operands first, then an optional chain, and optional glue operands (which do
/// not go into the resulting MachineInstr).
unsigned InstrEmitter::CountResults(SDNode *Node) {
unsigned N = Node->getNumValues();
while (N && Node->getValueType(N - 1) == MVT::Glue)
--N;
if (N && Node->getValueType(N - 1) == MVT::Other)
--N; // Skip over chain result.
return N;
}
/// countOperands - The inputs to target nodes have any actual inputs first,
/// followed by an optional chain operand, then an optional glue operand.
/// Compute the number of actual operands that will go into the resulting
/// MachineInstr.
///
/// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding
/// the chain and glue. These operands may be implicit on the machine instr.
static unsigned countOperands(SDNode *Node, unsigned NumExpUses,
unsigned &NumImpUses) {
unsigned N = Node->getNumOperands();
while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
--N;
if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
--N; // Ignore chain if it exists.
// Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses.
NumImpUses = N - NumExpUses;
for (unsigned I = N; I > NumExpUses; --I) {
if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
continue;
if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
if (TargetRegisterInfo::isPhysicalRegister(RN->getReg()))
continue;
NumImpUses = N - I;
break;
}
return N;
}
/// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
/// implicit physical register output.
void InstrEmitter::
EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
unsigned VRBase = 0;
if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
// Just use the input register directly!
SDValue Op(Node, ResNo);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
return;
}
// If the node is only used by a CopyToReg and the dest reg is a vreg, use
// the CopyToReg'd destination register instead of creating a new vreg.
bool MatchReg = true;
const TargetRegisterClass *UseRC = nullptr;
MVT VT = Node->getSimpleValueType(ResNo);
// Stick to the preferred register classes for legal types.
if (TLI->isTypeLegal(VT))
UseRC = TLI->getRegClassFor(VT);
if (!IsClone && !IsCloned)
for (SDNode *User : Node->uses()) {
bool Match = true;
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == ResNo) {
unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
VRBase = DestReg;
Match = false;
} else if (DestReg != SrcReg)
Match = false;
} else {
for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
SDValue Op = User->getOperand(i);
if (Op.getNode() != Node || Op.getResNo() != ResNo)
continue;
MVT VT = Node->getSimpleValueType(Op.getResNo());
if (VT == MVT::Other || VT == MVT::Glue)
continue;
Match = false;
if (User->isMachineOpcode()) {
const MCInstrDesc &II = TII->get(User->getMachineOpcode());
const TargetRegisterClass *RC = nullptr;
if (i+II.getNumDefs() < II.getNumOperands()) {
RC = TRI->getAllocatableClass(
TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF));
}
if (!UseRC)
UseRC = RC;
else if (RC) {
const TargetRegisterClass *ComRC =
TRI->getCommonSubClass(UseRC, RC, VT.SimpleTy);
// If multiple uses expect disjoint register classes, we emit
// copies in AddRegisterOperand.
if (ComRC)
UseRC = ComRC;
}
}
}
}
MatchReg &= Match;
if (VRBase)
break;
}
const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr;
SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
// Figure out the register class to create for the destreg.
if (VRBase) {
DstRC = MRI->getRegClass(VRBase);
} else if (UseRC) {
assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
DstRC = UseRC;
} else {
DstRC = TLI->getRegClassFor(VT);
}
// If all uses are reading from the src physical register and copying the
// register is either impossible or very expensive, then don't create a copy.
if (MatchReg && SrcRC->getCopyCost() < 0) {
VRBase = SrcReg;
} else {
// Create the reg, emit the copy.
VRBase = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
VRBase).addReg(SrcReg);
}
SDValue Op(Node, ResNo);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// getDstOfCopyToRegUse - If the only use of the specified result number of
/// node is a CopyToReg, return its destination register. Return 0 otherwise.
unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
unsigned ResNo) const {
if (!Node->hasOneUse())
return 0;
SDNode *User = *Node->use_begin();
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == ResNo) {
unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(Reg))
return Reg;
}
return 0;
}
void InstrEmitter::CreateVirtualRegisters(SDNode *Node,
MachineInstrBuilder &MIB,
const MCInstrDesc &II,
bool IsClone, bool IsCloned,
DenseMap<SDValue, unsigned> &VRBaseMap) {
assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
"IMPLICIT_DEF should have been handled as a special case elsewhere!");
unsigned NumResults = CountResults(Node);
for (unsigned i = 0; i < II.getNumDefs(); ++i) {
// If the specific node value is only used by a CopyToReg and the dest reg
// is a vreg in the same register class, use the CopyToReg'd destination
// register instead of creating a new vreg.
unsigned VRBase = 0;
const TargetRegisterClass *RC =
TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
// Always let the value type influence the used register class. The
// constraints on the instruction may be too lax to represent the value
// type correctly. For example, a 64-bit float (X86::FR64) can't live in
// the 32-bit float super-class (X86::FR32).
if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) {
const TargetRegisterClass *VTRC =
TLI->getRegClassFor(Node->getSimpleValueType(i));
if (RC)
VTRC = TRI->getCommonSubClass(RC, VTRC);
if (VTRC)
RC = VTRC;
}
if (II.OpInfo[i].isOptionalDef()) {
// Optional def must be a physical register.
unsigned NumResults = CountResults(Node);
VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
MIB.addReg(VRBase, RegState::Define);
}
if (!VRBase && !IsClone && !IsCloned)
for (SDNode *User : Node->uses()) {
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == i) {
unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(Reg)) {
const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
if (RegRC == RC) {
VRBase = Reg;
MIB.addReg(VRBase, RegState::Define);
break;
}
}
}
}
// Create the result registers for this node and add the result regs to
// the machine instruction.
if (VRBase == 0) {
assert(RC && "Isn't a register operand!");
VRBase = MRI->createVirtualRegister(RC);
MIB.addReg(VRBase, RegState::Define);
}
// If this def corresponds to a result of the SDNode insert the VRBase into
// the lookup map.
if (i < NumResults) {
SDValue Op(Node, i);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
}
}
/// getVR - Return the virtual register corresponding to the specified result
/// of the specified node.
unsigned InstrEmitter::getVR(SDValue Op,
DenseMap<SDValue, unsigned> &VRBaseMap) {
if (Op.isMachineOpcode() &&
Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
// Add an IMPLICIT_DEF instruction before every use.
unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
// IMPLICIT_DEF can produce any type of result so its MCInstrDesc
// does not include operand register class info.
if (!VReg) {
const TargetRegisterClass *RC =
TLI->getRegClassFor(Op.getSimpleValueType());
VReg = MRI->createVirtualRegister(RC);
}
BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
return VReg;
}
DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
assert(I != VRBaseMap.end() && "Node emitted out of order - late");
return I->second;
}
/// AddRegisterOperand - Add the specified register as an operand to the
/// specified machine instr. Insert register copies if the register is
/// not in the required register class.
void
InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
SDValue Op,
unsigned IIOpNum,
const MCInstrDesc *II,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsDebug, bool IsClone, bool IsCloned) {
assert(Op.getValueType() != MVT::Other &&
Op.getValueType() != MVT::Glue &&
"Chain and glue operands should occur at end of operand list!");
// Get/emit the operand.
unsigned VReg = getVR(Op, VRBaseMap);
const MCInstrDesc &MCID = MIB->getDesc();
bool isOptDef = IIOpNum < MCID.getNumOperands() &&
MCID.OpInfo[IIOpNum].isOptionalDef();
// If the instruction requires a register in a different class, create
// a new virtual register and copy the value into it, but first attempt to
// shrink VReg's register class within reason. For example, if VReg == GR32
// and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
if (II) {
const TargetRegisterClass *DstRC = nullptr;
if (IIOpNum < II->getNumOperands())
DstRC = TRI->getAllocatableClass(TII->getRegClass(*II,IIOpNum,TRI,*MF));
assert((!DstRC || TargetRegisterInfo::isVirtualRegister(VReg)) &&
"Expected VReg");
if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
unsigned NewVReg = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
VReg = NewVReg;
}
}
// If this value has only one use, that use is a kill. This is a
// conservative approximation. InstrEmitter does trivial coalescing
// with CopyFromReg nodes, so don't emit kill flags for them.
// Avoid kill flags on Schedule cloned nodes, since there will be
// multiple uses.
// Tied operands are never killed, so we need to check that. And that
// means we need to determine the index of the operand.
bool isKill = Op.hasOneUse() &&
Op.getNode()->getOpcode() != ISD::CopyFromReg &&
!IsDebug &&
!(IsClone || IsCloned);
if (isKill) {
unsigned Idx = MIB->getNumOperands();
while (Idx > 0 &&
MIB->getOperand(Idx-1).isReg() &&
MIB->getOperand(Idx-1).isImplicit())
--Idx;
bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
if (isTied)
isKill = false;
}
MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
getDebugRegState(IsDebug));
}
/// AddOperand - Add the specified operand to the specified machine instr. II
/// specifies the instruction information for the node, and IIOpNum is the
/// operand number (in the II) that we are adding.
void InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
SDValue Op,
unsigned IIOpNum,
const MCInstrDesc *II,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsDebug, bool IsClone, bool IsCloned) {
if (Op.isMachineOpcode()) {
AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
IsDebug, IsClone, IsCloned);
} else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
MIB.addImm(C->getSExtValue());
} else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
MIB.addFPImm(F->getConstantFPValue());
} else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
// Turn additional physreg operands into implicit uses on non-variadic
// instructions. This is used by call and return instructions passing
// arguments in registers.
bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
MIB.addReg(R->getReg(), getImplRegState(Imp));
} else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
MIB.addRegMask(RM->getRegMask());
} else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
TGA->getTargetFlags());
} else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
MIB.addMBB(BBNode->getBasicBlock());
} else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
MIB.addFrameIndex(FI->getIndex());
} else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
} else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
int Offset = CP->getOffset();
unsigned Align = CP->getAlignment();
Type *Type = CP->getType();
// MachineConstantPool wants an explicit alignment.
if (Align == 0) {
Align = MF->getDataLayout().getPrefTypeAlignment(Type);
if (Align == 0) {
// Alignment of vector types. FIXME!
Align = MF->getDataLayout().getTypeAllocSize(Type);
}
}
unsigned Idx;
MachineConstantPool *MCP = MF->getConstantPool();
if (CP->isMachineConstantPoolEntry())
Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
else
Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
} else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
} else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) {
MIB.addSym(SymNode->getMCSymbol());
} else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
MIB.addBlockAddress(BA->getBlockAddress(),
BA->getOffset(),
BA->getTargetFlags());
} else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
} else {
assert(Op.getValueType() != MVT::Other &&
Op.getValueType() != MVT::Glue &&
"Chain and glue operands should occur at end of operand list!");
AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
IsDebug, IsClone, IsCloned);
}
}
unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
MVT VT, const DebugLoc &DL) {
const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
// RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg
// within reason.
if (RC && RC != VRC)
RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
// VReg has been adjusted. It can be used with SubIdx operands now.
if (RC)
return VReg;
// VReg couldn't be reasonably constrained. Emit a COPY to a new virtual
// register instead.
RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
assert(RC && "No legal register class for VT supports that SubIdx");
unsigned NewReg = MRI->createVirtualRegister(RC);
BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
.addReg(VReg);
return NewReg;
}
/// EmitSubregNode - Generate machine code for subreg nodes.
///
void InstrEmitter::EmitSubregNode(SDNode *Node,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsClone, bool IsCloned) {
unsigned VRBase = 0;
unsigned Opc = Node->getMachineOpcode();
// If the node is only used by a CopyToReg and the dest reg is a vreg, use
// the CopyToReg'd destination register instead of creating a new vreg.
for (SDNode *User : Node->uses()) {
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node) {
unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
VRBase = DestReg;
break;
}
}
}
if (Opc == TargetOpcode::EXTRACT_SUBREG) {
// EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no
// constraints on the %dst register, COPY can target all legal register
// classes.
unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
const TargetRegisterClass *TRC =
TLI->getRegClassFor(Node->getSimpleValueType(0));
unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
MachineInstr *DefMI = MRI->getVRegDef(VReg);
unsigned SrcReg, DstReg, DefSubIdx;
if (DefMI &&
TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
SubIdx == DefSubIdx &&
TRC == MRI->getRegClass(SrcReg)) {
// Optimize these:
// r1025 = s/zext r1024, 4
// r1026 = extract_subreg r1025, 4
// to a copy
// r1026 = copy r1024
VRBase = MRI->createVirtualRegister(TRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
MRI->clearKillFlags(SrcReg);
} else {
// VReg may not support a SubIdx sub-register, and we may need to
// constrain its register class or issue a COPY to a compatible register
// class.
VReg = ConstrainForSubReg(VReg, SubIdx,
Node->getOperand(0).getSimpleValueType(),
Node->getDebugLoc());
// Create the destreg if it is missing.
if (VRBase == 0)
VRBase = MRI->createVirtualRegister(TRC);
// Create the extract_subreg machine instruction.
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
}
} else if (Opc == TargetOpcode::INSERT_SUBREG ||
Opc == TargetOpcode::SUBREG_TO_REG) {
SDValue N0 = Node->getOperand(0);
SDValue N1 = Node->getOperand(1);
SDValue N2 = Node->getOperand(2);
unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
// Figure out the register class to create for the destreg. It should be
// the largest legal register class supporting SubIdx sub-registers.
// RegisterCoalescer will constrain it further if it decides to eliminate
// the INSERT_SUBREG instruction.
//
// %dst = INSERT_SUBREG %src, %sub, SubIdx
//
// is lowered by TwoAddressInstructionPass to:
//
// %dst = COPY %src
// %dst:SubIdx = COPY %sub
//
// There is no constraint on the %src register class.
//
const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getSimpleValueType(0));
SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
VRBase = MRI->createVirtualRegister(SRC);
// Create the insert_subreg or subreg_to_reg machine instruction.
MachineInstrBuilder MIB =
BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
// If creating a subreg_to_reg, then the first input operand
// is an implicit value immediate, otherwise it's a register
if (Opc == TargetOpcode::SUBREG_TO_REG) {
const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
MIB.addImm(SD->getZExtValue());
} else
AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
IsClone, IsCloned);
// Add the subregster being inserted
AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
IsClone, IsCloned);
MIB.addImm(SubIdx);
MBB->insert(InsertPos, MIB);
} else
llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
/// COPY_TO_REGCLASS is just a normal copy, except that the destination
/// register is constrained to be in a particular register class.
///
void
InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
DenseMap<SDValue, unsigned> &VRBaseMap) {
unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
// Create the new VReg in the destination class and emit a copy.
unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
const TargetRegisterClass *DstRC =
TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
unsigned NewVReg = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
NewVReg).addReg(VReg);
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
///
void InstrEmitter::EmitRegSequence(SDNode *Node,
DenseMap<SDValue, unsigned> &VRBaseMap,
bool IsClone, bool IsCloned) {
unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
unsigned NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
unsigned NumOps = Node->getNumOperands();
assert((NumOps & 1) == 1 &&
"REG_SEQUENCE must have an odd number of operands!");
for (unsigned i = 1; i != NumOps; ++i) {
SDValue Op = Node->getOperand(i);
if ((i & 1) == 0) {
RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
// Skip physical registers as they don't have a vreg to get and we'll
// insert copies for them in TwoAddressInstructionPass anyway.
if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
const TargetRegisterClass *SRC =
TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
if (SRC && SRC != RC) {
MRI->setRegClass(NewVReg, SRC);
RC = SRC;
}
}
}
AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
IsClone, IsCloned);
}
MBB->insert(InsertPos, MIB);
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
(void)isNew; // Silence compiler warning.
assert(isNew && "Node emitted out of order - early");
}
/// EmitDbgValue - Generate machine instruction for a dbg_value node.
///
MachineInstr *
InstrEmitter::EmitDbgValue(SDDbgValue *SD,
DenseMap<SDValue, unsigned> &VRBaseMap) {
uint64_t Offset = SD->getOffset();
MDNode *Var = SD->getVariable();
MDNode *Expr = SD->getExpression();
DebugLoc DL = SD->getDebugLoc();
assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
if (SD->getKind() == SDDbgValue::FRAMEIX) {
// Stack address; this needs to be lowered in target-dependent fashion.
// EmitTargetCodeForFrameDebugValue is responsible for allocation.
return BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE))
.addFrameIndex(SD->getFrameIx())
.addImm(Offset)
.addMetadata(Var)
.addMetadata(Expr);
}
// Otherwise, we're going to create an instruction here.
const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
if (SD->getKind() == SDDbgValue::SDNODE) {
SDNode *Node = SD->getSDNode();
SDValue Op = SDValue(Node, SD->getResNo());
// It's possible we replaced this SDNode with other(s) and therefore
// didn't generate code for it. It's better to catch these cases where
// they happen and transfer the debug info, but trying to guarantee that
// in all cases would be very fragile; this is a safeguard for any
// that were missed.
DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
if (I==VRBaseMap.end())
MIB.addReg(0U); // undef
else
AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
/*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
} else if (SD->getKind() == SDDbgValue::CONST) {
const Value *V = SD->getConst();
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
if (CI->getBitWidth() > 64)
MIB.addCImm(CI);
else
MIB.addImm(CI->getSExtValue());
} else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
MIB.addFPImm(CF);
} else {
// Could be an Undef. In any case insert an Undef so we can see what we
// dropped.
MIB.addReg(0U);
}
} else {
// Insert an Undef so we can see what we dropped.
MIB.addReg(0U);
}
// Indirect addressing is indicated by an Imm as the second parameter.
if (SD->isIndirect())
MIB.addImm(Offset);
else {
assert(Offset == 0 && "direct value cannot have an offset");
MIB.addReg(0U, RegState::Debug);
}
MIB.addMetadata(Var);
MIB.addMetadata(Expr);
return &*MIB;
}
/// EmitMachineNode - Generate machine code for a target-specific node and
/// needed dependencies.
///
void InstrEmitter::
EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
DenseMap<SDValue, unsigned> &VRBaseMap) {
unsigned Opc = Node->getMachineOpcode();
// Handle subreg insert/extract specially
if (Opc == TargetOpcode::EXTRACT_SUBREG ||
Opc == TargetOpcode::INSERT_SUBREG ||
Opc == TargetOpcode::SUBREG_TO_REG) {
EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
return;
}
// Handle COPY_TO_REGCLASS specially.
if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
EmitCopyToRegClassNode(Node, VRBaseMap);
return;
}
// Handle REG_SEQUENCE specially.
if (Opc == TargetOpcode::REG_SEQUENCE) {
EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
return;
}
if (Opc == TargetOpcode::IMPLICIT_DEF)
// We want a unique VR for each IMPLICIT_DEF use.
return;
const MCInstrDesc &II = TII->get(Opc);
unsigned NumResults = CountResults(Node);
unsigned NumDefs = II.getNumDefs();
const MCPhysReg *ScratchRegs = nullptr;
// Handle STACKMAP and PATCHPOINT specially and then use the generic code.
if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) {
// Stackmaps do not have arguments and do not preserve their calling
// convention. However, to simplify runtime support, they clobber the same
// scratch registers as AnyRegCC.
unsigned CC = CallingConv::AnyReg;
if (Opc == TargetOpcode::PATCHPOINT) {
CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
NumDefs = NumResults;
}
ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
}
unsigned NumImpUses = 0;
unsigned NodeOperands =
countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
bool HasPhysRegOuts = NumResults > NumDefs && II.getImplicitDefs()!=nullptr;
#ifndef NDEBUG
unsigned NumMIOperands = NodeOperands + NumResults;
if (II.isVariadic())
assert(NumMIOperands >= II.getNumOperands() &&
"Too few operands for a variadic node!");
else
assert(NumMIOperands >= II.getNumOperands() &&
NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
NumImpUses &&
"#operands for dag node doesn't match .td file!");
#endif
// Create the new machine instruction.
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
// Add result register values for things that are defined by this
// instruction.
if (NumResults)
CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
// Emit all of the actual operands of this instruction, adding them to the
// instruction as appropriate.
bool HasOptPRefs = NumDefs > NumResults;
assert((!HasOptPRefs || !HasPhysRegOuts) &&
"Unable to cope with optional defs and phys regs defs!");
unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
for (unsigned i = NumSkip; i != NodeOperands; ++i)
AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
// Add scratch registers as implicit def and early clobber
if (ScratchRegs)
for (unsigned i = 0; ScratchRegs[i]; ++i)
MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
RegState::EarlyClobber);
// Transfer all of the memory reference descriptions of this instruction.
MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
cast<MachineSDNode>(Node)->memoperands_end());
// Insert the instruction into position in the block. This needs to
// happen before any custom inserter hook is called so that the
// hook knows where in the block to insert the replacement code.
MBB->insert(InsertPos, MIB);
// The MachineInstr may also define physregs instead of virtregs. These
// physreg values can reach other instructions in different ways:
//
// 1. When there is a use of a Node value beyond the explicitly defined
// virtual registers, we emit a CopyFromReg for one of the implicitly
// defined physregs. This only happens when HasPhysRegOuts is true.
//
// 2. A CopyFromReg reading a physreg may be glued to this instruction.
//
// 3. A glued instruction may implicitly use a physreg.
//
// 4. A glued instruction may use a RegisterSDNode operand.
//
// Collect all the used physreg defs, and make sure that any unused physreg
// defs are marked as dead.
SmallVector<unsigned, 8> UsedRegs;
// Additional results must be physical register defs.
if (HasPhysRegOuts) {
for (unsigned i = NumDefs; i < NumResults; ++i) {
unsigned Reg = II.getImplicitDefs()[i - NumDefs];
if (!Node->hasAnyUseOfValue(i))
continue;
// This implicitly defined physreg has a use.
UsedRegs.push_back(Reg);
EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
}
}
// Scan the glue chain for any used physregs.
if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
if (F->getOpcode() == ISD::CopyFromReg) {
UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
continue;
} else if (F->getOpcode() == ISD::CopyToReg) {
// Skip CopyToReg nodes that are internal to the glue chain.
continue;
}
// Collect declared implicit uses.
const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
UsedRegs.append(MCID.getImplicitUses(),
MCID.getImplicitUses() + MCID.getNumImplicitUses());
// In addition to declared implicit uses, we must also check for
// direct RegisterSDNode operands.
for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
unsigned Reg = R->getReg();
if (TargetRegisterInfo::isPhysicalRegister(Reg))
UsedRegs.push_back(Reg);
}
}
}
// Finally mark unused registers as dead.
if (!UsedRegs.empty() || II.getImplicitDefs())
MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
// Run post-isel target hook to adjust this instruction if needed.
if (II.hasPostISelHook())
TLI->AdjustInstrPostInstrSelection(*MIB, Node);
}
/// EmitSpecialNode - Generate machine code for a target-independent node and
/// needed dependencies.
void InstrEmitter::
EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
DenseMap<SDValue, unsigned> &VRBaseMap) {
switch (Node->getOpcode()) {
default:
#ifndef NDEBUG
Node->dump();
#endif
llvm_unreachable("This target-independent node should have been selected!");
case ISD::EntryToken:
llvm_unreachable("EntryToken should have been excluded from the schedule!");
case ISD::MERGE_VALUES:
case ISD::TokenFactor: // fall thru
break;
case ISD::CopyToReg: {
unsigned SrcReg;
SDValue SrcVal = Node->getOperand(2);
if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
SrcReg = R->getReg();
else
SrcReg = getVR(SrcVal, VRBaseMap);
unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
break;
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
DestReg).addReg(SrcReg);
break;
}
case ISD::CopyFromReg: {
unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
break;
}
case ISD::EH_LABEL: {
MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::EH_LABEL)).addSym(S);
break;
}
case ISD::LIFETIME_START:
case ISD::LIFETIME_END: {
unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
.addFrameIndex(FI->getIndex());
break;
}
case ISD::INLINEASM: {
unsigned NumOps = Node->getNumOperands();
if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
--NumOps; // Ignore the glue operand.
// Create the inline asm machine instruction.
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(),
TII->get(TargetOpcode::INLINEASM));
// Add the asm string as an external symbol operand.
SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
MIB.addExternalSymbol(AsmStr);
// Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
// bits.
int64_t ExtraInfo =
cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
getZExtValue();
MIB.addImm(ExtraInfo);
// Remember to operand index of the group flags.
SmallVector<unsigned, 8> GroupIdx;
// Remember registers that are part of early-clobber defs.
SmallVector<unsigned, 8> ECRegs;
// Add all of the operand registers to the instruction.
for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
unsigned Flags =
cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
GroupIdx.push_back(MIB->getNumOperands());
MIB.addImm(Flags);
++i; // Skip the ID value.
switch (InlineAsm::getKind(Flags)) {
default: llvm_unreachable("Bad flags!");
case InlineAsm::Kind_RegDef:
for (unsigned j = 0; j != NumVals; ++j, ++i) {
unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
// FIXME: Add dead flags for physical and virtual registers defined.
// For now, mark physical register defs as implicit to help fast
// regalloc. This makes inline asm look a lot like calls.
MIB.addReg(Reg, RegState::Define |
getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
}
break;
case InlineAsm::Kind_RegDefEarlyClobber:
case InlineAsm::Kind_Clobber:
for (unsigned j = 0; j != NumVals; ++j, ++i) {
unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
MIB.addReg(Reg, RegState::Define | RegState::EarlyClobber |
getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
ECRegs.push_back(Reg);
}
break;
case InlineAsm::Kind_RegUse: // Use of register.
case InlineAsm::Kind_Imm: // Immediate.
case InlineAsm::Kind_Mem: // Addressing mode.
// The addressing mode has been selected, just add all of the
// operands to the machine instruction.
for (unsigned j = 0; j != NumVals; ++j, ++i)
AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap,
/*IsDebug=*/false, IsClone, IsCloned);
// Manually set isTied bits.
if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
unsigned DefGroup = 0;
if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
unsigned DefIdx = GroupIdx[DefGroup] + 1;
unsigned UseIdx = GroupIdx.back() + 1;
for (unsigned j = 0; j != NumVals; ++j)
MIB->tieOperands(DefIdx + j, UseIdx + j);
}
}
break;
}
}
// GCC inline assembly allows input operands to also be early-clobber
// output operands (so long as the operand is written only after it's
// used), but this does not match the semantics of our early-clobber flag.
// If an early-clobber operand register is also an input operand register,
// then remove the early-clobber flag.
for (unsigned Reg : ECRegs) {
if (MIB->readsRegister(Reg, TRI)) {
MachineOperand *MO = MIB->findRegisterDefOperand(Reg, false, TRI);
assert(MO && "No def operand for clobbered register?");
MO->setIsEarlyClobber(false);
}
}
// Get the mdnode from the asm if it exists and add it to the instruction.
SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
if (MD)
MIB.addMetadata(MD);
MBB->insert(InsertPos, MIB);
break;
}
}
}
/// InstrEmitter - Construct an InstrEmitter and set it to start inserting
/// at the given position in the given block.
InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
MachineBasicBlock::iterator insertpos)
: MF(mbb->getParent()), MRI(&MF->getRegInfo()),
TII(MF->getSubtarget().getInstrInfo()),
TRI(MF->getSubtarget().getRegisterInfo()),
TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb),
InsertPos(insertpos) {}
| 40.376784 | 86 | 0.644099 | kpdev |
c8b1a3fde2fbebc557f9dc5d91f7685f204a4aea | 1,819 | cpp | C++ | bench/detail/arp_cache.cpp | andreimaximov/unet | 10b6aa82b1ce74fa40c9050f4593c902f9d0fd61 | [
"MIT"
] | null | null | null | bench/detail/arp_cache.cpp | andreimaximov/unet | 10b6aa82b1ce74fa40c9050f4593c902f9d0fd61 | [
"MIT"
] | null | null | null | bench/detail/arp_cache.cpp | andreimaximov/unet | 10b6aa82b1ce74fa40c9050f4593c902f9d0fd61 | [
"MIT"
] | null | null | null | #include <cstdint>
#include <cstring>
#include <vector>
#include <benchmark/benchmark.h>
#include <unet/detail/arp_cache.hpp>
#include <unet/random.hpp>
namespace unet {
namespace detail {
constexpr auto kNumAddOps = 65'536;
static Ipv4Addr randomIpv4(std::uint32_t maxAddress) {
auto raw = randInt<std::uint32_t>(0, maxAddress);
Ipv4Addr addr;
std::memcpy(&addr, &raw, sizeof(raw));
return addr;
}
static std::vector<Ipv4Addr> randomIpv4s(std::uint32_t maxAddress) {
std::vector<Ipv4Addr> addresses;
while (addresses.size() < kNumAddOps) {
addresses.push_back(randomIpv4(maxAddress));
}
return addresses;
}
static void benchArpCacheAdd(benchmark::State& state) {
auto capacity = static_cast<std::size_t>(state.range(0));
ArpCache cache{capacity, std::chrono::seconds{60}};
auto maxAddress = static_cast<std::uint32_t>(state.range(1));
auto addresses = randomIpv4s(maxAddress);
for (auto _ : state) {
for (auto addr : addresses) {
cache.add(addr, EthernetAddr{});
}
}
}
static void benchArpCacheLookup(benchmark::State& state) {
auto capacity = static_cast<std::size_t>(state.range(0));
ArpCache cache{capacity, std::chrono::seconds{60}};
auto maxAddress = static_cast<std::uint32_t>(state.range(1));
auto addresses = randomIpv4s(maxAddress);
for (auto addr : addresses) {
cache.add(addr, EthernetAddr{});
}
for (auto _ : state) {
for (auto addr : addresses) {
benchmark::DoNotOptimize(cache.lookup(addr));
}
}
}
BENCHMARK(benchArpCacheAdd)
->RangeMultiplier(64)
->Ranges({{64, 4'096}, {64, 4'096}})
->Unit(benchmark::kMicrosecond);
BENCHMARK(benchArpCacheLookup)
->RangeMultiplier(64)
->Ranges({{64, 4'096}, {64, 4'096}})
->Unit(benchmark::kMicrosecond);
} // namespace detail
} // namespace unet
| 24.917808 | 68 | 0.68884 | andreimaximov |
c8b1ef2a5feeef249c7990679a390318eb0bdfd2 | 40,167 | cpp | C++ | MSVC/14.24.28314/atlmfc/src/mfc/olecli2.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 2 | 2021-01-27T10:19:30.000Z | 2021-02-09T06:24:30.000Z | MSVC/14.24.28314/atlmfc/src/mfc/olecli2.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | null | null | null | MSVC/14.24.28314/atlmfc/src/mfc/olecli2.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 1 | 2021-01-27T10:19:36.000Z | 2021-01-27T10:19:36.000Z | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#define new DEBUG_NEW
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook Construction & Destruction
COleFrameHook::COleFrameHook(CFrameWnd* pFrameWnd, COleClientItem* pItem)
{
ASSERT_VALID(pItem);
ASSERT_VALID(pFrameWnd);
m_lpActiveObject = NULL;
m_pActiveItem = pItem;
m_pFrameWnd = pFrameWnd;
m_hWnd = pFrameWnd->m_hWnd;
m_bToolBarHidden = FALSE;
m_hAccelTable = NULL;
m_bInModalState = FALSE;
m_nModelessCount = 0;
pFrameWnd->m_pNotifyHook = this; // assume start out hooked
ASSERT_VALID(this);
}
COleFrameHook::~COleFrameHook()
{
if (m_pFrameWnd != NULL)
{
ASSERT_VALID(m_pFrameWnd);
if (m_pFrameWnd->m_pNotifyHook == this)
m_pFrameWnd->m_pNotifyHook = NULL;
}
ASSERT_VALID(this);
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook overrides
void COleFrameHook::OnRecalcLayout()
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL)
return;
// get current border size (without current server control bars)
RECT rectBorder;
m_pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderGet, &rectBorder);
// allow server to resize/move its control bars
m_lpActiveObject->ResizeBorder(&rectBorder, &m_xOleInPlaceFrame,
m_pActiveItem->m_pInPlaceFrame == this);
}
BOOL COleFrameHook::OnDocActivate(BOOL bActive)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL)
return TRUE;
// allow server to do document activation related actions
m_lpActiveObject->OnDocWindowActivate(bActive);
// make sure window caption gets updated later
COleFrameHook* pNotifyHook = m_pActiveItem->m_pInPlaceFrame;
pNotifyHook->m_pFrameWnd->DelayUpdateFrameTitle();
if (!bActive)
{
// clear border space
pNotifyHook->m_xOleInPlaceFrame.SetBorderSpace(NULL);
if (m_pActiveItem->m_pInPlaceDoc != NULL)
m_pActiveItem->m_pInPlaceDoc->m_xOleInPlaceFrame.SetBorderSpace(NULL);
// remove the menu hook when the doc is not active
pNotifyHook->m_xOleInPlaceFrame.SetMenu(NULL, NULL, NULL);
// unhook top-level frame if not needed
if (pNotifyHook != this)
{
// shouldn't be removing some other hook
ASSERT(pNotifyHook->m_pFrameWnd->m_pNotifyHook == pNotifyHook);
pNotifyHook->m_pFrameWnd->m_pNotifyHook = NULL;
}
}
else
{
// rehook top-level frame if necessary (no effect if top-level == doc-level)
pNotifyHook->m_pFrameWnd->m_pNotifyHook = pNotifyHook;
}
// don't do default if activating
return bActive;
}
BOOL COleFrameHook::OnContextHelp(BOOL bEnter)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return TRUE;
// allow all servers to enter/exit context sensitive help mode
return NotifyAllInPlace(bEnter, &COleFrameHook::DoContextSensitiveHelp);
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook callbacks for the top-level frame
BOOL COleFrameHook::OnMenuSelect(UINT nItemID, UINT nFlags, HMENU hSysMenu)
{
UNUSED_ALWAYS(nFlags);
UNUSED_ALWAYS(nItemID);
// if we're over a docobject item, we need to reflect messages
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
CWnd* pWnd = pActiveDocObjectItem->GetInPlaceWindow();
// if we're popping up a menu, figure out what menu is
// apparing; if it's in the help menu and it's not the
// first element, it's the object's menu.
if (nFlags & MF_POPUP)
{
if (pActiveDocObjectItem->m_pHelpPopupMenu->GetSafeHmenu() ==
hSysMenu)
{
pActiveDocObjectItem->m_bInHelpMenu = (nItemID != 0);
if (pActiveDocObjectItem->m_bInHelpMenu && pWnd != NULL)
{
pWnd->SendMessage(WM_MENUSELECT,
MAKEWPARAM(nItemID, nFlags), (LPARAM) hSysMenu);
return TRUE;
}
}
}
else
{
if (pActiveDocObjectItem->m_bInHelpMenu && pWnd != NULL)
{
pWnd->SendMessage(WM_MENUSELECT,
MAKEWPARAM(nItemID, nFlags), (LPARAM) hSysMenu);
return TRUE;
}
}
}
return FALSE;
}
void COleFrameHook::OnInitMenu(CMenu* pMenu)
{
UNUSED_ALWAYS(pMenu);
// reset the help menu flag when a new menu is opening
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem != NULL)
pActiveDocObjectItem->m_bInHelpMenu = FALSE;
return;
}
BOOL COleFrameHook::OnInitMenuPopup(CMenu* pMenu, int nIndex, BOOL bSysMenu)
{
UNUSED_ALWAYS(nIndex);
if (bSysMenu)
return FALSE;
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem == NULL)
return FALSE;
// if we're popping up a new menu, for the object,
// reflect the message and don't let MFC handle it
// with ON_COMMAND_UI stuff
if (pActiveDocObjectItem->m_bInHelpMenu)
{
CWnd* pWnd = pActiveDocObjectItem->GetInPlaceWindow();
if (pWnd != NULL)
{
pWnd->SendMessage(WM_INITMENUPOPUP, (WPARAM) pMenu->m_hMenu,
MAKELPARAM(nIndex, bSysMenu));
return TRUE;
}
}
return FALSE;
}
BOOL COleFrameHook::OnPreTranslateMessage(MSG* pMsg)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return FALSE;
// allow server to translate accelerators
if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST)
return m_lpActiveObject->TranslateAccelerator(pMsg) == S_OK;
// if we've finally gotten a WM_COMMAND message, make sure
// that it is appropriately reflected to the docobject
if (pMsg->message == WM_COMMAND)
{
COleDocObjectItem* pActiveDocObjectItem = DYNAMIC_DOWNCAST(COleDocObjectItem, m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
LRESULT lResult = 0;
if (pActiveDocObjectItem->m_bInHelpMenu)
{
CWnd* pWnd = pActiveDocObjectItem->GetInPlaceWindow();
if (pWnd != NULL)
lResult = pWnd->SendNotifyMessage(WM_COMMAND, pMsg->wParam, pMsg->lParam);
}
return (lResult != 0);
}
}
return FALSE;
}
void COleFrameHook::OnActivate(BOOL bActive)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return;
if (m_pFrameWnd->IsWindowEnabled())
{
// allow active server to do frame level activation
m_lpActiveObject->OnFrameWindowActivate(bActive);
}
}
void COleFrameHook::OnEnableModeless(BOOL bEnable)
{
ASSERT_VALID(this);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return;
// allow server to disable/enable modeless dialogs
NotifyAllInPlace(bEnable, &COleFrameHook::DoEnableModeless);
}
BOOL COleFrameHook::OnUpdateFrameTitle()
{
ASSERT_VALID(this);
ASSERT_VALID(m_pActiveItem);
if (m_lpActiveObject == NULL || m_pActiveItem->m_pInPlaceFrame != this)
return FALSE;
return m_pActiveItem->OnUpdateFrameTitle();
}
void COleFrameHook::OnPaletteChanged(CWnd* pFocusWnd)
{
CWnd* pWnd = m_pActiveItem->GetInPlaceWindow();
if (pWnd != NULL)
pWnd->SendMessage(WM_PALETTECHANGED, (WPARAM)pFocusWnd->GetSafeHwnd());
}
BOOL COleFrameHook::OnQueryNewPalette()
{
CWnd* pWnd = m_pActiveItem->GetInPlaceWindow();
if (pWnd != NULL)
return (pWnd->SendMessage(WM_QUERYNEWPALETTE) != 0);
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// Helpers for notifications that have to affect all in-place windows
BOOL COleFrameHook::NotifyAllInPlace(
BOOL bParam, BOOL (COleFrameHook::*pNotifyFunc)(BOOL bParam))
{
ASSERT_VALID(this);
HWND hWndFrame = m_hWnd;
CWinApp* pApp = AfxGetApp();
// no doc manager - no templates
if (pApp->m_pDocManager == NULL)
return TRUE;
// walk all templates in the application
CDocTemplate* pTemplate;
POSITION pos = pApp->m_pDocManager->GetFirstDocTemplatePosition();
while (pos != NULL)
{
pTemplate = pApp->m_pDocManager->GetNextDocTemplate(pos);
ASSERT_VALID(pTemplate);
ASSERT_KINDOF(CDocTemplate, pTemplate);
// walk all documents in the template
POSITION pos2 = pTemplate->GetFirstDocPosition();
while (pos2)
{
COleDocument* pDoc = (COleDocument*)pTemplate->GetNextDoc(pos2);
ASSERT_VALID(pDoc);
if (pDoc->IsKindOf(RUNTIME_CLASS(COleDocument)))
{
// walk all COleClientItem objects in the document
COleClientItem* pItem;
POSITION pos3 = pDoc->GetStartPosition();
while ((pItem = pDoc->GetNextClientItem(pos3)) != NULL)
{
if (pItem->m_pInPlaceFrame != NULL &&
pItem->m_pInPlaceFrame->m_lpActiveObject != NULL &&
pItem->m_pView != NULL &&
AfxIsDescendant(hWndFrame, pItem->m_pView->m_hWnd))
{
// Whew! Found an in-place active item that is
// part of this frame window hierarchy.
COleFrameHook* pNotifyHook = pItem->m_pInPlaceFrame;
if (!(pNotifyHook->*pNotifyFunc)(bParam))
return FALSE;
}
}
}
}
}
return TRUE;
}
BOOL COleFrameHook::DoContextSensitiveHelp(BOOL bEnter)
{
ASSERT_VALID(this);
ASSERT(m_lpActiveObject != NULL);
return !FAILED(m_lpActiveObject->ContextSensitiveHelp(bEnter));
}
BOOL COleFrameHook::DoEnableModeless(BOOL bEnable)
{
ASSERT_VALID(this);
ASSERT(m_lpActiveObject != NULL);
// allow server to enable/disable any modeless windows
if (!bEnable)
{
if (m_nModelessCount++ == 0)
m_lpActiveObject->EnableModeless(FALSE);
}
else
{
if (m_nModelessCount != 0 && --m_nModelessCount == 0)
m_lpActiveObject->EnableModeless(TRUE);
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// COleClientItem - default in-place activation implementation
BOOL COleClientItem::CanActivate()
{
// don't allow in-place activations with iconic aspect items
if (m_nDrawAspect == DVASPECT_ICON)
{
return FALSE;
}
// if no view has been set, attempt to find suitable one.
// (necessary to get links to embeddings to work correctly)
if (m_pView == NULL)
{
// only use pActivateView if this item is in same document
_AFX_OLE_STATE* pOleState = _afxOleState;
if (pOleState->m_pActivateView != NULL && pOleState->m_pActivateView->GetDocument() != GetDocument())
{
pOleState->m_pActivateView = NULL; // not in same document
}
CView* pView = pOleState->m_pActivateView;
if (pView == NULL)
{
// no routing view available - try to use the one with focus
CWnd* pWnd = CWnd::GetFocus();
while (pWnd != NULL && !pWnd->IsKindOf(RUNTIME_CLASS(CView)))
{
pWnd = pWnd->GetParent();
}
pView = STATIC_DOWNCAST(CView, pWnd);
if (pView == NULL)
{
// still no routing view available - just use first one
COleDocument* pDoc = GetDocument();
POSITION pos = pDoc->GetFirstViewPosition();
pView = pDoc->GetNextView(pos);
}
}
m_pView = pView;
}
return m_pView->GetSafeHwnd() != NULL;
}
void COleClientItem::OnActivate()
{
ASSERT_VALID(this);
// it is necessary to lock the object when it is in-place
// (without this, a link to an embedding may disconnect unexpectedly)
if (!m_bLocked)
{
OleLockRunning(m_lpObject, TRUE, FALSE);
m_bLocked = TRUE;
}
// notify the item of the state change
if (m_nItemState != activeState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)activeState);
m_nItemState = activeState;
}
}
void COleClientItem::OnActivateUI()
{
ASSERT_VALID(this);
CFrameWnd* pMainFrame;
CFrameWnd* pDocFrame = NULL;
if (OnGetWindowContext(&pMainFrame, &pDocFrame, NULL))
{
m_dwFrameMenuBarVisibility = pMainFrame->GetMenuBarVisibility();
pMainFrame->SetMenuBarVisibility(AFX_MBV_KEEPVISIBLE);
}
// notify the item of the state change
if (m_nItemState != activeUIState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)activeUIState);
m_nItemState = activeUIState;
}
// the container window must have WS_CLIPCHILDREN set
ASSERT_VALID(m_pView);
m_dwContainerStyle = m_pView->GetStyle();
m_pView->ModifyStyle(0, WS_CLIPCHILDREN);
// cache the server's HWND for later
LPOLEINPLACEOBJECT lpInPlaceObject = QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
ASSERT(lpInPlaceObject != NULL);
// get the HWND for the in-place active object
HWND hWnd;
if (lpInPlaceObject->GetWindow(&hWnd) != S_OK)
{
hWnd = NULL;
}
lpInPlaceObject->Release();
m_hWndServer = hWnd;
// make sure top-level frame is hooked
if (m_pInPlaceFrame != NULL)
{
ASSERT_VALID(m_pInPlaceFrame->m_pFrameWnd);
m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook = m_pInPlaceFrame;
}
// make sure doc-level frame is hooked
if (m_pInPlaceDoc != NULL)
{
ASSERT_VALID(m_pInPlaceDoc->m_pFrameWnd);
m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook = m_pInPlaceDoc;
}
}
BOOL COleClientItem::OnShowControlBars(CFrameWnd* pFrameWnd, BOOL bShow)
{
ASSERT_VALID(pFrameWnd);
ASSERT_VALID(this);
// show/hide all bars marked with CBRS_HIDE_INPLACE style
BOOL bResult = FALSE;
if (bShow)
{
POSITION pos = pFrameWnd->m_listControlBars.GetHeadPosition();
while (pos)
{
CControlBar* pBar =
(CControlBar*)pFrameWnd->m_listControlBars.GetNext(pos);
ASSERT_VALID(pBar);
if ((pBar->GetBarStyle() & CBRS_HIDE_INPLACE) &&
(pBar->m_nStateFlags & CControlBar::tempHide))
{
pBar->m_nStateFlags &= ~CControlBar::tempHide;
pFrameWnd->ShowControlBar(pBar, TRUE, TRUE);
bResult = TRUE;
}
}
}
else
{
POSITION pos = pFrameWnd->m_listControlBars.GetHeadPosition();
while (pos)
{
CControlBar* pBar =
(CControlBar*)pFrameWnd->m_listControlBars.GetNext(pos);
ASSERT_VALID(pBar);
if (pBar->IsVisible() && (pBar->GetBarStyle() & CBRS_HIDE_INPLACE))
{
pBar->m_nStateFlags |= CControlBar::tempHide;
pFrameWnd->ShowControlBar(pBar, FALSE, TRUE);
bResult = TRUE;
}
}
}
return bResult;
}
BOOL COleClientItem::OnGetWindowContext(CFrameWnd** ppMainFrame, CFrameWnd** ppDocFrame, LPOLEINPLACEFRAMEINFO pFrameInfo)
{
ASSERT(AfxIsValidAddress(ppMainFrame, sizeof(CFrameWnd*)));
ASSERT(AfxIsValidAddress(ppDocFrame, sizeof(CFrameWnd*)));
ASSERT(pFrameInfo == NULL || AfxIsValidAddress(pFrameInfo, sizeof(OLEINPLACEFRAMEINFO)));
ASSERT_VALID(this);
ASSERT_VALID(m_pView);
if ((ppMainFrame == NULL) || (ppDocFrame == NULL))
{
return E_POINTER;
}
// get main window of application
*ppMainFrame = m_pView->GetTopLevelFrame();
ENSURE_VALID(*ppMainFrame);
ASSERT_KINDOF(CFrameWnd, *ppMainFrame);
// get document window (if there is one)
CFrameWnd* pDocFrame = m_pView->GetParentFrame();
if (pDocFrame != *ppMainFrame)
{
*ppDocFrame = pDocFrame;
ASSERT_VALID(*ppDocFrame);
ASSERT_KINDOF(CFrameWnd, *ppDocFrame);
}
if (pFrameInfo != NULL)
{
// get accelerator table
CDocTemplate* pTemplate = GetDocument()->GetDocTemplate();
HACCEL hAccel = pTemplate != NULL ? pTemplate->m_hAccelInPlace : NULL;
pFrameInfo->cAccelEntries =
hAccel != NULL ? CopyAcceleratorTable(hAccel, NULL, 0) : 0;
pFrameInfo->haccel = pFrameInfo->cAccelEntries != 0 ? hAccel : NULL;
pFrameInfo->hwndFrame = (*ppMainFrame)->m_hWnd;
pFrameInfo->fMDIApp = *ppDocFrame != NULL;
}
return TRUE;
}
BOOL COleClientItem::OnScrollBy(CSize sizeExtent)
{
ASSERT_VALID(this);
ASSERT_VALID(m_pView);
// scroll through splitter or view
CSplitterWnd* pSplitter = CView::GetParentSplitter(m_pView, FALSE);
BOOL bResult;
if (pSplitter != NULL)
bResult = pSplitter->DoScrollBy(m_pView, sizeExtent);
else
bResult = m_pView->OnScrollBy(sizeExtent);
return bResult;
}
void COleClientItem::OnDeactivateUI(BOOL /*bUndoable*/)
{
ASSERT_VALID(this);
// notify the item of the state change
if (m_nItemState != activeState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)activeState);
m_nItemState = activeState;
}
if (m_pView != NULL && m_pDocument->GetFirstViewPosition())
{
// restore container window's WS_CLIPCHILDREN bit...
ASSERT_VALID(m_pView);
m_pView->ModifyStyle(WS_CLIPCHILDREN, m_dwContainerStyle & WS_CLIPCHILDREN);
}
// restore original user interface on the frame window
CFrameWnd* pMainFrame;
CFrameWnd* pDocFrame = NULL;
if (OnGetWindowContext(&pMainFrame, &pDocFrame, NULL))
{
ENSURE(pMainFrame->GetMenuBarVisibility() == AFX_MBV_KEEPVISIBLE);
pMainFrame->SetMenuBarVisibility(m_dwFrameMenuBarVisibility);
ASSERT_VALID(pMainFrame);
pMainFrame->DelayUpdateFrameTitle();
if (pMainFrame->NegotiateBorderSpace(CFrameWnd::borderSet, NULL))
pMainFrame->DelayRecalcLayout();
// restore original user interface on the document window
if (pDocFrame != NULL)
{
pDocFrame->DelayUpdateFrameTitle();
if (pDocFrame->NegotiateBorderSpace(CFrameWnd::borderSet, NULL))
pDocFrame->DelayRecalcLayout();
}
}
// cleanup frame interfaces allocated in GetWindowContext
if (m_pInPlaceFrame != NULL)
{
OnShowControlBars(m_pInPlaceFrame->m_pFrameWnd, TRUE);
// release OLE frame window hooks and allow menu update
::OleSetMenuDescriptor(NULL, m_pInPlaceFrame->m_pFrameWnd->m_hWnd,
NULL, NULL, NULL);
if (m_pInPlaceDoc != NULL)
{
::OleSetMenuDescriptor(NULL, m_pInPlaceDoc->m_pFrameWnd->m_hWnd,
NULL, NULL, NULL);
}
m_pInPlaceFrame->m_pFrameWnd->DelayUpdateFrameMenu(NULL);
// unhook from frame window
if (m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook == m_pInPlaceFrame)
m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook = NULL;
// cleanup document interfaces allocated in GetWindowContext
if (m_pInPlaceDoc != NULL)
{
OnShowControlBars(m_pInPlaceDoc->m_pFrameWnd, TRUE);
// unhook from frame window
if (m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook == m_pInPlaceDoc)
m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook = NULL;
}
}
// reset server HWND -- no longer necessary
m_hWndServer = NULL;
CWnd* pWnd = AfxGetMainWnd();
if (pWnd != NULL)
{
// set focus back to the container
pWnd = pWnd->EnsureTopLevelParent();
if (::GetActiveWindow() == pWnd->m_hWnd)
{
pWnd->SetFocus();
}
}
}
void COleClientItem::OnDeactivate()
{
ASSERT_VALID(this);
// notify the item of the state change
if (m_nItemState != loadedState)
{
OnChange(OLE_CHANGED_STATE, (DWORD)loadedState);
m_nItemState = loadedState;
}
// cleanup frame interfaces allocated in GetWindowContext
if (m_pInPlaceFrame != NULL)
{
// release in place frame
if (m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook == m_pInPlaceFrame)
{
m_pInPlaceFrame->m_pFrameWnd->m_pNotifyHook = NULL;
m_pInPlaceFrame->m_pFrameWnd = NULL;
}
m_pInPlaceFrame->InternalRelease();
m_pInPlaceFrame = NULL;
// cleanup document interfaces allocated in GetWindowContext
if (m_pInPlaceDoc != NULL)
{
// release in place document
if (m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook == m_pInPlaceDoc)
{
m_pInPlaceDoc->m_pFrameWnd->m_pNotifyHook = NULL;
m_pInPlaceDoc->m_pFrameWnd = NULL;
}
m_pInPlaceDoc->InternalRelease();
m_pInPlaceDoc = NULL;
}
}
// both frame-level and doc-level interfaces should be cleaned up
ASSERT(m_pInPlaceFrame == NULL);
ASSERT(m_pInPlaceDoc == NULL);
// no longer need the container window
m_pView = NULL;
}
void COleClientItem::OnDiscardUndoState()
{
ASSERT_VALID(this);
// default does nothing
}
void COleClientItem::OnDeactivateAndUndo()
{
ASSERT_VALID(this);
DeactivateUI(); // default is to UI deactivate
}
BOOL COleClientItem::OnChangeItemPosition(const CRect& rectPos)
{
if (!IsInPlaceActive())
return FALSE;
ASSERT_VALID(this);
ASSERT(AfxIsValidAddress(&rectPos, sizeof(CRect), FALSE));
ASSERT_VALID(m_pView);
// determine the visible rect based on intersection between client rect
CRect clipRect;
OnGetClipRect(clipRect);
CRect visRect;
visRect.IntersectRect(clipRect, rectPos);
// advise the server of the new visible rectangle
if (!visRect.IsRectEmpty())
return SetItemRects(&rectPos, &clipRect);
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// IOleInPlaceFrame notifications (default implementation)
void COleClientItem::OnInsertMenus(CMenu* pMenuShared,
LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
ASSERT_VALID(this);
ASSERT_VALID(pMenuShared);
ASSERT(AfxIsValidAddress(lpMenuWidths, sizeof(OLEMENUGROUPWIDTHS)));
// initialize the group widths array
lpMenuWidths->width[0] = 0;
lpMenuWidths->width[2] = 0;
lpMenuWidths->width[4] = 0;
// get menu from document template
CDocTemplate* pTemplate = GetDocument()->GetDocTemplate();
HMENU hMenuOLE = pTemplate->m_hMenuInPlace;
// only copy the popups if there is a menu loaded
if (hMenuOLE == NULL)
return;
// insert our menu items and adjust group widths array
AfxMergeMenus(pMenuShared->GetSafeHmenu(), hMenuOLE, &lpMenuWidths->width[0], 0);
}
void COleClientItem::OnSetMenu(CMenu* pMenuShared, HOLEMENU holemenu,
HWND hwndActiveObject)
{
ASSERT_VALID(this);
ASSERT(m_pInPlaceFrame != NULL);
ASSERT(m_pInPlaceFrame->m_pFrameWnd != NULL);
// don't set the doc is active
CFrameWnd* pFrameWnd = m_pInPlaceFrame->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
if (m_pInPlaceDoc != NULL &&
m_pInPlaceDoc->m_pFrameWnd != pFrameWnd->GetActiveFrame())
{
return;
}
// update the menu
pFrameWnd->DelayUpdateFrameMenu(pMenuShared->GetSafeHmenu());
// enable/disable the OLE command routing hook
::OleSetMenuDescriptor(holemenu, pFrameWnd->m_hWnd,
hwndActiveObject, NULL, NULL);
if (m_pInPlaceDoc != NULL)
{
pFrameWnd = m_pInPlaceDoc->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
::OleSetMenuDescriptor(holemenu, pFrameWnd->m_hWnd,
hwndActiveObject, NULL, NULL);
}
}
void COleClientItem::OnRemoveMenus(CMenu* pMenuShared)
{
ASSERT_VALID(this);
ASSERT_VALID(pMenuShared);
// get menu from document template
CDocTemplate* pTemplate = GetDocument()->GetDocTemplate();
HMENU hMenuOLE = pTemplate->m_hMenuInPlace;
if (hMenuOLE == NULL)
return;
// remove any menu popups originally added in OnInsertMenus
AfxUnmergeMenus(pMenuShared->GetSafeHmenu(), hMenuOLE);
}
BOOL COleClientItem::OnUpdateFrameTitle()
{
ASSERT_VALID(this);
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// In-place Activation operations
void COleClientItem::Deactivate()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(IsInPlaceActive());
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
{
Close(); // handle rare failure cases by calling Close
return;
}
// call IOleInPlaceObject::InPlaceDeactivate
m_scLast = lpInPlaceObject->InPlaceDeactivate();
lpInPlaceObject->Release();
if (FAILED(m_scLast))
{
Close(); // handle rare failure cases by calling Close
return;
}
m_nItemState = loadedState; // just in case server has crashed
}
void COleClientItem::DeactivateUI()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(GetItemState() == activeUIState);
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
{
Close(); // handle rare failure cases by calling Close
return;
}
// call IOleInPlaceObject::UIDeactivate
m_scLast = lpInPlaceObject->UIDeactivate();
lpInPlaceObject->Release();
if (FAILED(m_scLast))
{
Close(); // handle rare failure cases by calling Close
return;
}
if (m_nItemState == activeUIState)
m_nItemState = activeState; // just in case server has crashed
}
BOOL COleClientItem::SetItemRects(LPCRECT lpPosRect, LPCRECT lpClipRect)
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(IsInPlaceActive());
ASSERT(lpPosRect == NULL ||
AfxIsValidAddress(lpPosRect, sizeof(RECT), FALSE));
ASSERT(lpClipRect == NULL ||
AfxIsValidAddress(lpClipRect, sizeof(RECT), FALSE));
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
return FALSE; // perhaps server crashed?
// use OnGetPosRect if rectangle not specified
CRect rectPos;
if (lpPosRect == NULL)
{
ASSERT(lpClipRect == NULL);
OnGetItemPosition(rectPos);
lpPosRect = &rectPos;
}
// use OnGetClipRect if clipping rectangle not specified
CRect rectClip;
if (lpClipRect == NULL)
{
OnGetClipRect(rectClip);
lpClipRect = &rectClip;
}
ASSERT(lpPosRect != NULL);
ASSERT(lpClipRect != NULL);
// notify the server of the new item rectangles
m_scLast = lpInPlaceObject->SetObjectRects(lpPosRect, lpClipRect);
lpInPlaceObject->Release();
// remember position rectangle as cached position
return !FAILED(m_scLast);
}
BOOL COleClientItem::ReactivateAndUndo()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
ASSERT(IsInPlaceActive());
// get IOleInPlaceObject interface
LPOLEINPLACEOBJECT lpInPlaceObject =
QUERYINTERFACE(m_lpObject, IOleInPlaceObject);
if (lpInPlaceObject == NULL)
{
Close(); // handle rare failure cases by calling Close
return FALSE;
}
// call IOleInPlaceObject::ReactivateAndUndo
m_scLast = lpInPlaceObject->ReactivateAndUndo();
lpInPlaceObject->Release();
if (FAILED(m_scLast))
{
Close(); // handle rare failure cases by calling Close
return FALSE;
}
return TRUE;
}
CWnd* COleClientItem::GetInPlaceWindow()
{
ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
// only inplace active items should be asking for the window handle
if (GetItemState() != activeUIState)
return NULL;
// handle case of server that just disappears
if (m_hWndServer != NULL && !::IsWindow(m_hWndServer))
{
Close();
return NULL;
}
ASSERT(m_hWndServer == NULL || ::IsWindow(m_hWndServer));
return CWnd::FromHandle(m_hWndServer);
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook OLE interface implementation
BEGIN_INTERFACE_MAP(COleFrameHook, CCmdTarget)
INTERFACE_PART(COleFrameHook, IID_IOleWindow, OleInPlaceFrame)
INTERFACE_PART(COleFrameHook, IID_IOleInPlaceUIWindow, OleInPlaceFrame)
INTERFACE_PART(COleFrameHook, IID_IOleInPlaceFrame, OleInPlaceFrame)
INTERFACE_PART(COleFrameHook, IID_IOleCommandTarget, OleCommandTarget)
END_INTERFACE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook::XOleCommandTarget implementation
STDMETHODIMP_(ULONG) COleFrameHook::XOleCommandTarget::AddRef()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleFrameHook::XOleCommandTarget::Release()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
return pThis->ExternalRelease();
}
STDMETHODIMP COleFrameHook::XOleCommandTarget::QueryInterface(
REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP COleFrameHook::XOleCommandTarget::Exec(
const GUID* pguidCmdGroup, DWORD nCmdID, DWORD nCmdExecOpt,
VARIANTARG* pvarargIn, VARIANTARG* pvarargOut)
{
HRESULT hResult = OLECMDERR_E_UNKNOWNGROUP;
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
COleDocObjectItem* pActiveDocObjectItem =
DYNAMIC_DOWNCAST(COleDocObjectItem, pThis->m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
hResult = _AfxExecOleCommandHelper(pActiveDocObjectItem,
pguidCmdGroup, nCmdID, nCmdExecOpt, pvarargIn, pvarargOut);
}
return hResult;
}
STDMETHODIMP COleFrameHook::XOleCommandTarget::QueryStatus(
const GUID* pguidCmdGroup, ULONG cCmds, OLECMD rgCmds[],
OLECMDTEXT* pcmdtext)
{
HRESULT hResult = OLECMDERR_E_UNKNOWNGROUP;
METHOD_PROLOGUE_EX_(COleFrameHook, OleCommandTarget)
COleDocObjectItem* pActiveDocObjectItem =
DYNAMIC_DOWNCAST(COleDocObjectItem, pThis->m_pActiveItem);
if (pActiveDocObjectItem != NULL)
{
hResult = _AfxQueryStatusOleCommandHelper(pActiveDocObjectItem,
pguidCmdGroup, cCmds, rgCmds, pcmdtext);
}
return hResult;
}
/////////////////////////////////////////////////////////////////////////////
// COleFrameHook::XOleInPlaceFrame implementation
STDMETHODIMP_(ULONG) COleFrameHook::XOleInPlaceFrame::AddRef()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleFrameHook::XOleInPlaceFrame::Release()
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
return pThis->ExternalRelease();
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::QueryInterface(
REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::GetWindow(HWND* lphwnd)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
if (lphwnd == NULL)
{
return E_POINTER;
}
*lphwnd = pThis->m_hWnd;
return *lphwnd != NULL ? S_OK : E_FAIL;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::ContextSensitiveHelp(
BOOL fEnterMode)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// document frame windows should not be put in help mode, so we get the
// top-level frame window and check it first
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd->GetTopLevelFrame();
ENSURE_VALID(pFrameWnd);
if (fEnterMode)
{
if (!pFrameWnd->m_bHelpMode)
{
// check if help mode probable
if (!pFrameWnd->CanEnterHelpMode())
return E_UNEXPECTED;
// attempt to enter context help
if (!pThis->OnContextHelp(TRUE) ||
!pFrameWnd->PostMessage(WM_COMMAND, ID_CONTEXT_HELP))
{
return E_UNEXPECTED;
}
}
}
else
{
// just exit help mode
pFrameWnd->ExitHelpMode();
}
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::GetBorder(LPRECT lpRectBorder)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
// hide the control bars temporarily
BOOL bHidden = pItem->OnShowControlBars(pFrameWnd, FALSE);
// determine border space assuming that we'll remove our control bars
CRect rectSave = pFrameWnd->m_rectBorder;
pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderSet, NULL);
pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderGet, lpRectBorder);
pFrameWnd->NegotiateBorderSpace(CFrameWnd::borderSet, &rectSave);
// restore control bars
if (bHidden)
pItem->OnShowControlBars(pFrameWnd, TRUE);
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::RequestBorderSpace(
LPCRECT lpRectWidths)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
ASSERT_VALID(pFrameWnd);
if (!pFrameWnd->NegotiateBorderSpace(
CFrameWnd::borderRequest, (LPRECT)lpRectWidths))
{
return INPLACE_E_NOTOOLSPACE;
}
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetBorderSpace(
LPCRECT lpRectWidths)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
if (pFrameWnd->NegotiateBorderSpace(
CFrameWnd::borderSet, (LPRECT)lpRectWidths))
{
// We have to turn off the notify and idlelayout flags so RecalcLayout
// doesn't call back into the object and tell it to resize it's borders
// while we are in the middle of setting the border space.
pFrameWnd->m_nIdleFlags &= ~(CFrameWnd::idleLayout|CFrameWnd::idleNotify);
// synchronously re-layout borders.
pFrameWnd->RecalcLayout(FALSE);
}
pThis->m_pActiveItem->OnShowControlBars(pFrameWnd, lpRectWidths == NULL);
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetActiveObject(
LPOLEINPLACEACTIVEOBJECT lpActiveObject, LPCOLESTR lpszObjName)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
// release the old active object
RELEASE(pThis->m_lpActiveObject);
// set the new active object
pThis->m_lpActiveObject = lpActiveObject;
if (lpActiveObject != NULL)
lpActiveObject->AddRef();
// update caption if necessary
pThis->m_strObjName.Empty();
if (lpszObjName != NULL && lpActiveObject != NULL)
{
pThis->m_strObjName = lpszObjName;
pThis->m_pActiveItem->OnUpdateFrameTitle();
}
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::InsertMenus(
HMENU hmenuShared, LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// get the associated COleClientItem object
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
SCODE sc = E_UNEXPECTED;
TRY
{
pItem->OnInsertMenus(CMenu::FromHandle(hmenuShared), lpMenuWidths);
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetMenu(
HMENU hmenuShared, HOLEMENU holemenu, HWND hwndActiveObject)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// get the associated COleClientItem object
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
SCODE sc = E_UNEXPECTED;
TRY
{
pItem->OnSetMenu(CMenu::FromHandle(hmenuShared), holemenu,
hwndActiveObject);
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::RemoveMenus(
HMENU hmenuShared)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
// get the associated COleClientItem object
COleClientItem* pItem = pThis->m_pActiveItem;
ASSERT_VALID(pItem);
SCODE sc = E_UNEXPECTED;
TRY
{
pItem->OnRemoveMenus(CMenu::FromHandle(hmenuShared));
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::SetStatusText(
LPCOLESTR lpszStatusText)
{
METHOD_PROLOGUE_EX_(COleFrameHook, OleInPlaceFrame)
LPARAM lParam;
CString strText;
if (lpszStatusText)
{
strText = lpszStatusText;
lParam = reinterpret_cast<LPARAM>(strText.GetString());
}
else
{
lParam = 0;
}
pThis->m_pFrameWnd->SendMessage(WM_SETMESSAGESTRING, 0, lParam);
return S_OK;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::EnableModeless(BOOL fEnable)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
ASSERT_VALID(pThis->m_pFrameWnd);
SCODE sc = E_UNEXPECTED;
TRY
{
if (!fEnable)
pThis->m_pFrameWnd->BeginModalState();
else
pThis->m_pFrameWnd->EndModalState();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleFrameHook::XOleInPlaceFrame::TranslateAccelerator(
LPMSG lpmsg, WORD /*wID*/)
{
METHOD_PROLOGUE_EX(COleFrameHook, OleInPlaceFrame)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
// swap accel tables and call PreTranslateMessage
CFrameWnd* pFrameWnd = pThis->m_pFrameWnd;
HACCEL hAccelSave = pFrameWnd->m_hAccelTable;
pFrameWnd->m_hAccelTable = pThis->m_hAccelTable;
ASSERT(lpmsg != NULL);
MSG msg = *lpmsg;
sc = pFrameWnd->PreTranslateMessage(&msg) ? S_OK : S_FALSE;
*lpmsg = msg;
pFrameWnd->m_hAccelTable = hAccelSave;
}
END_TRY
return sc;
}
/////////////////////////////////////////////////////////////////////////////
// COleClientItem::XOleIPSite implementation
STDMETHODIMP_(ULONG) COleClientItem::XOleIPSite::AddRef()
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) COleClientItem::XOleIPSite::Release()
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
return pThis->ExternalRelease();
}
STDMETHODIMP COleClientItem::XOleIPSite::QueryInterface(REFIID iid, LPVOID* ppvObj)
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP COleClientItem::XOleIPSite::GetWindow(HWND* lphwnd)
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
if (lphwnd == NULL)
{
return E_POINTER;
}
*lphwnd = pThis->m_pView->GetSafeHwnd();
return *lphwnd != NULL ? S_OK : E_FAIL;
}
STDMETHODIMP COleClientItem::XOleIPSite::ContextSensitiveHelp(
BOOL fEnterMode)
{
METHOD_PROLOGUE_EX_(COleClientItem, OleIPSite)
if (pThis->m_pInPlaceFrame == NULL)
return E_UNEXPECTED;
// simply delegate to frame window implementation
return pThis->m_pInPlaceFrame->
m_xOleInPlaceFrame.ContextSensitiveHelp(fEnterMode);
}
STDMETHODIMP COleClientItem::XOleIPSite::CanInPlaceActivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
return pThis->CanActivate() ? S_OK : S_FALSE;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnInPlaceActivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnActivate();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnUIActivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnActivateUI();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::GetWindowContext(LPOLEINPLACEFRAME* lplpFrame,
LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT lpPosRect, LPRECT lpClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
if ((lplpFrame == NULL) || (lplpDoc == NULL))
{
return E_POINTER;
}
*lplpFrame = NULL; // init these in-case of mem-alloc failure
*lplpDoc = NULL;
CFrameWnd* pMainFrame = NULL;
CFrameWnd* pDocFrame = NULL;
SCODE sc = E_UNEXPECTED;
TRY
{
// get position of the item relative to activation view
CRect rect;
pThis->OnGetItemPosition(rect);
::CopyRect(lpPosRect, &rect);
pThis->OnGetClipRect(rect);
::CopyRect(lpClipRect, &rect);
// get the window context information
if (pThis->OnGetWindowContext(&pMainFrame, &pDocFrame, lpFrameInfo))
{
// hook IOleInPlaceFrame interface to pMainFrame
if (pThis->m_pInPlaceFrame == NULL)
pThis->m_pInPlaceFrame = new COleFrameHook(pMainFrame, pThis);
pThis->m_pInPlaceFrame->InternalAddRef();
*lplpFrame = (LPOLEINPLACEFRAME)pThis->m_pInPlaceFrame->
GetInterface(&IID_IOleInPlaceFrame);
// save accel table for IOleInPlaceFrame::TranslateAccelerators
pThis->m_pInPlaceFrame->m_hAccelTable = lpFrameInfo->haccel;
// hook IOleInPlaceUIWindow to pDocFrame
if (pDocFrame != NULL)
{
if (pThis->m_pInPlaceDoc == NULL)
pThis->m_pInPlaceDoc = new COleFrameHook(pDocFrame, pThis);
pThis->m_pInPlaceDoc->InternalAddRef();
*lplpDoc = (LPOLEINPLACEUIWINDOW)pThis->m_pInPlaceDoc->
GetInterface(&IID_IOleInPlaceUIWindow);
}
sc = S_OK;
}
}
CATCH_ALL(e)
{
// cleanup memory that may be partially allocated
delete *lplpFrame;
ASSERT(*lplpDoc == NULL);
DELETE_EXCEPTION(e);
}
END_CATCH_ALL
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::Scroll(SIZE scrollExtent)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
if (!pThis->OnScrollBy(CSize(scrollExtent)))
sc = S_FALSE;
else
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnUIDeactivate(BOOL fUndoable)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDeactivateUI(fUndoable);
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnInPlaceDeactivate()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDeactivate();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::DiscardUndoState()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDiscardUndoState();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::DeactivateAndUndo()
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
pThis->OnDeactivateAndUndo();
sc = S_OK;
}
END_TRY
return sc;
}
STDMETHODIMP COleClientItem::XOleIPSite::OnPosRectChange(
LPCRECT lpPosRect)
{
METHOD_PROLOGUE_EX(COleClientItem, OleIPSite)
ASSERT_VALID(pThis);
SCODE sc = E_UNEXPECTED;
TRY
{
CRect rect;
rect.CopyRect(lpPosRect);
pThis->OnChangeItemPosition(rect);
sc = S_OK;
}
END_TRY
return sc;
}
/////////////////////////////////////////////////////////////////////////////
| 25.073034 | 122 | 0.72694 | 825126369 |
c8b24e8a164f685838c7c6a841320c461a1b60f9 | 6,505 | cpp | C++ | src/message.cpp | smallb/ucxxrt | 6f1fddae4f5eefb4e1ad36b7c9a1cd664caf2f26 | [
"MIT"
] | null | null | null | src/message.cpp | smallb/ucxxrt | 6f1fddae4f5eefb4e1ad36b7c9a1cd664caf2f26 | [
"MIT"
] | null | null | null | src/message.cpp | smallb/ucxxrt | 6f1fddae4f5eefb4e1ad36b7c9a1cd664caf2f26 | [
"MIT"
] | null | null | null | /*
* PROJECT: Universal C++ RunTime (UCXXRT)
* FILE: message.cpp
* DATA: 2022/05/22
*
* PURPOSE: Universal C++ RunTime
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: MiroKaku (miro.kaku AT Outlook.com)
*/
EXTERN_C NTSTATUS NTAPI RtlFindAndFormatMessage(
_In_ UINT32 Flags,
_In_opt_ LPCVOID Source,
_In_ UINT32 MessageId,
_In_ UINT32 LanguageId,
_Out_ LPWSTR Buffer,
_Inout_ UINT32* Size,
_In_opt_ va_list* Arguments
)
{
NTSTATUS Status = STATUS_SUCCESS;
PVOID AllocatedBuffer = nullptr;
ANSI_STRING AnsiMessage{};
UNICODE_STRING UnicodeMessage{};
do
{
/* If this is a Win32 error wrapped as an OLE HRESULT then unwrap it */
if (((MessageId & 0xffff0000) == 0x80070000) &&
BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_SYSTEM) &&
!BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_HMODULE) &&
!BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_STRING))
{
MessageId &= 0x0000ffff;
}
if (Buffer == nullptr)
{
Status = STATUS_INVALID_PARAMETER;
break;
}
if (Flags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
{
*(PVOID*)Buffer = nullptr;
}
PVOID DllHandle = nullptr;
ULONG MaximumWidth = 0ul;
PWSTR MessageFormat = nullptr;
PMESSAGE_RESOURCE_ENTRY MessageEntry = nullptr;
__try
{
PVOID BaseDllHandle = ucxxrt::PsSystemDllBase;
MaximumWidth = Flags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
if (MaximumWidth == FORMAT_MESSAGE_MAX_WIDTH_MASK)
{
MaximumWidth = ULONG_MAX;
}
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_STRING))
{
MessageFormat = (PWSTR)Source;
}
else
{
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_HMODULE))
{
if (Source == nullptr)
{
DllHandle = BaseDllHandle;
}
else
{
DllHandle = (LPVOID)Source;
}
}
else if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_SYSTEM))
{
DllHandle = BaseDllHandle;
}
else
{
Status = STATUS_INVALID_PARAMETER;
break;
}
Status = RtlFindMessage(
DllHandle,
PtrToUlong(RT_MESSAGETABLE),
LanguageId,
MessageId,
&MessageEntry);
if (Status == STATUS_MESSAGE_NOT_FOUND)
{
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_HMODULE) &&
BooleanFlagOn(Flags, FORMAT_MESSAGE_FROM_SYSTEM))
{
DllHandle = BaseDllHandle;
ClearFlag(Flags, FORMAT_MESSAGE_FROM_HMODULE);
Status = RtlFindMessage(
DllHandle,
PtrToUlong(RT_MESSAGETABLE),
LanguageId,
MessageId,
&MessageEntry);
}
}
if (!NT_SUCCESS(Status))
{
break;
}
if (!BooleanFlagOn(MessageEntry->Flags, MESSAGE_RESOURCE_UNICODE))
{
RtlInitAnsiString(&AnsiMessage, (PCSZ)MessageEntry->Text);
Status = RtlAnsiStringToUnicodeString(&UnicodeMessage, &AnsiMessage, TRUE);
if (!NT_SUCCESS(Status))
{
break;
}
MessageFormat = UnicodeMessage.Buffer;
}
else
{
MessageFormat = (PWSTR)MessageEntry->Text;
}
}
auto WrittenSize = 256ul;
bool IgnoreInserts = BooleanFlagOn(Flags, FORMAT_MESSAGE_IGNORE_INSERTS);
bool ArgumentsAreAnAnsi = BooleanFlagOn(Flags, FORMAT_MESSAGE_ARGUMENT_ANSI);
bool ArgumentsAreAnArray = BooleanFlagOn(Flags, FORMAT_MESSAGE_ARGUMENT_ARRAY);
do
{
if (AllocatedBuffer)
{
free(AllocatedBuffer);
}
AllocatedBuffer = malloc(WrittenSize);
if (AllocatedBuffer == nullptr)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
Status = RtlFormatMessage(
MessageFormat,
MaximumWidth,
IgnoreInserts,
ArgumentsAreAnAnsi,
ArgumentsAreAnArray,
Arguments,
(PWSTR)AllocatedBuffer,
WrittenSize,
&WrittenSize);
if (NT_SUCCESS(Status))
{
break;
}
if (Status != STATUS_BUFFER_OVERFLOW)
{
break;
}
WrittenSize += 256;
} while (true);
if (!NT_SUCCESS(Status))
{
break;
}
if (BooleanFlagOn(Flags, FORMAT_MESSAGE_ALLOCATE_BUFFER))
{
*(PVOID*)Buffer = AllocatedBuffer;
AllocatedBuffer = nullptr;
}
else if ((WrittenSize / sizeof(WCHAR)) > *Size)
{
Status = STATUS_BUFFER_TOO_SMALL;
break;
}
else
{
RtlMoveMemory(Buffer, AllocatedBuffer, WrittenSize);
}
*Size = (WrittenSize - sizeof(WCHAR)) / sizeof(WCHAR);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
Status = GetExceptionCode();
break;
}
} while (false);
free(AllocatedBuffer);
RtlFreeUnicodeString(&UnicodeMessage);
return Status;
}
| 29.976959 | 95 | 0.458878 | smallb |
c8b26f9e3717617622e4b11a08f9fd9e74c7c8cb | 1,032 | cpp | C++ | hdu100/problem2019.cpp | xiangflight/algopc | 75824fe085a51f5a7009b42e81feb645135db656 | [
"Apache-2.0"
] | null | null | null | hdu100/problem2019.cpp | xiangflight/algopc | 75824fe085a51f5a7009b42e81feb645135db656 | [
"Apache-2.0"
] | null | null | null | hdu100/problem2019.cpp | xiangflight/algopc | 75824fe085a51f5a7009b42e81feb645135db656 | [
"Apache-2.0"
] | null | null | null | //
// Created by xiang on 2019/9/24.
//
// Description:
// 有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。
//
// Input:
// 输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。
//
// Output:
// 对于每个测试实例,输出插入新的元素后的数列。
//
// Sample:
//
// 3 3
// 1 2 4 -> 1 2 3 4
// 0 0
//
//
#include <cstdio>
int main() {
int n, m;
while (scanf("%d %d", &n, &m) != EOF) {
if (n == 0 && m == 0) {
continue;
}
int a[n + 1];
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
}
int j;
for (j = n - 1; j >= 0; j--) {
if (a[j] <= m) {
break;
}
}
j++;
for (int k = n; k > j; k--) {
a[k] = a[k - 1];
}
a[j] = m;
for (int i = 0; i < n + 1; i++) {
printf("%d", a[i]);
if (i != n) {
printf(" ");
}
}
printf("\n");
}
return 0;
}
| 18.763636 | 78 | 0.356589 | xiangflight |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.