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 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 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 listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | 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 listlengths 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a78cf1e9a5cc80c2bf0dfcea28d0f8ae551178f5 | 301 | cpp | C++ | cluster.cpp | Recmo/depgraph | 102eeecb5f875d38dedbd0d777bbb212e143dfa9 | [
"MIT"
] | 1 | 2020-10-06T03:25:40.000Z | 2020-10-06T03:25:40.000Z | cluster.cpp | Recmo/depgraph | 102eeecb5f875d38dedbd0d777bbb212e143dfa9 | [
"MIT"
] | null | null | null | cluster.cpp | Recmo/depgraph | 102eeecb5f875d38dedbd0d777bbb212e143dfa9 | [
"MIT"
] | null | null | null | #include "cluster.h"
#include "varint.h"
Cluster::Cluster()
{
}
Cluster::~Cluster()
{
}
void Cluster::to_bip(char*& cursor)
{
}
void Cluster::from_bip(char*& cursor)
{
set_label(read_string(cursor));
}
ostream& operator<<(ostream& out, const Cluster& in)
{
out << in.label();
return out;
}
| 10.75 | 52 | 0.654485 | Recmo |
a79021c15b4819f81d36b56ff31fc8357738162e | 38,074 | cpp | C++ | src/syntax/compiler.cpp | srijan-paul/snap | 93bd7bed27008910bdce706f4545a06c3445e242 | [
"MIT"
] | 29 | 2021-02-01T15:36:40.000Z | 2022-03-27T08:28:28.000Z | src/syntax/compiler.cpp | srijan-paul/snap | 93bd7bed27008910bdce706f4545a06c3445e242 | [
"MIT"
] | 12 | 2021-01-23T15:21:10.000Z | 2022-03-27T14:13:28.000Z | src/syntax/compiler.cpp | srijan-paul/snap | 93bd7bed27008910bdce706f4545a06c3445e242 | [
"MIT"
] | 3 | 2021-03-02T09:13:25.000Z | 2021-07-26T11:41:10.000Z | #include "common.hpp"
#include "debug.hpp"
#include "../str_format.hpp"
#include <compiler.hpp>
#include <cstring>
#include <string>
#include <vm.hpp>
#define TOK2NUM(t) VYSE_NUM(std::stod(t.raw(*m_source)))
#define THIS_BLOCK (m_codeblock->block())
#define ERROR(...) (error_at_token(kt::format_str(__VA_ARGS__).c_str(), token))
#define DEFINE_PARSE_FN(name, cond, next_fn) \
void name() { \
next_fn(); \
while (cond) { \
const Token op_token = token; \
next_fn(); \
emit(toktype_to_op(op_token.type), op_token); \
} \
}
namespace vy {
using Op = Opcode;
using TT = TokenType;
Compiler::Compiler(VM* vm, const std::string* src) : m_vm{vm}, m_source{src} {
m_scanner = new Scanner{src};
advance(); // set `peek` to the first token in the token stream.
String* fname = &vm->make_string("<script>", 8);
// reserve the first slot for this toplevel function.
m_symtable.add("<script>", 8, true);
// When allocating [m_codeblock], the String "script" not reachable by the VM, so we protect it
// from GC.
GCLock lock = m_vm->gc_lock(fname);
m_codeblock = &vm->make<CodeBlock>(fname);
}
Compiler::Compiler(VM* vm, Compiler* parent, String* name) : m_vm{vm}, m_parent{parent} {
m_scanner = m_parent->m_scanner;
m_codeblock = &m_vm->make<CodeBlock>(name);
m_symtable.add(name->c_str(), name->len(), false);
m_source = parent->m_source;
vm->m_compiler = this;
prev = parent->prev;
token = parent->token;
peek = parent->peek;
}
Compiler::~Compiler() {
// If this is the top-level compiler then we can free the scanner assosciated with it.
if (m_parent == nullptr) {
delete m_scanner;
}
}
CodeBlock* Compiler::compile() {
while (!eof()) {
toplevel();
}
emit(Op::load_nil, Op::return_val);
m_codeblock->m_num_upvals = m_symtable.m_num_upvals;
return m_codeblock;
}
CodeBlock* Compiler::compile_func(bool is_arrowfn) {
// If this a compiler for an arrow function, then test for an implicitly returned expression
// right after the '->'. If there is a `{` however, we treat it as a function body instead.
if (is_arrowfn) {
if (check(TT::LCurlBrace)) {
block_stmt();
emit(Op::load_nil);
} else {
expr();
}
emit(Op::return_val);
} else {
test(TT::LCurlBrace, "Expected '{' before function body.");
block_stmt();
// In case the function does not return anything, we add an implicit 'return nil'. If the
// closure *does* return explicitly then these 2 opcodes will never be reached anyway.
emit(Op::load_nil, Op::return_val);
}
m_codeblock->m_num_upvals = m_symtable.m_num_upvals;
m_vm->m_compiler = m_parent;
return m_codeblock;
}
// top level statements are one of:
// - var declaration
// - function declaration
// - if statement
// - loop (while/for)
// - expression statement
// - export statement
void Compiler::toplevel() {
if (has_error) goto_eof();
if (eof()) return;
const TT token_type = peek.type;
// clang-format off
switch (token_type) {
case TT::Const:
case TT::Let: var_decl(); break;
case TT::LCurlBrace: block_stmt(); break;
case TT::If: if_stmt(); break;
case TT::While: while_stmt(); break;
case TT::For: for_stmt(); break;
case TT::Fn: fn_decl(); break;
case TT::Return: ret_stmt(); break;
case TT::Break: break_stmt(); break;
case TT::Continue: continue_stmt(); break;
default: expr_stmt(); break;
}
// clang-format on
match(TT::Semi);
}
void Compiler::var_decl() {
advance(); // eat the 'let'|'const'
const bool is_const = token.type == TT::Const;
do {
declarator(is_const);
} while (match(TT::Comma));
}
void Compiler::declarator(bool is_const) {
expect(TT::Id, "Expected variable name.");
// add the new variable to the symbol table.
const Token name = token;
// default value for variables is 'nil'.
match(TT::Eq) ? expr() : emit(Op::load_nil, token);
new_variable(name, is_const);
}
void Compiler::block_stmt() {
advance(); // eat the opening '{'
enter_block();
while (!(eof() or check(TT::RCurlBrace))) {
toplevel();
}
expect(TT::RCurlBrace, "Expected '}' to close block.");
exit_block();
}
void Compiler::if_stmt() {
advance(); // consume 'if'
expr(); // parse condition.
// If the condition is false, we simply pop it and jump to the end of the if statement.
// This puts as after the closing '}', which might be an 'else' block sometimes.
size_t jmp = emit_jump(Op::pop_jmp_if_false);
toplevel();
if (match(TT::Else)) {
// If the 'if' block executed then the 'else' shouldn't run, to do this, we jump straight to
// the end of the 'else' block after evaluating the 'if'.
size_t else_jmp = emit_jump(Op::jmp);
patch_jump(jmp);
toplevel();
patch_jump(else_jmp);
return;
}
patch_jump(jmp);
}
void Compiler::enter_loop(Loop& loop) {
loop.enclosing = m_loop;
// loop.start stores index of the first instruction in the loop
// body/conditon. Which here is the next instruction to be emitted
loop.start = THIS_BLOCK.op_count();
loop.scope_depth = m_symtable.m_scope_depth;
m_loop = &loop;
}
void Compiler::exit_loop(Op op_loop) {
VYSE_ASSERT(m_loop != nullptr, "Attempt to exit loop in a top-level block.");
const int n_ops = THIS_BLOCK.op_count();
// Emit the jmp_back instruction that connects the end of the
// loop to the beginning.
const int back_jmp = emit_jump(op_loop);
patch_backwards_jump(back_jmp, m_loop->start);
for (int i = m_loop->start; i < n_ops;) {
// no_op instructions are 'placeholders' for jumps resulting from a break or continue
// statement.
if (THIS_BLOCK.code[i] == Op::no_op) {
// If it's a break statement then patch it to the
// end of the loop.
if (u8(THIS_BLOCK.code[i + 1]) == 0) {
THIS_BLOCK.code[i] = Op::jmp;
patch_jump(i + 1);
} else {
VYSE_ASSERT(u8(THIS_BLOCK.code[i + 1]) == 0xff, "Bad jump.");
THIS_BLOCK.code[i] =
(m_loop->loop_type == Loop::Type::While) ? Op::jmp_back : Op::for_loop;
patch_backwards_jump(i + 1, m_loop->start);
}
}
// It is crucial that we increment the counter by the current instruction's arity (number of
// operands needed) instead of simply doing `i++`. If we do `i++` then we'd be reading
// operands to other instructions like `load_const` as bytecode instructions and
// misinterpreting the values.
i += op_arity(i) + 1;
}
m_loop = m_loop->enclosing;
}
void Compiler::discard_loop_locals(u32 depth) {
VYSE_ASSERT(m_symtable.m_scope_depth > depth, "Bad call to discard_locals.");
for (int i = m_symtable.m_num_symbols - 1; i >= 0; i--) {
const LocalVar& var = m_symtable.m_symbols[i];
if (var.depth <= depth) break;
emit(var.is_captured ? Op::close_upval : Op::pop);
}
}
void Compiler::break_stmt() {
advance(); // consume 'break' token.
if (m_loop == nullptr) {
ERROR("break statement outside a loop.");
return;
}
/// Remove all the local variables inside the loop's body before jumping out of it.
discard_loop_locals(m_loop->scope_depth);
// A 'break' statement's jump instruction is characterized by a `no_op` instruction. So when the
// `Compiler::loop_exit` method is patching old loops, it doesn't get confused between 'jmp'
// instructions from break statements and 'jmp' instructions from other statements like "if".
const int jmp = emit_jump(Op::no_op);
// A no_op instruction followed by a 0x00 is recognized as a 'break' statement.
// Later the 0x00 and the following byte are changed into the actual jump offset.
THIS_BLOCK.code[jmp] = Op(0x00);
}
void Compiler::continue_stmt() {
advance(); // consume 'continue'
if (m_loop == nullptr) {
ERROR("continue statement outside a loop.");
return;
}
discard_loop_locals(m_loop->scope_depth);
// continue statement jumps that need to be patched
// later are marked with a `no_op` instruction followed
// by two `0xff`s.
emit_jump(Op::no_op);
}
void Compiler::while_stmt() {
advance(); // consume 'while'
Loop loop(Loop::Type::While);
enter_loop(loop);
expr(); // parse condition.
const u32 jmp = emit_jump(Opcode::pop_jmp_if_false);
toplevel();
exit_loop(Op::jmp_back);
patch_jump(jmp);
}
void Compiler::for_stmt() {
advance(); // consume the 'for'
expect(TT::Id, "Expected for-loop variable.");
const Token name = token;
// Enter the scope for the for loop.
// Note that the loop iterator variable belongs inside this block.
enter_block();
new_variable("<for-start>", 11);
// Loop start
expect(TT::Eq, "Expected '=' after for-loop variable.");
expr();
// Loop limit
expect(TT::Comma, "Expected ',' to separate for-loop variable and limit.");
new_variable("<for-limit>", 11);
expr();
// Optional loop step, 1 by default.
new_variable("<for-step>", 10);
if (match(TT::Comma)) {
expr();
} else {
const int idx = emit_value(VYSE_NUM(1));
emit_with_arg(Op::load_const, idx);
}
// Add the actual loop variable that is exposed to the user. (i)
new_variable(name);
const size_t prep_jump = emit_jump(Op::for_prep);
// Loop body
Loop loop(Loop::Type::For);
enter_loop(loop);
toplevel();
patch_jump(prep_jump);
exit_loop(Op::for_loop);
exit_block();
}
void Compiler::fn_decl() {
advance(); // consume 'fn' token.
expect(TT::Id, "expected function name");
const Token name_token = token;
String* fname = &m_vm->make_string(name_token.raw_cstr(*m_source), name_token.length());
func_expr(fname);
new_variable(name_token);
}
// Compile the body of a function or method assuming everything excluding the
// the opening parenthesis has been consumed.
void Compiler::func_expr(String* fname, bool is_method, bool is_arrow) {
// When compiling the body of the function, we allocate
// a code block; at that point in time, the name of the
// function is not reachable by the Garbage Collector,
// so we protect it.
GCLock lock = m_vm->gc_lock(fname);
Compiler compiler{m_vm, this, fname};
// parentheses are optional for arrow functions
bool open_paren;
if (is_arrow) {
open_paren = compiler.match(TT::LParen);
} else {
compiler.expect(TT::LParen, "Expected '(' before function parameter list.");
open_paren = true;
}
uint param_count = 0;
// Methods have an implicit 'self' parameter, used to reference the object itself.
if (is_method) {
++param_count;
compiler.add_self_param();
}
bool is_vararg = false;
if ((open_paren and !compiler.check(TT::RParen)) or (is_arrow and !compiler.check(TT::Arrow))) {
do {
compiler.expect(TT::Id, "Expected parameter name.");
compiler.add_param(compiler.token);
++param_count;
if (compiler.match(TT::DotDotDot)) {
is_vararg = true;
break; // variadic parameter is the last one.
}
} while (compiler.match(TT::Comma));
}
if (param_count > MaxFuncParams) {
compiler.error_at_token("Function cannot have more than 200 parameters", compiler.token);
return;
}
if (open_paren) {
compiler.expect(TT::RParen, "Expected ')' after function parameters.");
}
if (is_arrow) {
compiler.expect(TT::Arrow, "Expected '->' before lambda body.");
}
CodeBlock* const code = compiler.compile_func(is_arrow);
code->m_is_variadic = is_vararg;
if (compiler.has_error) has_error = true;
const u8 idx = emit_value(VYSE_OBJECT(code));
emit(Op::make_func);
emit_arg(idx);
emit_arg(code->m_num_upvals);
for (int i = 0; i < compiler.m_symtable.m_num_upvals; ++i) {
const UpvalDesc& upval = compiler.m_symtable.m_upvals[i];
// An operand of '1' means that the upvalue exists in the call
// frame of the currently executing function while this closure is
// being created. '0' means the upvalue exists in the current
// function's upvalue list.
emit_arg(upval.is_local ? 1 : 0);
emit_arg(upval.index);
}
#ifdef VYSE_DEBUG_DISASSEMBLY
disassemble_block(code->name_cstr(), code->block());
#endif
// synchronize the parent compiler with the child so we can continue compiling
// from where the child left off.
prev = compiler.prev;
token = compiler.token;
peek = compiler.peek;
has_error = compiler.has_error;
}
void Compiler::ret_stmt() {
advance(); // eat the 'return' keyword.
// If the next token marks the start of an expression, then
// compile this statement as `return EXPR`, else it's just a `return`.
// where a `nil` after the return is implicit.
if (peek.is_literal() or check(TT::Id) or peek.is_unary_op() or check(TT::LParen) or
check(TT::Fn) or check(TT::LCurlBrace) or check(TT::LSqBrace)) {
expr();
} else {
emit(Op::load_nil);
}
emit(Op::return_val);
}
void Compiler::expr_stmt() {
const ExpKind prefix_type = prefix();
// If a toplevel assignment statement
// was already compiled then exit.
if (prefix_type == ExpKind::none) return;
// Otherwise keep parsing to get a valid
// assignment statement.
complete_expr_stmt(prefix_type);
/// TODO: The pop instruction here can be implicit
/// for 'set' and 'index' instructions.
emit(Op::pop);
}
/// Compiling expression statements ///
// There are no 'expression statements' as such in vyse.
// The only valid toplevel expression is a function call.
// Assignment ('a=b') is strictly a statement and not allowed
// in expression contexts.
//
// A call expression can be an arbitrarily long suffixed
// expression followed by a '()'. So all of the following
// are valid call expressions:
// 1. foo()
// 2. foo.bar()
// 3. t['k']()
// 4. foo:bar().baz['key']()
// 5. f()()()
// 6. g()['k']()
//
// Similarly, all of the following are valid assignment
// statements:
// 1. a = 1
// 2. a.b = 1
// 3. t['k'] = 1
// 4. t['k'].bar().baz = 123
//
// To make sure the all the above cases are covered, we clearly define
// what is and isn't a valid LHS for assignment.
// The following is the grammar for a valid assignment statement:
//
// ASSIGN := LHS ASSIGN_TOK EXPRESSION
// LHS := ID | (SUFFIXED_EXP ASSIGNABLE_SUFFIX)
// SUFFIXED_EXP := (PREFIX | SUFFIXED_EXP) SUFFIX
// PREFIX := (ID | STRING | NUMBER | BOOLEAN)
// SUFFIX := ASSIGNABLE_SUFFIX | '('ARGS')' | METHOD_CALL | APPEND
// ASSIGNABLE_SUFFIX := '[' EXPRESSION ']' | '.'ID
// METHOD_CALL := ':' ID '(' ARGS ')'
// APPEND := '<<<' EXPR_OR
// ASSIGN_TOK := '=' | '+=' | '-=' | '*=' | '%=' | '/=' | '//='
//
// It may be noticed that parsing an assignment when the LHS can be an arbitrarily
// long chain of '.', '[]', '()' etc will require indefinite backtracking, or some
// form of an AST. To tackle this, we follow a simple idea:
// Keep track of the current state / expr kind in while parsing, if we see an '=' and
// the last state was a valid assignment LHS, then we compile an assignment.
void Compiler::complete_expr_stmt(ExpKind prefix_type) {
ExpKind exp_kind = prefix_type;
// Keep compiling the rest of the prefix, however if a
// an '=' is seen, then compile a top level assignment
// and stop.
while (true) {
switch (peek.type) {
case TT::LSqBrace: {
advance();
expr();
expect(TT::RSqBrace, "Expected ']' to close index expression.");
if (is_assign_tok(peek.type)) {
table_assign(Op::index_no_pop, -1);
emit(Op::subscript_set);
return;
} else {
emit(Op::subscript_get);
exp_kind = ExpKind::prefix;
}
break;
}
case TT::LParen: {
if (exp_kind == ExpKind::literal_value) {
ERROR("Unexpected '('");
return;
}
compile_args();
exp_kind = ExpKind::call;
break;
}
case TT::Dot: {
advance();
expect(TT::Id, "Expected field name.");
const u8 index = emit_id_string(token);
if (is_assign_tok(peek.type)) {
table_assign(Op::table_get_no_pop, index);
emit_with_arg(Op::table_set, index);
return;
} else {
exp_kind = ExpKind::prefix;
emit_with_arg(Op::table_get, index);
}
break;
}
case TT::Colon: {
advance();
expect(TT::Id, "Expected method name.");
const u8 index = emit_id_string(token);
emit_with_arg(Op::prep_method_call, index);
compile_args(true);
exp_kind = ExpKind::call;
break;
}
/// Appending to an array is also allowed
/// in a statement context.
case TT::Append: {
advance(); // eat the '<<<'
logic_or();
emit(Op::list_append);
exp_kind = ExpKind::append;
break;
}
default: {
if (exp_kind == ExpKind::call or exp_kind == ExpKind::append) return;
// If the expression type that was compiled last is not a
// method or closure call, and we haven't found
// a proper LHS for assignment yet, then this is
// incorrect source code.
ERROR("Unexpected expression.");
return;
}
}
}
}
// Compile a prefix or a variable assignment.
// A prefix can be (as described above): (ID | STRING | NUMBER | BOOLEAN)
// A var assignment is simply ID '=' EXPRESSION
ExpKind Compiler::prefix() {
if (check(TT::LParen)) {
grouping();
return ExpKind::prefix;
}
if (match(TT::Id)) {
if (is_assign_tok(peek.type)) {
variable(true);
// Since we have successfully compiled a valid toplevel statement, it is longer an
// expression. We use ExpKind::none to indicate this.
return ExpKind::none;
} else {
variable(false);
return ExpKind::prefix;
}
}
if (!peek.is_literal()) {
ERROR("Unexpected '{}'.", peek.raw(*m_source));
return ExpKind::literal_value;
}
if (peek.type == TT::Nil) {
ERROR("Unexpected 'nil'.");
return ExpKind::none;
}
literal();
return ExpKind::literal_value;
}
void Compiler::expr() {
append();
}
void Compiler::append() {
logic_or();
while (match(TT::Append)) {
logic_or();
emit(Op::list_append);
}
}
void Compiler::logic_or() {
logic_and();
if (match(TT::Or)) {
const size_t jump = emit_jump(Op::jmp_if_true_or_pop);
logic_or();
patch_jump(jump);
}
}
void Compiler::logic_and() {
bit_or();
if (match(TT::And)) {
const size_t jump = emit_jump(Op::jmp_if_false_or_pop);
logic_and();
patch_jump(jump);
}
}
DEFINE_PARSE_FN(Compiler::bit_or, match(TT::BitOr), bit_xor)
DEFINE_PARSE_FN(Compiler::bit_xor, match(TT::BitXor), bit_and)
DEFINE_PARSE_FN(Compiler::bit_and, match(TT::BitAnd), equality)
DEFINE_PARSE_FN(Compiler::equality, match(TT::EqEq) or match(TT::BangEq), comparison)
DEFINE_PARSE_FN(Compiler::comparison,
match(TT::Gt) or match(TT::Lt) or match(TT::GtEq) or match(TT::LtEq), b_shift)
DEFINE_PARSE_FN(Compiler::b_shift, match(TT::BitLShift) or match(TT::BitRShift), sum)
DEFINE_PARSE_FN(Compiler::sum, (match(TT::Plus) or match(TT::Minus) or match(TT::Concat)), mult)
DEFINE_PARSE_FN(Compiler::mult, (match(TT::Mult) or match(TT::Mod) or match(TT::Div)), exp)
DEFINE_PARSE_FN(Compiler::exp, match(TT::Exp), unary)
void Compiler::unary() {
/// TODO: group all unary oprators together in 'token.hpp' and then change this if statement to
/// a simple range check.
if (peek.is_unary_op()) {
advance();
const Token op_token = token;
unary();
switch (op_token.type) {
case TT::Bang: emit(Op::lnot, op_token); break;
case TT::Minus: emit(Op::negate, op_token); break;
case TT::Len: emit(Op::len, op_token); break;
case TT::BitNot: emit(Op::bnot, op_token); break;
default: VYSE_ERROR("Impossible unary token."); break;
}
return;
}
atomic();
}
void Compiler::atomic() {
grouping();
suffix_expr();
}
void Compiler::suffix_expr() {
while (true) {
switch (peek.type) {
case TT::LSqBrace: {
advance();
expr();
expect(TT::RSqBrace, "Expected ']' to close index expression.");
emit(Op::subscript_get);
break;
}
case TT::LParen: compile_args(); break;
case TT::Dot: {
advance();
expect(TT::Id, "Expected field name.");
const u8 index = emit_id_string(token);
emit_with_arg(Op::table_get, index);
break;
}
case TT::Colon: {
advance();
expect(TT::Id, "Expected method name.");
u8 index = emit_id_string(token);
emit_with_arg(Op::prep_method_call, index);
compile_args(true);
break;
}
default: return;
}
}
}
void Compiler::table_assign(Op get_op, int idx) {
VYSE_ASSERT(is_assign_tok(peek.type), "Bad call to Compiler::table_assign");
advance();
const TT ttype = token.type;
/// if this is a simple assignment with '=' operator, then simply compile the RHS as an
/// expression and return to the call site, wherein it's the caller's responsibility to emit the
/// 'set' opcode.
if (ttype == TT::Eq) {
expr();
return;
}
/// If we've reached here then it must be a compound assignment operator. So we first need to
/// get the original field value, push it on top of the stack, modify this value then use a
/// 'set' opcode to store it back into the table/array. The 'set' opcode is emitted by the
/// caller.
emit(get_op);
if (idx > 0) emit_arg(idx);
expr();
emit(toktype_to_op(ttype));
}
void Compiler::compile_args(bool is_method) {
advance(); // eat opening '('
// If it's a method call, then start with 1 argument count for the implicit 'self' argument.
u32 argc = is_method ? 1 : 0;
if (!check(TT::RParen)) {
do {
++argc;
if (argc > MaxFuncParams) ERROR("Too many arguments to function call.");
expr(); // push the arguments on the stack,
} while (match(TT::Comma));
}
expect(TT::RParen, "Expected ')' after call.");
emit_with_arg(Op::call_func, argc);
}
void Compiler::grouping() {
if (match(TT::LParen)) {
expr();
expect(TT::RParen, "Expected ')' after grouping expression.");
return;
}
primary();
}
void Compiler::primary() {
if (peek.is_literal()) {
literal();
} else if (match(TT::Fn)) {
static constexpr const char* name = "<anonymous>";
String* fname = &m_vm->make_string(name, strlen(name));
if (check(TT::LParen)) return func_expr(fname);
// Names of lambda expressions are simply ignored unless found in a statement context.
expect(TT::Id, "Expected function name or '('.");
return func_expr(fname);
} else if (match(TT::Id)) {
variable(false);
} else if (match(TT::LCurlBrace)) {
table();
} else if (match(TT::LSqBrace)) {
array();
} else if (match(TT::Div)) {
static constexpr const char* name = "<arrow-fn>";
String* fname = &m_vm->make_string(name, strlen(name));
func_expr(fname, false, true); // is_method = false, is_arrow = true
} else {
ERROR("Unexpected '{}'.", peek.raw(*m_source));
advance();
}
}
void Compiler::table() {
emit(Opcode::new_table);
// empty table.
if (match(TT::RCurlBrace)) return;
do {
if (match(TT::LSqBrace)) {
/// a computed table key like in { [1 + 2]: 3 }
expr();
expect(TT::RSqBrace, "Expected ']' near table key.");
} else {
expect(TT::Id, "Expected identifier as table key.");
String* key_string = &m_vm->make_string(token.raw_cstr(*m_source), token.length());
const int key_idx = emit_value(VYSE_OBJECT(key_string));
emit_with_arg(Op::load_const, key_idx);
if (check(TT::LParen)) {
func_expr(key_string, true); // is_method = true, is_arrow = false
emit(Op::table_add_field);
if (check(TT::RCurlBrace)) break;
continue;
}
}
expect(TT::Colon, "Expected ':' after table key.");
expr();
emit(Op::table_add_field);
if (check(TT::RCurlBrace)) break;
} while (!eof() and match(TT::Comma));
if (eof()) {
error("Reached end of file while compiling.");
return;
}
expect(TT::RCurlBrace, "Expected '}' to close table or ',' to separate entry.");
}
void Compiler::array() {
emit(Op::new_list);
if (match(TT::RSqBrace)) return; // empty array.
do {
expr();
emit(Op::list_append);
if (check(TT::RSqBrace)) break;
expect(TT::Comma, "Expected a ',' to separate array entry");
} while (!eof());
expect(TT::RSqBrace, "Expected a ']' to close array or ',' to separate entry.");
}
void Compiler::variable(bool can_assign) {
Op get_op = Op::get_var;
Op set_op = Op::set_var;
int index = find_local_var(token);
bool is_const = (index == -1) ? false : m_symtable.find_by_slot(index)->is_const;
// if no local variable with that name was found then look for an
// upvalue.
if (index == -1) {
index = find_upvalue(token);
if (index == -1) {
get_op = Opcode::get_global;
set_op = Opcode::set_global;
index = emit_id_string(token);
} else {
get_op = Opcode::get_upval;
set_op = Opcode::set_upval;
is_const = m_symtable.m_upvals[index].is_const;
}
}
if (can_assign) {
VYSE_ASSERT(is_assign_tok(peek.type), "Not in an assignment context.");
if (is_const) {
std::string message = kt::format_str("Cannot assign to variable '{}' marked const.",
token.raw(*m_source));
error_at_token(message.c_str(), token);
}
/// Compile the RHS of the assignment, and any necessary arithmetic ops if its a compound
/// assignment operator. So by the time we are setting the value, the RHS is sitting ready
/// on top of the stack.
var_assign(get_op, index);
emit_with_arg(set_op, index);
} else {
emit_with_arg(get_op, index);
}
}
void Compiler::var_assign(Op get_op, u32 idx_or_name_str) {
advance();
const TT ttype = token.type;
VYSE_ASSERT(is_assign_tok(ttype), "Bad call to Compiler::var_assign");
if (ttype == TT::Eq) {
expr();
return;
}
emit_with_arg(get_op, idx_or_name_str);
expr();
emit(toktype_to_op(ttype));
}
void Compiler::literal() {
advance();
u32 index = 0;
switch (token.type) {
case TT::Integer:
case TT::Float: index = emit_value(TOK2NUM(token)); break;
case TT::String: index = emit_string(token); break;
case TT::True: index = emit_value(VYSE_BOOL(true)); break;
case TT::False: index = emit_value(VYSE_BOOL(false)); break;
case TT::Nil: {
emit(Op::load_nil);
return;
}
default:
VYSE_ERROR(kt::format_str("Impossible literal token type {}", int(token.type)).c_str());
break;
}
if (index > MaxLocalVars) {
ERROR("Too many literal constants in one function.");
}
/// TODO: handle indices larger than UINT8_MAX, by adding a load_const_long instruction that
/// takes 2 operands.
emit_with_arg(Op::load_const, static_cast<u8>(index));
}
void Compiler::goto_eof() {
while (!eof()) {
advance();
}
}
void Compiler::enter_block() noexcept {
++m_symtable.m_scope_depth;
}
void Compiler::exit_block() {
for (int i = m_symtable.m_num_symbols - 1; i >= 0; i--) {
const LocalVar& var = m_symtable.m_symbols[i];
if (var.depth != m_symtable.m_scope_depth) break;
emit(var.is_captured ? Op::close_upval : Op::pop);
--m_symtable.m_num_symbols;
}
--m_symtable.m_scope_depth;
}
size_t Compiler::emit_jump(Opcode op) {
const size_t index = THIS_BLOCK.op_count();
emit(op);
emit_arg(0xff);
emit_arg(0xff);
return index + 1;
}
void Compiler::patch_jump(size_t index) {
u32 jump_dist = THIS_BLOCK.op_count() - index - 2;
if (jump_dist > UINT16_MAX) {
ERROR("Too much code to jump over");
return;
}
// If we use a single opcode for the jump offset, then we're only allowed
// to jump over 255 instructions, which is unfortunately a very small number.
// To counter this, jumps are broken down into two Ops, the first Op contains the
// first byte and the second Op contains the second byte. The bytes are then stitched
// together to form a short int, thus allowing us to jump over UINT16_MAX bytes of code
// (65535 instructions) at best.
// For example, if we want to jump over 25000 opcodes, that means our jump offset
// is `0x61A8`. The first byte, `0x61` goes in the first opcode, and the second
// byte, `0xA8` goes in the second opcode. At runtime, the VM reads both of these,
// and joins them together using some bit operators.
THIS_BLOCK.code[index] = static_cast<Op>((jump_dist >> 8) & 0xff);
THIS_BLOCK.code[index + 1] = static_cast<Op>(jump_dist & 0xff);
}
void Compiler::patch_backwards_jump(size_t index, u32 dst_index) {
const u32 distance = index - dst_index + 2;
if (distance > UINT16_MAX) {
ERROR("Too much code to jump over.");
return;
}
THIS_BLOCK.code[index] = static_cast<Op>((distance >> 8) & 0xff);
THIS_BLOCK.code[index + 1] = static_cast<Op>(distance & 0xff);
}
void Compiler::add_param(const Token& token) {
new_variable(token);
m_codeblock->add_param();
}
void Compiler::add_self_param() {
VYSE_ASSERT(m_symtable.m_num_symbols == 1, "'self' must be the first parameter.");
constexpr const char* self = "self";
m_codeblock->add_param();
m_symtable.add(self, 4, true);
}
// Helper functions:
void Compiler::advance() {
prev = token;
token = peek;
peek = m_scanner->next_token();
}
bool Compiler::match(TT expected) noexcept {
if (check(expected)) {
advance();
return true;
}
return false;
}
void Compiler::expect(TT expected, const char* err_msg) {
if (check(expected)) {
advance();
return;
}
error_at_token(err_msg, token);
}
void Compiler::test(TT expected, const char* errmsg) {
if (!check(expected)) {
error_at_token(errmsg, peek);
}
}
void Compiler::error_at(const char* message, u32 line) {
error(kt::format_str("[line {}]: {}", line, message));
}
void Compiler::error_at_token(const char* message, const Token& token) {
static constexpr const char* fmt = "[line {}]: near '{}': {}";
error(kt::format_str(fmt, token.location.line, token.raw(*m_source), message));
}
void Compiler::error(std::string&& message) {
// To prevent cascading errors, we only report the very first error that the compiler
// encounters.
if (has_error) return;
m_vm->on_error(*m_vm, message);
has_error = true;
}
bool Compiler::ok() const noexcept {
return !has_error;
}
u32 Compiler::emit_string(const Token& token) {
const u32 length = token.length() - 2; // minus the quotes
// The actual length of the string may be different from what we see in the source code because
// of escape characters.
// +1 to skip the openening quote.
const char* srcbuf = token.raw_cstr(*m_source) + 1;
char* strbuf = (char*)malloc(sizeof(char) * (length + 1));
strbuf[length] = '\0';
uint pos = 0;
for (uint i = 0; i < length; ++i) {
// count escape characters as single chars.
if (srcbuf[i] == '\\') {
VYSE_ASSERT(i + 1 < length, "Malformed string token with '\\' as last character.");
char next_char = srcbuf[i + 1];
switch (next_char) {
case 'n': strbuf[pos] = '\n'; break;
case 't': strbuf[pos] = '\t'; break;
case 'r': strbuf[pos] = '\r'; break;
case 'b': strbuf[pos] = '\b'; break;
case 'v': strbuf[pos] = '\v'; break;
default: strbuf[pos] = next_char; break;
}
++i;
} else {
strbuf[pos] = srcbuf[i];
}
++pos;
}
uint str_len = pos;
strbuf = (char*)realloc(strbuf, sizeof(char) * (str_len + 1));
strbuf[str_len] = '\0';
String& string = m_vm->take_string(strbuf, str_len);
return emit_value(VYSE_OBJECT(&string));
}
u32 Compiler::emit_id_string(const Token& token) {
String* s = &m_vm->make_string(token.raw_cstr(*m_source), token.length());
return emit_value(VYSE_OBJECT(s));
}
int Compiler::find_local_var(const Token& name_token) const noexcept {
const char* name = name_token.raw_cstr(*m_source);
const int length = name_token.length();
const int idx = m_symtable.find(name, length);
return idx;
}
int Compiler::find_upvalue(const Token& token) {
if (m_parent == nullptr) return -1;
// First search among the local variables of the enclosing
// compiler.
int index = m_parent->find_local_var(token);
// If found the local var, then add it to the upvalues list and mark the upvalue is "local".
if (index != -1) {
LocalVar& local = m_parent->m_symtable.m_symbols[index];
local.is_captured = true;
return m_symtable.add_upvalue(index, true, local.is_const);
}
// If not found within the parent compiler's local vars then look into the parent compiler's
// upvalues.
index = m_parent->find_upvalue(token);
// If found in some enclosing scope, add it to the current upvalues list and return it.
if (index != -1) {
// is not local since we found it in an enclosing compiler.
const UpvalDesc& upval = m_parent->m_symtable.m_upvals[index];
return m_symtable.add_upvalue(index, false, upval.is_const);
}
// No local variable in any of the enclosing scopes was found with the same name.
return -1;
}
size_t Compiler::emit_value(Value v) {
const size_t index = THIS_BLOCK.add_value(v);
if (index >= Compiler::MaxLocalVars) {
error_at_token("Too many constants in a single block.", token);
}
return index;
}
inline void Compiler::emit(Op op) {
const int stack_effect = op_stack_effect(op);
m_stack_size += stack_effect;
if (m_stack_size > m_codeblock->max_stack_size) {
m_codeblock->max_stack_size = m_stack_size;
}
emit(op, token);
}
inline void Compiler::emit(Op op, const Token& token) {
THIS_BLOCK.add_instruction(op, token.location.line);
}
inline void Compiler::emit_arg(u8 operand) {
THIS_BLOCK.add_instruction(static_cast<Op>(operand), token.location.line);
}
inline void Compiler::emit_with_arg(Op op, u8 arg) {
emit(op);
emit_arg(arg);
}
inline void Compiler::emit(Op a, Op b) {
emit(a, token);
emit(b, token);
}
Op Compiler::toktype_to_op(TT toktype) const noexcept {
// clang-format off
switch (toktype) {
case TT::Plus:
case TT::PlusEq: return Op::add;
case TT::Minus:
case TT::MinusEq: return Op::sub;
case TT::Div:
case TT::DivEq: return Op::div;
case TT::Mult:
case TT::MultEq: return Op::mult;
case TT::Mod:
case TT::ModEq: return Op::mod;
case TT::EqEq: return Op::eq;
case TT::BangEq: return Op::neq;
case TT::Concat: return Op::concat;
case TT::BitLShift: return Op::lshift;
case TT::BitRShift: return Op::rshift;
case TT::BitAnd: return Op::band;
case TT::BitOr: return Op::bor;
case TT::BitXor: return Op::bxor;
case TT::Gt: return Op::gt;
case TT::Lt: return Op::lt;
case TT::GtEq: return Op::gte;
case TT::LtEq: return Op::lte;
case TT::Exp: return Op::exp;
default: VYSE_UNREACHABLE(); return Op::no_op;
}
// clang-format on
}
#define CHECK_ARITY(x, y) ((x) >= (Op_##y##_operands_start) and ((x) <= (Op_##y##_operands_end)))
int Compiler::op_arity(u32 op_index) const noexcept {
const Op op = THIS_BLOCK.code[op_index];
if (op == Op::make_func) {
VYSE_ASSERT(op_index != THIS_BLOCK.op_count() - 1,
"Op::make_func cannot be the last opcode");
int n_upvals = int(THIS_BLOCK.code[op_index + 1]);
return 1 + n_upvals * 2;
}
if (CHECK_ARITY(op, 0)) return 0;
if (CHECK_ARITY(op, 1)) return 1;
// Constant instructions take 1 operand: the index of the constant in the constant pool.
if (op >= Op_const_start and op <= Op_const_end) return 1;
VYSE_ASSERT(CHECK_ARITY(op, 2), "Instructions other than make_func can have upto 2 operands.");
return 2;
}
#undef CHECK_ARITY
int Compiler::op_stack_effect(Op op) const noexcept {
#define OP(_, __, stack_effect) stack_effect
constexpr std::array<int, size_t(Op::no_op) + 1> stack_effects = {
#include "x_opcode.hpp"
};
#undef OP
return stack_effects[size_t(op)];
}
bool Compiler::is_assign_tok(TT type) const noexcept {
return (type == TT::Eq or (type >= TT::ModEq and type <= TT::PlusEq));
}
// We need two overloads for Compiler::new_variable.
// On one hand, it's nice to be able to call new_variable(token)
// and not extract the name and length of the name at the call site.
// But sometimes we will want to add dummy variables (like for-loop limits).
// And we don't have a token for those to take the name from.
int Compiler::new_variable(const Token& varname, bool is_const) {
const char* name = varname.raw_cstr(*m_source);
const u32 length = varname.length();
if (m_symtable.find_in_current_scope(name, length) != -1) {
std::string errmsg = kt::format_str("Attempt to redeclare existing variable '{}'.",
std::string_view(name, length));
error_at_token(errmsg.c_str(), varname);
return -1;
}
return m_symtable.add(name, length, is_const);
}
int Compiler::new_variable(const char* name, u32 length, bool is_const) {
// check of a variable with this name already exists in the current scope.
if (m_symtable.find_in_current_scope(name, length) != -1) {
ERROR("Attempt to redeclare existing variable '{}'.", std::string_view(name, length));
return -1;
}
return m_symtable.add(name, length, is_const);
}
// -- LocalVar Table --
int SymbolTable::add(const char* name, u32 length, bool is_const = false) {
m_symbols[m_num_symbols] = LocalVar{name, length, u8(m_scope_depth), is_const};
return m_num_symbols++;
}
static bool names_equal(const char* a, int len_a, const char* b, int len_b) {
if (len_a != len_b) return false;
return std::memcmp(a, b, len_a) == 0;
}
int SymbolTable::find(const char* name, int length) const {
// start looking from the innermost scope, and work our way outwards.
for (int i = m_num_symbols - 1; i >= 0; i--) {
const LocalVar& symbol = m_symbols[i];
if (names_equal(name, length, symbol.name, symbol.length)) return i;
}
return -1;
}
int SymbolTable::find_in_current_scope(const char* name, int length) const {
for (int i = m_num_symbols - 1; i >= 0; i--) {
const LocalVar& symbol = m_symbols[i];
if (symbol.depth < m_scope_depth) return -1; // we've reached an outer scope
if (names_equal(name, length, symbol.name, symbol.length)) return i;
}
return -1;
}
const LocalVar* SymbolTable::find_by_slot(const u8 index) const {
return &m_symbols[index];
}
int SymbolTable::add_upvalue(int index, bool is_local, bool is_const) {
// If the upvalue has already been captured, then return the stored value.
for (int i = 0; i < m_num_upvals; ++i) {
UpvalDesc& upval = m_upvals[i];
if (upval.index == index and upval.is_local == is_local) {
return i;
}
}
m_upvals[m_num_upvals] = UpvalDesc{index, is_const, is_local};
return m_num_upvals++;
}
} // namespace vy
| 29.310239 | 100 | 0.665021 | srijan-paul |
042b4f6c5070297ffc9dc6a9a919e97976d5a3ab | 25,366 | hpp | C++ | include/LightningJSON/LightningJSON.hpp | ShadauxCat/LightningJSON | ba0b53c4b18d3360a761a7ad7e20ddbe6ac630bf | [
"MIT"
] | 1 | 2021-07-21T17:03:38.000Z | 2021-07-21T17:03:38.000Z | include/LightningJSON/LightningJSON.hpp | ShadauxCat/LightningJSON | ba0b53c4b18d3360a761a7ad7e20ddbe6ac630bf | [
"MIT"
] | null | null | null | include/LightningJSON/LightningJSON.hpp | ShadauxCat/LightningJSON | ba0b53c4b18d3360a761a7ad7e20ddbe6ac630bf | [
"MIT"
] | null | null | null | #pragma once
/*
* Copyright (C) 2020 Jaedyn K. Draper
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifdef _WIN32
#pragma warning( push )
#pragma warning( disable: 4250; disable: 4996 )
#endif
#if __cplusplus >= 201703L
#include <string_view>
#else
#include "StringView.hpp"
#endif
#include <sstream>
#include <string>
#include <vector>
#include "Exceptions.hpp"
#include "JSONType.hpp"
#include "third-party/SkipProbe/SkipProbe.hpp"
#ifndef LIGHTNINGJSON_STRICT
# define LIGHTNINGJSON_STRICT 0
#endif
namespace LightningJSON
{
#if __cplusplus >= 201703L
typedef std::string_view string_view;
#endif
class StringData
{
public:
StringData(char const* const data, size_t length)
: m_data(data)
, m_length(length)
, m_commitData(nullptr)
{
//
}
StringData(char const* const data)
: m_data(data)
, m_length(strlen(data))
, m_commitData(nullptr)
{
//
}
void CommitStorage()
{
m_commitData = new char[m_length + 1];
memcpy(m_commitData, m_data, m_length);
m_data = m_commitData;
}
~StringData()
{
if (m_commitData)
{
delete[] m_commitData;
}
}
StringData(StringData const& other)
: m_data(other.m_data)
, m_length(other.m_length)
, m_commitData(other.m_commitData)
{
if (m_commitData)
{
CommitStorage(); // Get our own copy of it, there's no refcounting
}
}
StringData& operator=(StringData const& other)
{
if (m_commitData)
{
delete[] m_commitData;
}
m_data = other.m_data;
m_length = other.m_length;
if (other.m_commitData)
{
CommitStorage();
}
return *this;
}
bool operator==(StringData const& other) const
{
if (m_length != other.m_length)
return false;
return !memcmp(m_data, other.m_data, m_length);
}
size_t length() const
{
return m_length;
}
char const* c_str() const
{
return m_data;
}
char operator[](size_t index) const
{
return m_data[index];
}
std::string toString() const
{
return std::string(m_data, m_length);
}
private:
char const* m_data;
size_t m_length;
char* m_commitData;
};
}
namespace SkipProbe
{
template<>
struct Hash<LightningJSON::StringData>
{
typedef LightningJSON::StringData argument_type;
size_t operator()(argument_type const& str) const
{
return SkipProbe::CityHash(str.c_str(), str.length());
}
};
}
namespace LightningJSON
{
class JSONObject
{
public:
static long long ToInt(StringData const& str);
static unsigned long long ToUInt(StringData const& str);
static long double ToDouble(StringData const& str);
static bool ToBool(StringData const& str);
static std::string EscapeString(StringData const& str);
static std::string UnescapeString(StringData const& str);
string_view GetKey() const
{
return string_view(m_key.c_str(), m_key.length());
}
long long AsInt() const
{
#ifdef LIGHTNINGJSON_STRICT
if (m_holder->m_type != JSONType::Integer)
{
throw JSONTypeMismatch(JSONType::Integer, m_holder->m_type);
}
#endif
return ToInt(m_holder->m_data);
}
unsigned long long AsUnsigned() const
{
#ifdef LIGHTNINGJSON_STRICT
if (m_holder->m_type != JSONType::Integer)
{
throw JSONTypeMismatch(JSONType::Integer, m_holder->m_type);
}
#endif
return ToUInt(m_holder->m_data);
}
void Val(signed char& value) const
{
value = (signed char)(AsInt());
}
void Val(short& value) const
{
value = short(AsInt());
}
void Val(int& value) const
{
value = int(AsInt());
}
void Val(long& value) const
{
value = long(AsInt());
}
void Val(long long& value) const
{
value = (long long)(AsInt());
}
void Val(unsigned char& value) const
{
value = (unsigned char)(AsInt());
}
void Val(unsigned short& value) const
{
value = (unsigned short)(AsInt());
}
void Val(unsigned int& value) const
{
value = (unsigned int)(AsInt());
}
void Val(unsigned long& value) const
{
value = (unsigned long)(AsInt());
}
void Val(unsigned long long& value) const
{
value = (unsigned long long)(AsInt());
}
void Val(bool& value) const
{
value = AsBool();
}
void Val(double& value) const
{
value = (double)AsDouble();
}
void Val(float& value) const
{
value = float(AsDouble());
}
void Val(long double& value) const
{
value = AsDouble();
}
void Val(std::string& value) const
{
value = AsString();
}
void Val(char* value, size_t length) const
{
std::string data = AsString();
size_t copyLength = length < data.length() ? length : data.length();
memcpy(value, data.c_str(), copyLength);
value[copyLength] = '\0';
}
std::string AsString() const
{
#ifdef LIGHTNINGJSON_STRICT
if (m_holder->m_type != JSONType::String)
{
throw JSONTypeMismatch(JSONType::String, m_holder->m_type);
}
#endif
return UnescapeString(m_holder->m_data);
}
bool AsBool() const
{
#ifdef LIGHTNINGJSON_STRICT
if (m_holder->m_type != JSONType::Boolean)
{
throw JSONTypeMismatch(JSONType::Boolean, m_holder->m_type);
}
#endif
return ToBool(m_holder->m_data);
}
long double AsDouble() const
{
#ifdef LIGHTNINGJSON_STRICT
if (m_holder->m_type != JSONType::Double)
{
throw JSONTypeMismatch(JSONType::Double, m_holder->m_type);
}
#endif
return ToDouble(m_holder->m_data);
}
JSONObject& NextSibling();
JSONObject const& NextSibling() const;
JSONObject const& operator[](char const* const key) const
{
return this->operator[](string_view(key, strlen(key)));
}
JSONObject const& operator[](std::string const& key) const
{
return this->operator[](string_view(key.c_str(), key.length()));
}
JSONObject const& operator[](string_view const& key) const;
JSONObject const& operator[](size_t index) const;
JSONObject& operator[](char const* const key)
{
return this->operator[](string_view(key, strlen(key)));
}
JSONObject& operator[](std::string const& key)
{
return this->operator[](string_view(key.c_str(), key.length()));
}
JSONObject& operator[](string_view const& key);
JSONObject& operator[](size_t index);
JSONObject& operator[](int index) { return operator[](size_t(index)); }
JSONType Type() const
{
return m_holder->m_type;
}
bool IsNull() const
{
return (m_holder->m_type == JSONType::Null);
}
bool IsEmpty() const
{
return (m_holder->m_type == JSONType::Empty);
}
bool IsInteger() const
{
return (m_holder->m_type == JSONType::Integer);
}
bool IsString() const
{
return (m_holder->m_type == JSONType::String);
}
bool IsDouble() const
{
return (m_holder->m_type == JSONType::Double);
}
bool IsBool() const
{
return (m_holder->m_type == JSONType::Boolean);
}
bool IsArray() const
{
return (m_holder->m_type == JSONType::Array);
}
bool IsObject() const
{
return (m_holder->m_type == JSONType::Object);
}
bool HasKey(std::string const& key) const
{
return IsObject() && m_holder->m_children.asObject.Contains(StringData(key.c_str(), key.length()));
}
bool HasKey(string_view const& key) const
{
return IsObject() && m_holder->m_children.asObject.Contains(StringData(key.data(), key.length()));
}
bool HasKey(char const* const key) const
{
return IsObject() && m_holder->m_children.asObject.Contains(StringData(key, strlen(key)));
}
bool HasKey(char const* const key, size_t length) const
{
return IsObject() && m_holder->m_children.asObject.Contains(StringData(key, length));
}
size_t Size();
std::string ToJSONString(bool pretty = false);
JSONObject& PushBack(JSONObject const& token);
JSONObject& PushBack(signed char value) { return PushBack((long long)(value)); }
JSONObject& PushBack(short value) { return PushBack((long long)(value)); }
JSONObject& PushBack(int value) { return PushBack((long long)(value)); }
JSONObject& PushBack(long value) { return PushBack((long long)(value)); }
JSONObject& PushBack(unsigned char value) { return PushBack((unsigned long long)(value)); }
JSONObject& PushBack(unsigned short value) { return PushBack((unsigned long long)(value)); }
JSONObject& PushBack(unsigned int value) { return PushBack((unsigned long long)(value)); }
JSONObject& PushBack(unsigned long value) { return PushBack((unsigned long long)(value)); }
JSONObject& PushBack(unsigned long long value);
JSONObject& PushBack(long long value);
JSONObject& PushBack(float value) { return PushBack((long double)(value)); }
JSONObject& PushBack(double value) { return PushBack((long double)(value)); }
JSONObject& PushBack(long double value);
JSONObject& PushBack(bool value);
JSONObject& PushBack(const char* const value);
JSONObject& PushBack(const char* const value, size_t length);
JSONObject& PushBack(std::string const& value);
JSONObject& PushBack(string_view const& value);
JSONObject& Insert(std::string const& name, JSONObject const& token) { return Insert(string_view(name.c_str(), name.length()), token); }
JSONObject& Insert(std::string const& name, signed char value) { return Insert(string_view(name.c_str(), name.length()), (long long)(value)); }
JSONObject& Insert(std::string const& name, short value) { return Insert(string_view(name.c_str(), name.length()), (long long)(value)); }
JSONObject& Insert(std::string const& name, int value) { return Insert(string_view(name.c_str(), name.length()), (long long)(value)); }
JSONObject& Insert(std::string const& name, long value) { return Insert(string_view(name.c_str(), name.length()), (long long)(value)); }
JSONObject& Insert(std::string const& name, unsigned char value) { return Insert(string_view(name.c_str(), name.length()), (unsigned long long)(value)); }
JSONObject& Insert(std::string const& name, unsigned short value) { return Insert(string_view(name.c_str(), name.length()), (unsigned long long)(value)); }
JSONObject& Insert(std::string const& name, unsigned int value) { return Insert(string_view(name.c_str(), name.length()), (unsigned long long)(value)); }
JSONObject& Insert(std::string const& name, unsigned long value) { return Insert(string_view(name.c_str(), name.length()), (unsigned long long)(value)); }
JSONObject& Insert(std::string const& name, unsigned long long value) { return Insert(string_view(name.c_str(), name.length()), value); }
JSONObject& Insert(std::string const& name, long long value) { return Insert(string_view(name.c_str(), name.length()), value); }
JSONObject& Insert(std::string const& name, float value) { return Insert(string_view(name.c_str(), name.length()), (long double)(value)); }
JSONObject& Insert(std::string const& name, double value) { return Insert(string_view(name.c_str(), name.length()), (long double)(value)); }
JSONObject& Insert(std::string const& name, long double value) { return Insert(string_view(name.c_str(), name.length()), value); }
JSONObject& Insert(std::string const& name, bool value) { return Insert(string_view(name.c_str(), name.length()), value); }
JSONObject& Insert(std::string const& name, const char* const value) { return Insert(string_view(name.c_str(), name.length()), value); }
JSONObject& Insert(std::string const& name, const char* const value, size_t length) { return Insert(string_view(name.c_str(), name.length()), value, length); }
JSONObject& Insert(std::string const& name, std::string const& value) { return Insert(string_view(name.c_str(), name.length()), value); }
JSONObject& Insert(std::string const& name, string_view const& value) { return Insert(string_view(name.c_str(), name.length()), value); }
JSONObject& Insert(string_view const& name, JSONObject const& token);
JSONObject& Insert(string_view const& name, signed char value) { return Insert(name, (long long)(value)); }
JSONObject& Insert(string_view const& name, short value) { return Insert(name, (long long)(value)); }
JSONObject& Insert(string_view const& name, int value) { return Insert(name, (long long)(value)); }
JSONObject& Insert(string_view const& name, long value) { return Insert(name, (long long)(value)); }
JSONObject& Insert(string_view const& name, unsigned char value) { return Insert(name, (unsigned long long)(value)); }
JSONObject& Insert(string_view const& name, unsigned short value) { return Insert(name, (unsigned long long)(value)); }
JSONObject& Insert(string_view const& name, unsigned int value) { return Insert(name, (unsigned long long)(value)); }
JSONObject& Insert(string_view const& name, unsigned long value) { return Insert(name, (unsigned long long)(value)); }
JSONObject& Insert(string_view const& name, unsigned long long value);
JSONObject& Insert(string_view const& name, long long value);
JSONObject& Insert(string_view const& name, float value) { return Insert(name, (long double)(value)); }
JSONObject& Insert(string_view const& name, double value) { return Insert(name, (long double)(value)); }
JSONObject& Insert(string_view const& name, long double value);
JSONObject& Insert(string_view const& name, bool value);
JSONObject& Insert(string_view const& name, const char* const value);
JSONObject& Insert(string_view const& name, const char* const value, size_t length);
JSONObject& Insert(string_view const& name, std::string const& value);
JSONObject& Insert(string_view const& name, string_view const& value);
JSONObject& Insert(char const* const name, JSONObject const& token) { return Insert(string_view(name, strlen(name)), token); }
JSONObject& Insert(char const* const name, signed char value) { return Insert(string_view(name, strlen(name)), (long long)(value)); }
JSONObject& Insert(char const* const name, short value) { return Insert(string_view(name, strlen(name)), (long long)(value)); }
JSONObject& Insert(char const* const name, int value) { return Insert(string_view(name, strlen(name)), (long long)(value)); }
JSONObject& Insert(char const* const name, long value) { return Insert(string_view(name, strlen(name)), (long long)(value)); }
JSONObject& Insert(char const* const name, unsigned char value) { return Insert(string_view(name, strlen(name)), (unsigned long long)(value)); }
JSONObject& Insert(char const* const name, unsigned short value) { return Insert(string_view(name, strlen(name)), (unsigned long long)(value)); }
JSONObject& Insert(char const* const name, unsigned int value) { return Insert(string_view(name, strlen(name)), (unsigned long long)(value)); }
JSONObject& Insert(char const* const name, unsigned long value) { return Insert(string_view(name, strlen(name)), (unsigned long long)(value)); }
JSONObject& Insert(char const* const name, unsigned long long value) { return Insert(string_view(name, strlen(name)), value); }
JSONObject& Insert(char const* const name, long long value) { return Insert(string_view(name, strlen(name)), value); }
JSONObject& Insert(char const* const name, float value) { return Insert(string_view(name, strlen(name)), (long double)(value)); }
JSONObject& Insert(char const* const name, double value) { return Insert(string_view(name, strlen(name)), (long double)(value)); }
JSONObject& Insert(char const* const name, long double value) { return Insert(string_view(name, strlen(name)), value); }
JSONObject& Insert(char const* const name, bool value) { return Insert(string_view(name, strlen(name)), value); }
JSONObject& Insert(char const* const name, const char* const value) { return Insert(string_view(name, strlen(name)), value); }
JSONObject& Insert(char const* const name, const char* const value, size_t length) { return Insert(string_view(name, strlen(name)), value, length); }
JSONObject& Insert(char const* const name, std::string const& value) { return Insert(string_view(name, strlen(name)), value); }
JSONObject& Insert(char const* const name, string_view const& value) { return Insert(string_view(name, strlen(name)), value); }
static JSONObject Array()
{
return JSONObject(JSONType::Array, string_view());
}
static JSONObject Object()
{
return JSONObject(JSONType::Object, string_view());
}
static JSONObject String(char const* const data)
{
return JSONObject(JSONType::String, string_view(data));
}
static JSONObject String(char const* const data, size_t length)
{
return JSONObject(JSONType::String, string_view(data, length));
}
static JSONObject String(string_view const& data)
{
return JSONObject(JSONType::String, data);
}
static JSONObject Number(signed char value) { return Number((long long)(value)); }
static JSONObject Number(short value) { return Number((long long)(value)); }
static JSONObject Number(int value) { return Number((long long)(value)); }
static JSONObject Number(long value) { return Number((long long)(value)); }
static JSONObject Number(unsigned char value) { return Number((unsigned long long)(value)); }
static JSONObject Number(unsigned short value) { return Number((unsigned long long)(value)); }
static JSONObject Number(unsigned int value) { return Number((unsigned long long)(value)); }
static JSONObject Number(unsigned long value) { return Number((unsigned long long)(value)); }
static JSONObject Number(long long data)
{
return JSONObject(JSONType::Integer, data);
}
static JSONObject Number(unsigned long long data)
{
return JSONObject(JSONType::Integer, data);
}
static JSONObject Number(long double data)
{
return JSONObject(JSONType::Double, data);
}
static JSONObject Boolean(bool data)
{
return JSONObject(JSONType::Boolean, data);
}
static JSONObject Null()
{
return JSONObject(JSONType::Null);
}
static JSONObject Empty()
{
return JSONObject(JSONType::Empty);
}
static JSONObject FromString(string_view const& jsonStr)
{
char const* data = jsonStr.data();
SkipWhitespace(data);
JSONType type = JSONType::Empty;
switch (data[0])
{
case '{': type = JSONType::Object; break;
case '[': type = JSONType::Array; break;
case '"': type = JSONType::String; break;
case 't':
case 'f': type = JSONType::Boolean; break;
case 'n': type = JSONType::Null; break;
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
type = JSONType::Integer; break;
default:
throw InvalidJSON();
}
return JSONObject(StringData(nullptr, 0), data, type);
}
~JSONObject();
JSONObject();
JSONObject(JSONObject const& other);
JSONObject& operator=(JSONObject const& other);
StringData const& KeyData() const
{
return m_key;
}
class JSONTokenAllocator : public std::allocator<JSONObject>
{
public:
template< class U, class... Args >
void construct(U* p, Args&& ... args)
{
::new((void*)p) U(std::forward<Args>(args)...);
}
template<class U>
struct rebind
{
typedef std::allocator<U> other;
};
template<>
struct rebind<JSONObject>
{
typedef JSONTokenAllocator other;
};
};
friend class JSONTokenAllocator;
typedef SkipProbe::HashMap<StringData, JSONObject> TokenMap;
typedef std::vector<JSONObject, JSONTokenAllocator> TokenList;
class iterator;
typedef iterator const const_iterator;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
const_iterator cbegin() const;
const_iterator cend() const;
JSONObject ShallowCopy();
JSONObject DeepCopy();
protected:
JSONObject(StringData const& myKey, char const*& data, JSONType expectedType);
JSONObject(JSONType statedType, string_view const& data);
JSONObject(JSONType statedType, bool data);
JSONObject(JSONType statedType, long long data);
JSONObject(JSONType statedType, unsigned long long data);
JSONObject(JSONType statedType);
JSONObject(JSONType statedType, long double data);
JSONObject(StringData const& myKey, JSONType statedType, string_view const& data);
JSONObject(StringData const& myKey, JSONType statedType, bool data);
JSONObject(StringData const& myKey, JSONType statedType, long long data);
JSONObject(StringData const& myKey, JSONType statedType, unsigned long long data);
JSONObject(StringData const& myKey, JSONType statedType);
JSONObject(StringData const& myKey, JSONType statedType, long double data);
JSONObject(StringData const& myKey, JSONObject const& other);
private:
void BuildJSONString(std::stringstream& outString, bool pretty, int tabDepth);
void IncRef()
{
++m_holder->refCount;
}
void DecRef()
{
if (--m_holder->refCount == 0)
{
Holder::Free(m_holder);
}
}
static void SkipWhitespace(char const*& data);
static void CollectString(char const*& data);
void ParseString(char const*& data);
void ParseNumber(char const*& data);
void ParseBool(char const*& data);
void ParseArray(char const*& data);
void ParseObject(char const*& data);
struct Holder
{
StringData m_data;
JSONType m_type;
union Children
{
TokenMap asObject;
TokenList asArray;
nullptr_t asNull;
// Construction and destruction handled in Holder constructor/destructor.
Children() : asNull(nullptr) {}
~Children() {}
} m_children;
int refCount;
bool Unique() { return refCount == 1; }
Holder(JSONType forType);
static Holder* Create();
static void Free(Holder* holder);
~Holder();
};
Holder* m_holder;
StringData m_key;
static JSONObject GetEmpty()
{
static JSONObject staticEmpty(JSONType::Empty);
return staticEmpty;
}
};
class JSONObject::iterator
{
public:
iterator(TokenList::iterator it, TokenList::iterator begin, TokenList::iterator end)
: mapIter()
, arrayBegin(begin)
, arrayIter(it)
, arrayEnd(end)
, type(JSONType::Array)
{
//
}
iterator(TokenMap::Iterator it)
: mapIter(it)
, arrayBegin()
, arrayIter()
, arrayEnd()
, type(JSONType::Object)
{
//
}
iterator(std::nullptr_t)
: mapIter()
, arrayBegin()
, arrayIter()
, arrayEnd()
, type(JSONType::Empty)
{
//
}
JSONObject& operator*()
{
if (type == JSONType::Array)
{
return *arrayIter;
}
return mapIter->value;
}
JSONObject* operator->()
{
if (type == JSONType::Array)
{
return &*arrayIter;
}
return &mapIter->value;
}
JSONObject const& operator*() const
{
if (type == JSONType::Array)
{
return *arrayIter;
}
return mapIter->value;
}
JSONObject const* operator->() const
{
if (type == JSONType::Array)
{
return &*arrayIter;
}
return &mapIter->value;
}
JSONType Type()
{
return type;
}
size_t Index() const
{
if (type == JSONType::Array)
{
return arrayIter - arrayBegin;
}
return size_t(-1);
}
string_view Key() const
{
if (type == JSONType::Array)
{
return "";
}
return string_view(mapIter->key.c_str(), mapIter->key.length());
}
JSONObject& Value()
{
if (type == JSONType::Array)
{
return *arrayIter;
}
return mapIter->value;
}
JSONObject const& Value() const
{
if (type == JSONType::Array)
{
return *arrayIter;
}
return mapIter->value;
}
iterator& operator++()
{
if (type == JSONType::Array)
{
++arrayIter;
}
else
{
++mapIter;
}
return *this;
}
iterator operator++(int)
{
iterator tmp(*this);
++(*this);
return tmp;
}
bool operator==(iterator const& rhs) const
{
if (type == JSONType::Array)
{
return arrayIter == rhs.arrayIter;
}
return mapIter == rhs.mapIter;
}
bool operator!=(iterator const& rhs) const
{
return !this->operator==(rhs);
}
operator bool() const
{
return Valid();
}
bool operator!() const
{
return !Valid();
}
bool Valid() const
{
if (type == JSONType::Empty)
{
return false;
}
else if (type == JSONType::Array)
{
return arrayIter != arrayEnd;
}
return mapIter.Valid();
}
iterator Next()
{
return ++(*this);
}
private:
JSONObject::TokenMap::Iterator mapIter;
TokenList::iterator arrayBegin;
TokenList::iterator arrayIter;
TokenList::iterator arrayEnd;
JSONType type;
};
}
#include "LightningJSON.inl"
#ifdef _WIN32
#pragma warning( pop )
#endif
| 27.874725 | 161 | 0.685918 | ShadauxCat |
042df8fb4e525f45ef7c9287b0dac892d3e43807 | 912 | cpp | C++ | Thread/ThreadWorker.cpp | ReliaSolve/acl | a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9 | [
"MIT"
] | null | null | null | Thread/ThreadWorker.cpp | ReliaSolve/acl | a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9 | [
"MIT"
] | null | null | null | Thread/ThreadWorker.cpp | ReliaSolve/acl | a0b305e7bf6a2d86839fb6f00d7d8fbf2bd583b9 | [
"MIT"
] | null | null | null | /**
* \copyright Copyright 2021 Aqueti, Inc. All rights reserved.
* \license This project is released under the MIT Public License.
**/
/******************************************************************************
*
* \file ThreadWorker.cpp
* \brief
* \author Andrew Ferg
*
* Copyright Aqueti 2019
*
*****************************************************************************/
#include "ThreadWorker.h"
namespace acl {
ThreadWorker::ThreadWorker(std::function<void()> f)
{
m_mainLoopFunction = f;
}
ThreadWorker::~ThreadWorker()
{
Stop();
Join();
}
void ThreadWorker::setMainLoopFunction(std::function<void()> f)
{
std::lock_guard<std::mutex> l(m_mainLoopMutex);
m_mainLoopFunction = f;
}
void ThreadWorker::mainLoop()
{
std::lock_guard<std::mutex> l(m_mainLoopMutex);
if (m_mainLoopFunction) {
m_mainLoopFunction();
}
}
} //end namespace acl
| 19.826087 | 79 | 0.551535 | ReliaSolve |
042f57116906e71cd70934a76e07f29e306daf67 | 30,948 | cpp | C++ | tests/unit/security/transform/private-key.t.cpp | named-data/ndn-cxx | d1b6f95864d9ca6a60d632e4f0565d665578a048 | [
"OpenSSL"
] | 106 | 2015-01-06T10:08:29.000Z | 2022-02-27T13:40:16.000Z | tests/unit/security/transform/private-key.t.cpp | named-data/ndn-cxx | d1b6f95864d9ca6a60d632e4f0565d665578a048 | [
"OpenSSL"
] | 6 | 2015-10-15T23:21:06.000Z | 2016-12-20T19:03:10.000Z | tests/unit/security/transform/private-key.t.cpp | named-data/ndn-cxx | d1b6f95864d9ca6a60d632e4f0565d665578a048 | [
"OpenSSL"
] | 147 | 2015-01-15T15:07:29.000Z | 2022-02-03T13:08:43.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2021 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx library is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#include "ndn-cxx/security/transform/private-key.hpp"
#include "ndn-cxx/encoding/buffer-stream.hpp"
#include "ndn-cxx/security/impl/openssl.hpp"
#include "ndn-cxx/security/key-params.hpp"
#include "ndn-cxx/security/transform/base64-decode.hpp"
#include "ndn-cxx/security/transform/bool-sink.hpp"
#include "ndn-cxx/security/transform/buffer-source.hpp"
#include "ndn-cxx/security/transform/public-key.hpp"
#include "ndn-cxx/security/transform/signer-filter.hpp"
#include "ndn-cxx/security/transform/stream-sink.hpp"
#include "ndn-cxx/security/transform/verifier-filter.hpp"
#include "ndn-cxx/util/string-helper.hpp"
#include "tests/boost-test.hpp"
#include <boost/mpl/vector.hpp>
#include <sstream>
namespace ndn {
namespace security {
namespace transform {
namespace tests {
BOOST_AUTO_TEST_SUITE(Security)
BOOST_AUTO_TEST_SUITE(Transform)
BOOST_AUTO_TEST_SUITE(TestPrivateKey)
BOOST_AUTO_TEST_CASE(Empty)
{
// test invoking member functions on an empty (default-constructed) PrivateKey
PrivateKey sKey;
BOOST_CHECK_EQUAL(sKey.getKeyType(), KeyType::NONE);
BOOST_CHECK_EQUAL(sKey.getKeySize(), 0);
BOOST_CHECK_THROW(sKey.getKeyDigest(DigestAlgorithm::SHA256), PrivateKey::Error);
BOOST_CHECK_THROW(sKey.derivePublicKey(), PrivateKey::Error);
const uint8_t theAnswer = 42;
BOOST_CHECK_THROW(sKey.decrypt(&theAnswer, sizeof(theAnswer)), PrivateKey::Error);
std::ostringstream os;
BOOST_CHECK_THROW(sKey.savePkcs1(os), PrivateKey::Error);
std::string passwd("password");
BOOST_CHECK_THROW(sKey.savePkcs8(os, passwd.data(), passwd.size()), PrivateKey::Error);
}
#if OPENSSL_VERSION_NUMBER < 0x30000000L // FIXME #5154
BOOST_AUTO_TEST_CASE(KeyDigest)
{
const Buffer buf(16);
PrivateKey sKey;
sKey.loadRaw(KeyType::HMAC, buf.data(), buf.size());
auto digest = sKey.getKeyDigest(DigestAlgorithm::SHA256);
const uint8_t expected[] = {
0x37, 0x47, 0x08, 0xff, 0xf7, 0x71, 0x9d, 0xd5, 0x97, 0x9e, 0xc8, 0x75, 0xd5, 0x6c, 0xd2, 0x28,
0x6f, 0x6d, 0x3c, 0xf7, 0xec, 0x31, 0x7a, 0x3b, 0x25, 0x63, 0x2a, 0xab, 0x28, 0xec, 0x37, 0xbb,
};
BOOST_CHECK_EQUAL_COLLECTIONS(digest->begin(), digest->end(),
expected, expected + sizeof(expected));
}
#endif
BOOST_AUTO_TEST_CASE(LoadRaw)
{
const Buffer buf(32);
PrivateKey sKey;
sKey.loadRaw(KeyType::HMAC, buf.data(), buf.size());
#if OPENSSL_VERSION_NUMBER < 0x30000000L // FIXME #5154
BOOST_CHECK_EQUAL(sKey.getKeyType(), KeyType::HMAC);
BOOST_CHECK_EQUAL(sKey.getKeySize(), 256);
#endif
PrivateKey sKey2;
BOOST_CHECK_THROW(sKey2.loadRaw(KeyType::NONE, buf.data(), buf.size()), std::invalid_argument);
BOOST_CHECK_THROW(sKey2.loadRaw(KeyType::RSA, buf.data(), buf.size()), std::invalid_argument);
BOOST_CHECK_THROW(sKey2.loadRaw(KeyType::EC, buf.data(), buf.size()), std::invalid_argument);
BOOST_CHECK_THROW(sKey2.loadRaw(KeyType::AES, buf.data(), buf.size()), std::invalid_argument);
}
struct RsaKey_DesEncrypted
{
const size_t keySize = 2048;
const std::string privateKeyPkcs1 =
R"PEM(MIIEpAIBAAKCAQEAw0WM1/WhAxyLtEqsiAJgWDZWuzkYpeYVdeeZcqRZzzfRgBQT
sNozS5t4HnwTZhwwXbH7k3QN0kRTV826Xobws3iigohnM9yTK+KKiayPhIAm/+5H
GT6SgFJhYhqo1/upWdueojil6RP4/AgavHhopxlAVbk6G9VdVnlQcQ5Zv0OcGi73
c+EnYD/YgURYGSngUi/Ynsh779p2U69/te9gZwIL5PuE9BiO6I39cL9z7EK1SfZh
OWvDe/qH7YhD/BHwcWit8FjRww1glwRVTJsA9rH58ynaAix0tcR/nBMRLUX+e3rU
RHg6UbSjJbdb9qmKM1fTGHKUzL/5pMG6uBU0ywIDAQABAoIBADQkckOIl4IZMUTn
W8LFv6xOdkJwMKC8G6bsPRFbyY+HvC2TLt7epSvfS+f4AcYWaOPcDu2E49vt2sNr
cASly8hgwiRRAB3dHH9vcsboiTo8bi2RFvMqvjv9w3tK2yMxVDtmZamzrrnaV3YV
Q+5nyKo2F/PMDjQ4eUAKDOzjhBuKHsZBTFnA1MFNI+UKj5X4Yp64DFmKlxTX/U2b
wzVywo5hzx2Uhw51jmoLls4YUvMJXD0wW5ZtYRuPogXvXb/of9ef/20/wU11WFKg
Xb4gfR8zUXaXS1sXcnVm3+24vIs9dApUwykuoyjOqxWqcHRec2QT2FxVGkFEraze
CPa4rMECgYEA5Y8CywomIcTgerFGFCeMHJr8nQGqY2V/owFb3k9maczPnC9p4a9R
c5szLxA9FMYFxurQZMBWSEG2JS1HR2mnjigx8UKjYML/A+rvvjZOMe4M6Sy2ggh4
SkLZKpWTzjTe07ByM/j5v/SjNZhWAG7sw4/LmPGRQkwJv+KZhGojuOkCgYEA2cOF
T6cJRv6kvzTz9S0COZOVm+euJh/BXp7oAsAmbNfOpckPMzqHXy8/wpdKl6AAcB57
OuztlNfV1D7qvbz7JuRlYwQ0cEfBgbZPcz1p18HHDXhwn57ZPb8G33Yh9Omg0HNA
Imb4LsVuSqxA6NwSj7cpRekgTedrhLFPJ+Ydb5MCgYEAsM3Q7OjILcIg0t6uht9e
vrlwTsz1mtCV2co2I6crzdj9HeI2vqf1KAElDt6G7PUHhglcr/yjd8uEqmWRPKNX
ddnnfVZB10jYeP/93pac6z/Zmc3iU4yKeUe7U10ZFf0KkiiYDQd59CpLef/2XScS
HB0oRofnxRQjfjLc4muNT+ECgYEAlcDk06MOOTly+F8lCc1bA1dgAmgwFd2usDBd
Y07a3e0HGnGLN3Kfl7C5i0tZq64HvxLnMd2vgLVxQlXGPpdQrC1TH+XLXg+qnlZO
ivSH7i0/gx75bHvj75eH1XK65V8pDVDEoSPottllAIs21CxLw3N1ObOZWJm2EfmR
cuHICmsCgYAtFJ1idqMoHxES3mlRpf2JxyQudP3SCm2WpGmqVzhRYInqeatY5sUd
lPLHm/p77RT7EyxQHTlwn8FJPuM/4ZH1rQd/vB+Y8qAtYJCexDMsbvLW+Js+VOvk
jweEC0nrcL31j9mF0vz5E6tfRu4hhJ6L4yfWs0gSejskeVB/w8QY4g==
)PEM";
const std::string privateKeyPkcs8 =
R"PEM(MIIFCzA9BgkqhkiG9w0BBQ0wMDAbBgkqhkiG9w0BBQwwDgQIOKYJXvB6p8kCAggA
MBEGBSsOAwIHBAiQgMK8kQXTyASCBMjeNiKYYw5/yHgs9BfSGrpqvV0LkkgMQNUW
R4ZY8fuNjZynd+PxDuw2pyrv1Yv3jc+tupwUehZEzYOnGd53wQAuLO+Z0TBgRFN7
Lhk+AxlT7hu0xaB3ZpJ/uvWpgEJHsq/aB/GYgyzXcQo2AiqzERVpMCWJVmE1L977
CHwJmLm5mxclVLYp1UK5lkIBFu/M4nPavmNmYNUU1LOrXRo56TlJ2kUp8gQyQI1P
VPxi4chmlsr/OnQ2d1eZN+euFm0CS+yP+LFgI9ZqdyH1w+J43SXdHDzauVcZp7oa
Kw24OrhHfolLAnQIECXEJYeT7tZmhC4O9V6B18PFVyxWnEU4eFNpFE8kYSmm8Um2
buvDKI71q43hm23moYT9uIM1f4M8UkoOliJGrlf4xgEcmDuokEX01PdOq1gc4nvG
0DCwDI9cOsyn8cxhk9UVtFgzuG/seuznxIv1F5H0hzYOyloStXxRisJES0kgByBt
FFTfyoFKRrmCjRIygwVKUSkSDR0DlQS5ZLvQyIswnSQFwxAHqfvoSL4dB9UAIAQ+
ALVF1maaHgptbL6Ifqf0GFCv0hdNCVNDNCdy8R+S6nEYE+YdYSIdT1L88KD5PjU3
YY/CMnxhTncMaT4acPO1UUYuSGRZ/JL6E0ihoqIU+bqUgLSHNzhPySPfN9uqN61Y
HFBtxeEPWKU0f/JPkRBMmZdMI1/OVmA3QHSRBydI+CQN8no2gZRFoVbHTkG8IMpE
1fiDJpwFkpzIv/JPiTSE7DeBH5NJk1bgu7TcuZfa4unyAqss0UuLnXzS06TppkUj
QGft0g8VPW56eli6B4xrSzzuvAdbrxsVfxdmtHPyYxLb3/UG1g4x/H/yULhx7x9P
iI6cw6JUE+8bwJV2ZIlHXXHO+wUp/gCFJ6MHo9wkR1QvnHP2ClJAzBm9OvYnUx2Y
SX0HxEowW8BkhxOF184LEmxeua0yyZUqCdrYmErp7x9EY/LhD1zBwH8OGRa0qzmR
VKxAPKihkb9OgxcUKbvKePx3k2cQ7fbCUspGPm4Kn1zwMgRAZ4fz/o8Lnwc8MSY3
lPWnmLTFu420SRH2g9N0o/r195hiZ5cc+KfF4pwZWKbEbKFk/UfXA9vmOi7BBtDJ
RWshOINhzMU6Ij3KuaEpHni1HoHjw0SQ97ow2x/aB8k2QC28tbsa49lD2KKJku6b
2Or89adwFKqMgS2IXfXMXs/iG5EFLYN6r8e40Dn5f1vJfRLJl03XByIfT2n92pw3
fP7muOIKLUsEKjOrmn94NwMlfeW13oQHEH2KjPOWFS/tyJHDdVU+of4COH5yg59a
TZqFkOTGeliE1O+6sfF9fRuVxFUF3D8Hpr0JIjdc6+3RgIlGsXc8BwiSjDSI2XW+
vo75/2zPU9t8OeXEIJk2CQGyqLwUJ6dyi/yDRrvZAgjrUvbpcxydnBAHrLbLUGXJ
aEHH2tjEtnTqVyTchr1yHoupcFOCkA0dAA66XqwcssQxJiMGrWTpCbgd9mrTXQaZ
U7afFN1jpO78tgBQUUpImXdHLLsqdN5tefqjileZGZ9x3/C6TNAfDwYJdsicNNn5
y+JVsbltfLWlJxb9teb3dtQiFlJ7ofprLJnJVqI/Js8lozY+KaxV2vtbZkcD4dM=
)PEM";
const std::string publicKey =
R"PEM(MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw0WM1/WhAxyLtEqsiAJg
WDZWuzkYpeYVdeeZcqRZzzfRgBQTsNozS5t4HnwTZhwwXbH7k3QN0kRTV826Xobw
s3iigohnM9yTK+KKiayPhIAm/+5HGT6SgFJhYhqo1/upWdueojil6RP4/AgavHho
pxlAVbk6G9VdVnlQcQ5Zv0OcGi73c+EnYD/YgURYGSngUi/Ynsh779p2U69/te9g
ZwIL5PuE9BiO6I39cL9z7EK1SfZhOWvDe/qH7YhD/BHwcWit8FjRww1glwRVTJsA
9rH58ynaAix0tcR/nBMRLUX+e3rURHg6UbSjJbdb9qmKM1fTGHKUzL/5pMG6uBU0
ywIDAQAB
)PEM";
};
struct RsaKey_Aes256Encrypted
{
// Generated with OpenSSL 3.0.0
// openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -outform PEM -out key.pem
// openssl pkcs8 -in key.pem -nocrypt -traditional -outform PEM -out pvt1.pem
// openssl pkcs8 -in key.pem -topk8 -v2 aes256 -passout pass:password -outform PEM -out pvt8.pem
// openssl pkey -in key.pem -pubout -outform PEM -out pub.pem
const size_t keySize = 2048;
const std::string privateKeyPkcs1 =
R"PEM(MIIEowIBAAKCAQEAzEKtiRrzvhwGDMpsUlKMd7Veo9+lvLpttdX/ETo2exU36HqV
6zSM7LnpfqId7zug+l+VGwPd+oJOzROSCAoUcP3C3m9CkfqT97H9g2zdfwXqJnMQ
tnpAGngXOTF6RSBDVqo+jfeRw3c+MCXDZ0cHd49uv+CnWks6Sj+gowppdsQfvQRr
2incnwqht3JuaiTytxNrk6DjpoNTHyZJ53SY6DibGSk6aDFWMJcfvTZ6EuUbcepP
7HRwABn4Ctj1FTx3hDPe4sIrBFrbfP7yDQ9NxYh1baxXcCjWfCS43qUjrtcQFVkK
vE3uucmw1rf0C0Wy7dDvF2n1v+WLAEPSgJnumwIDAQABAoIBAEdNgWGKkIqNIsmF
QhHssg85t2tSL3t1wsWGic8cOJd3vTgAzuO3yPf8IBeuBPAVqyirhBPVokAIC/UH
v2LiDeexlbxrL1xhEhUVw48Eyj9Es8uvQCbK/ySeRlEXRfzqecc/j62kPfRzZDiP
fipHv8ILRlhh1lmtSBBSLMOtZ0pnJUmrNIOaFlJa56t0G3a+4C1u2swOtoCOWtyR
o7NAHiCcZNbnFQQSLyfDj3Sqnsaxke41A+gtrSeeUHkqnP0rxdmqChdyU36Yszi2
nB+yUXJT7Iw5GD+/vVUoby1/FVCRbh8zNfXvozC3llUSmsn3CBzVLoI+uwD5/zSz
+zMZ1x0CgYEA1o/cuEnALy+FXYbyrdV2R+ecy6t2/3WFDmK7+7klFFHcPBbmh/nL
OIjFPHVYUcyv2qW6JnCYqCutPOJ97JGvyScriNdg047UPGHaFaPZY/4rTXLm6tzN
I6E5eTRLkaFDVb96zYevxLjf88Lceocp2g8vR88kHqKe//0K8sBw+n0CgYEA87WA
CJOzmBdeWN7GbfA9rqxQq8qsFMaG+mJ5sE1MQHW5j/Hzsj6xi5qS9Uy8D9qlQiSV
nA/frqNBjaXiagVIqvfKvkkOFqRFIkVfGIJcYJk3tzi3tgdcHJ0B0LNCg/xHtjuZ
9KiuBNlDfkhsV6d7g/YQ0Sf/ghWmSGyOtVEtQPcCgYEAs5wYK1jpfVZtcN5/lc8k
RYr4MXJmmfB5opI6RL028eyYzOBquJb9bGTpnvOoLEmJSCIFUxpcYCK30UjUGs3V
9jBI/DM3hcGBns5W7liLqW3iN+IgtaiCPPpAj1qci9sP797rYNPd6nLMXlTXleZB
vZ2KebVHyjFdonLj0FQR/00CgYBSbXLuc7ZsnIrGmCKZEIZsS8/FKvlk1XjVuvTZ
kmtV6ftnGjiIcvft9cv6t4dr/VGju2f2rs/C62jClfasUTkwyjqCfYcMVWcknj35
ti20Zl4X1FEeegLHkrsIcXjv1yYSFrqNq3egIDPZxHkQdI8sJM+vTk33G4dwO3dR
EDG0JQKBgBeZhFw4R4MgCYUjNecw+k6AcU5J1JZ+KCJpSBv6J9ilQhkM0PeGLEab
TsurvpoIdAlqojgMnNf98gBahz+zjyLJEB+SPU6AGsahkQZ8wRY1a7ua/SjHPbCk
I3CkY6wqJK8vcjQkUQhE+5y1ZBIhQpH22eHyM4WMLaTFsL9yMvzY
)PEM";
const std::string privateKeyPkcs8 =
R"PEM(MIIFLTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIc3ZMcKTZDhcCAggA
MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBA1/62RtDr/mX2ZuI3Nq9tTBIIE
0ITRsiXopz4ox+k3ltt64vwQDLrKhm3uoz9lb885mD/wDkRU+02a3Kq+LjhExawM
Po8VVIbMjyXa3c2eYlmPOUXuXyMz8zi1NyDD1ypZTcVQxIT1ZZK+qsTlIy9Q2MIt
PU/Xg/nPCCJn7FBjkjqpGa942SVnvAbBLk342y8XozHmdbKYDVvNRjkYd6zUpR/n
5EG1AHBHNFySbtJSg5/6HU5sX6pM7LNAiTT3i0r8LcCWijHofhmUbCfrg+DdgW5+
ttmsTo/HZCjSSsHtd6xqxdOJyfvFIV1BvVKFP5X6OK8cnHtk/0SuNt2OROjvbOtU
JqSGkzV6MukagrMVtTu9BuXGNz8ee1zVglArEwHw13MihI9a/lGD/AujwjU9CdOd
jH6l2Ibp1MrSn52injoY9i6VmFSTktOrTrIzkGVevHcHkyZBqN3mwQRL3M16t0Bp
RJl01z5b7UYoSDO/w4BOtf6NK/zWix1+GHDnz9fplsaebiDF3YFOq6+p+1/14zPg
cfMkqgco6AGijPimhCQhMVnuWoBKcwIHCs6+sp02lI5HsVl3Lke4586w3qqOU9QY
L8iJFlLax/Sm9MVM/usWUaolXY6BElqkqhd3Z7KJoCazWos2oxVHkutKArNYf9XI
DV309jwBSnBDzmgDpXk7VZWFswxJIc8I1z5759wh370NJ06HeGCLvgBuLp6Dkq2c
hNqR32HWN7wjVqX2hB7X7RPjwX4a/z2oih/fQFc5WuIHfKWTviWcVq8jhIxocLqz
dSGWVvj6j0LoDh7s26iCXe6hb5N5khWHI6Dh7ZFC27aSejljyNqB+KEblIHvTPjS
WgGF14QTwDL6L4tpwtxoPG+QFnoHhM2ORkvwFkmQRmfSKeBfTapiRDLPQvlfIzTI
6Ie3l9gA4H14HqffawdwfP1fS/lOlLFH7SyO59tSjtVC3ErLMhHD+1R+Q3X1w/lF
jUZ2vwvE+86ikhxZvQCVOiCGXqry9qZfm67cuXD/tolAv5pV2qFDxHAEe5QqUYSv
bJTgo6zin1XByu3jlQPblcEeJ33iRcQDqh96GgMnJstsGuUjBREVjbNZ30YZYeVg
+L/h9otyO92Nq0knADHeixy9JZ2ATRMoTAT4XydSN9lHOh+K5pC3kf9pke2NCJyr
r/w9VQnQiIkxZ+THFshHHJxZZLlLwYWWr894rKftyZB+nDidNZfXr6K8VWoCAwh4
XwV6109KeHx86Kim9KQPn5RYVFdoxt2dO5O9vcXWtcNciIEi4MPyUM+oHwWrKTLX
EQsVu5gaz8vFt3lg0+Ctf8vAIA1/FxXEZ/BTAiV96lvRcUbXU2AdL+rNU2rtpqxH
h9L3r6IEN9WVIkNH5Q4CqSS9z+BxIPj76dA1MXK1nb8OJ9Y+BMPhktMz9M+KcVpD
1rXebv+/9Tw0lKLcNL50AglJOP+IRL0hHh62xtXs+FP5KocBs1kVAJORrS6wiy22
DGwcVmgTvWsPHzIf3IEa7DEjhClnU6alxKxCEmzPtm29upYXL9o3y7CMwidvCYpD
zFU2pIKA85YpjUYL25MiCyJPODc3VoW9l+rBqPu6bVWZXsfgsD4lcdFaJbPqcVby
PEe2dEUjhwpYgjbjOO7geMe+VeShipZJ63yFsNaPWzcz
)PEM";
const std::string publicKey =
R"PEM(MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzEKtiRrzvhwGDMpsUlKM
d7Veo9+lvLpttdX/ETo2exU36HqV6zSM7LnpfqId7zug+l+VGwPd+oJOzROSCAoU
cP3C3m9CkfqT97H9g2zdfwXqJnMQtnpAGngXOTF6RSBDVqo+jfeRw3c+MCXDZ0cH
d49uv+CnWks6Sj+gowppdsQfvQRr2incnwqht3JuaiTytxNrk6DjpoNTHyZJ53SY
6DibGSk6aDFWMJcfvTZ6EuUbcepP7HRwABn4Ctj1FTx3hDPe4sIrBFrbfP7yDQ9N
xYh1baxXcCjWfCS43qUjrtcQFVkKvE3uucmw1rf0C0Wy7dDvF2n1v+WLAEPSgJnu
mwIDAQAB
)PEM";
};
struct EcKeySpecifiedCurve_DesEncrypted
{
// EC keys are generated in "namedCurve" format only. However, old keys in "specifiedCurve"
// format are still accepted. See https://redmine.named-data.net/issues/5037
const size_t keySize = 256;
const std::string privateKeyPkcs1 =
R"PEM(MIIBaAIBAQQgRxwcbzK9RV6AHYFsDcykI86o3M/a1KlJn0z8PcLMBZOggfowgfcC
AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////
MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr
vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE
axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W
K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8
YyVRAgEBoUQDQgAEaG4WJuDAt0QkEM4t29KDUdzkQlMPGrqWzkWhgt9OGnwc6O7A
ZLPSrDyhwyrKS7XLRXml5DisQ93RvByll32y8A==
)PEM";
const std::string privateKeyPkcs8 =
R"PEM(MIIBwzA9BgkqhkiG9w0BBQ0wMDAbBgkqhkiG9w0BBQwwDgQIVHkBzLGtDvICAggA
MBEGBSsOAwIHBAhk6g9eI3toNwSCAYDd+LWPDBTrKV7vUyxTvDbpUd0eXfh73DKA
MHkdHuVmhpmpBbsF9XvaFuL8J/1xi1Yl2XGw8j3WyrprD2YEhl/+zKjNbdTDJmNO
SlomuwWb5AVCJ9reT94zIXKCnexUcyBFS7ep+P4dwuef0VjzprjfmnAZHrP+u594
ELHpKwi0ZpQLtcJjjud13bn43vbXb+aU7jmPV5lU2XP8TxaQJiYIibNEh1Y3TZGr
akJormYvhaYbiZkKLHQ9AvQMEjhoIW5WCB3q+tKZUKTzcQpjNnf9FOTeKN3jk3Kd
2OmibPZcbMJdgCD/nRVn1cBo7Hjn3IMjgtszQHtEUphOQiAkOJUnKmy9MTYqtcNN
6cuFItbu4QvbVwailgdUjOYwIJCmIxExlPV0ohS24pFGsO03Yn7W8rBB9VWENYmG
HkZIbGsHv7O9Wy7fv+FJgZkjeti0807IsNXSJl8LUK0ZIhAR7OU8uONWMsbHdQnk
q1HB1ZKa52ugACl7g/DF9b7CoSAjFeE=
)PEM";
const std::string publicKey =
R"PEM(MIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAA
AAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA////
///////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSd
NgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5
RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA
//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABGhuFibgwLdEJBDOLdvSg1Hc
5EJTDxq6ls5FoYLfThp8HOjuwGSz0qw8ocMqyku1y0V5peQ4rEPd0bwcpZd9svA=
)PEM";
};
struct EcKeyNamedCurve_DesEncrypted
{
// Generated with older (1.0.x?) OpenSSL
// openssl ecparam -name secp384r1 -genkey -out pvt1.pem
// openssl pkcs8 -in pvt1.pem -topk8 -passout pass:password -outform PEM -out pvt8.pem
// openssl ec -in pvt1.pem -pubout -outform PEM -out pub.pem
const size_t keySize = 384;
const std::string privateKeyPkcs1 =
R"PEM(MIGkAgEBBDCUsb7NymksCkQAjdLMjUilWhOEyeYmGi79sX1RbsmfnoF/8SesKBhO
or+TZ8g8/8igBwYFK4EEACKhZANiAARWGplLOGdQiXRFQcd0VLPeTt0zXEj5zvSv
aHx9MrzBy57wgz10wTAiR561wuLtFAYxmqL9Ikrzx/BaEg0+v2zQ05NCzMNN8v2c
7/FzOhD7fmZrlJsT6Q2aHGExW0Rj3GE=
)PEM";
const std::string privateKeyPkcs8 =
R"PEM(MIHgMBsGCSqGSIb3DQEFAzAOBAjniUjwJfWsMQICCAAEgcCakGTKa49csaPpmtzi
5sTJw+AH8ajUqcDbtp2pJP/Ni6M1p9fai9hOKPElf9uJuYh/S80FAU6WQmZBAxL4
bF598ncLPogpGvz21wLuSc1xnbD829zAsMmh0XZvMZpBWX2g0NnZJx7GOraskTSh
7qGu70B+uKzw+JxIzgBEeMcoBUg8mTEht5zghfLGYkQp6BpTPdpU64udpPAKzFNs
5X+BzBnT5Yy49/Lp4uYIji8qwJFF3VqTn8RFKunFYDDejRU=
)PEM";
const std::string publicKey =
R"PEM(MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEVhqZSzhnUIl0RUHHdFSz3k7dM1xI+c70
r2h8fTK8wcue8IM9dMEwIkeetcLi7RQGMZqi/SJK88fwWhINPr9s0NOTQszDTfL9
nO/xczoQ+35ma5SbE+kNmhxhMVtEY9xh
)PEM";
};
struct EcKeyNamedCurve_Aes256Encrypted
{
// Generated with OpenSSL 3.0.0
// openssl genpkey -quiet -algorithm EC -pkeyopt ec_paramgen_curve:P-384
// -pkeyopt ec_param_enc:named_curve -outform PEM -out key.pem
// openssl pkcs8 -in key.pem -nocrypt -traditional -outform PEM -out pvt1.pem
// openssl pkcs8 -in key.pem -topk8 -v2 aes256 -passout pass:password -outform PEM -out pvt8.pem
// openssl pkey -in key.pem -pubout -outform PEM -out pub.pem
const size_t keySize = 384;
const std::string privateKeyPkcs1 =
R"PEM(MIGkAgEBBDAa5I6hfwcDZ8Hzn6/ZU3jV/Fp6jZP+tgUHSdMcfRS3iLOY296KdcXd
xISVHU3g+XygBwYFK4EEACKhZANiAAQh3xGTxgMFXwoRNBCrnzawZnoQUojZ1Qe5
3VrR+9ECawVf2sPklX+Lw1pE1TG5q+YepM8imRclRbXLBSGPF6f+qJCiFWR71XS2
CX2kW/AZOGluxYrVMe22ns5TY2o50G8=
)PEM";
const std::string privateKeyPkcs8 =
R"PEM(MIIBHDBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIy4A7Il3JRNQCAggA
MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBBPYOn/2qSDBlKhZ6+ckre8BIHA
jXwlDh+OX+1VayCWohXUooxZPfgKmIVkxhNrQzn0DV/FW9WbiXC72vss75/o5O2H
o4EuIOxnbxIM5HhsrdDY5g8Abkk5gKYt+eVJQn1EPAR+PU9T8OUKyQr9rO0Pvsu8
9h5V9+WFHNnNBTN3pqIV5cU25oVX7tqeZKs+5I4QIaq4hzPj+k15dLFaaq5XejZH
KjMKNdKbfz4TEs7u1W9YyrD3Z8/RgzLwVRjJqqOKeoJF4b1lOqOd5rWb4Oa06alr
)PEM";
const std::string publicKey =
R"PEM(MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEId8Rk8YDBV8KETQQq582sGZ6EFKI2dUH
ud1a0fvRAmsFX9rD5JV/i8NaRNUxuavmHqTPIpkXJUW1ywUhjxen/qiQohVke9V0
tgl9pFvwGThpbsWK1THttp7OU2NqOdBv
)PEM";
};
struct EcKeyNamedCurve_Des3Encrypted
{
// Generated with OpenSSL 3.0.0
// openssl genpkey -quiet -algorithm EC -pkeyopt ec_paramgen_curve:P-256
// -pkeyopt ec_param_enc:named_curve -outform PEM -out key.pem
// openssl pkcs8 -in key.pem -nocrypt -traditional -outform PEM -out pvt1.pem
// openssl pkcs8 -in key.pem -topk8 -v2 des3 -passout pass:password -outform PEM -out pvt8.pem
// openssl pkey -in key.pem -pubout -outform PEM -out pub.pem
const size_t keySize = 256;
const std::string privateKeyPkcs1 =
R"PEM(MHcCAQEEIEbb/pnOVzkIZP4jrpZQCxl2OTJVQD7rHBJxxv8Aa215oAoGCCqGSM49
AwEHoUQDQgAEvSFhYwmFe17QAj0xhumERNJFf5MTkAegdE+db4ojchAbcDLRcnzY
+TUx5pTBqdBg+STMK7h36ZUn+KcMeizMRA==
)PEM";
const std::string privateKeyPkcs8 =
R"PEM(MIHjME4GCSqGSIb3DQEFDTBBMCkGCSqGSIb3DQEFDDAcBAj2rY09BeCZGgICCAAw
DAYIKoZIhvcNAgkFADAUBggqhkiG9w0DBwQI6CIHMAz7K7AEgZBzyr8QcH1OWEqc
ByPy4Vlze9D0izD7/NIxUeauHILqXMjU6Z057oYZ14Nm+DpbyJWu16gjZ2N+M2GH
4bH8gS6JUGhqtSbQ1Oo5lmjPXphefZp0tarv19Hp8S1VKmcVoj65kxfn5x0GKepg
fhXlMB2uQHvNoujU9PyeTZhwjAPQ6vHgFonbPPaL/f256NqMmnA=
)PEM";
const std::string publicKey =
R"PEM(MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvSFhYwmFe17QAj0xhumERNJFf5MT
kAegdE+db4ojchAbcDLRcnzY+TUx5pTBqdBg+STMK7h36ZUn+KcMeizMRA==
)PEM";
};
using KeyTestDataSets = boost::mpl::vector<
#if OPENSSL_VERSION_NUMBER < 0x30000000L
// DES-encrypted keys
// .privateKeyPkcs8 uses either the PBES1 or PBES2 encryption scheme with DES-CBC-Pad (see RFC 8018)
// This is no longer supported out-of-the-box by OpenSSL 3.0 and later
RsaKey_DesEncrypted,
EcKeySpecifiedCurve_DesEncrypted,
EcKeyNamedCurve_DesEncrypted,
#endif
// AES-encrypted keys
// .privateKeyPkcs8 uses the PBES2 encryption scheme with AES-CBC-Pad (see RFC 8018)
// This works with all supported versions of OpenSSL
RsaKey_Aes256Encrypted,
EcKeyNamedCurve_Aes256Encrypted,
// 3DES-encrypted keys
// .privateKeyPkcs8 uses the PBES2 encryption scheme with DES-EDE3-CBC-Pad (see RFC 8018)
// This works with all supported versions of OpenSSL
EcKeyNamedCurve_Des3Encrypted
>;
static void
checkPkcs8Encoding(const ConstBufferPtr& encoding,
const std::string& password,
const ConstBufferPtr& pkcs1)
{
PrivateKey sKey;
sKey.loadPkcs8(encoding->data(), encoding->size(), password.data(), password.size());
OBufferStream os;
sKey.savePkcs1(os);
BOOST_CHECK_EQUAL_COLLECTIONS(pkcs1->begin(), pkcs1->end(),
os.buf()->begin(), os.buf()->end());
}
static void
checkPkcs8Base64Encoding(const ConstBufferPtr& encoding,
const std::string& password,
const ConstBufferPtr& pkcs1)
{
OBufferStream os;
bufferSource(*encoding) >> base64Decode() >> streamSink(os);
checkPkcs8Encoding(os.buf(), password, pkcs1);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(SaveLoad, T, KeyTestDataSets)
{
T dataSet;
auto sKeyPkcs1Base64 = reinterpret_cast<const uint8_t*>(dataSet.privateKeyPkcs1.data());
auto sKeyPkcs1Base64Len = dataSet.privateKeyPkcs1.size();
OBufferStream os;
bufferSource(sKeyPkcs1Base64, sKeyPkcs1Base64Len) >> base64Decode() >> streamSink(os);
ConstBufferPtr sKeyPkcs1Buf = os.buf();
const uint8_t* sKeyPkcs1 = sKeyPkcs1Buf->data();
size_t sKeyPkcs1Len = sKeyPkcs1Buf->size();
// load key in base64-encoded pkcs1 format
PrivateKey sKey;
BOOST_CHECK_NO_THROW(sKey.loadPkcs1Base64(sKeyPkcs1Base64, sKeyPkcs1Base64Len));
BOOST_CHECK_EQUAL(sKey.getKeySize(), dataSet.keySize);
std::stringstream ss2(dataSet.privateKeyPkcs1);
PrivateKey sKey2;
BOOST_CHECK_NO_THROW(sKey2.loadPkcs1Base64(ss2));
// load key in pkcs1 format
PrivateKey sKey3;
BOOST_CHECK_NO_THROW(sKey3.loadPkcs1(sKeyPkcs1, sKeyPkcs1Len));
BOOST_CHECK_EQUAL(sKey3.getKeySize(), dataSet.keySize);
std::stringstream ss4;
ss4.write(reinterpret_cast<const char*>(sKeyPkcs1), sKeyPkcs1Len);
PrivateKey sKey4;
BOOST_CHECK_NO_THROW(sKey4.loadPkcs1(ss4));
// save key in base64-encoded pkcs1 format
OBufferStream os2;
BOOST_REQUIRE_NO_THROW(sKey.savePkcs1Base64(os2));
BOOST_CHECK_EQUAL_COLLECTIONS(sKeyPkcs1Base64, sKeyPkcs1Base64 + sKeyPkcs1Base64Len,
os2.buf()->begin(), os2.buf()->end());
// save key in pkcs1 format
OBufferStream os3;
BOOST_REQUIRE_NO_THROW(sKey.savePkcs1(os3));
BOOST_CHECK_EQUAL_COLLECTIONS(sKeyPkcs1, sKeyPkcs1 + sKeyPkcs1Len,
os3.buf()->begin(), os3.buf()->end());
auto sKeyPkcs8Base64 = reinterpret_cast<const uint8_t*>(dataSet.privateKeyPkcs8.data());
auto sKeyPkcs8Base64Len = dataSet.privateKeyPkcs8.size();
OBufferStream os4;
bufferSource(sKeyPkcs8Base64, sKeyPkcs8Base64Len) >> base64Decode() >> streamSink(os4);
const uint8_t* sKeyPkcs8 = os4.buf()->data();
size_t sKeyPkcs8Len = os4.buf()->size();
std::string password("password");
std::string wrongpw("wrongpw");
auto pwCallback = [&password] (char* buf, size_t size, int) -> int {
BOOST_REQUIRE_LE(password.size(), size);
std::copy(password.begin(), password.end(), buf);
return static_cast<int>(password.size());
};
// load key in base64-encoded pkcs8 format
PrivateKey sKey5;
BOOST_CHECK_NO_THROW(sKey5.loadPkcs8Base64(sKeyPkcs8Base64, sKeyPkcs8Base64Len,
password.data(), password.size()));
BOOST_CHECK_EQUAL(sKey5.getKeySize(), dataSet.keySize);
PrivateKey sKey6;
BOOST_CHECK_NO_THROW(sKey6.loadPkcs8Base64(sKeyPkcs8Base64, sKeyPkcs8Base64Len, pwCallback));
std::stringstream ss7(dataSet.privateKeyPkcs8);
PrivateKey sKey7;
BOOST_CHECK_NO_THROW(sKey7.loadPkcs8Base64(ss7, password.data(), password.size()));
std::stringstream ss8(dataSet.privateKeyPkcs8);
PrivateKey sKey8;
BOOST_CHECK_NO_THROW(sKey8.loadPkcs8Base64(ss8, pwCallback));
// load key in pkcs8 format
PrivateKey sKey9;
BOOST_CHECK_NO_THROW(sKey9.loadPkcs8(sKeyPkcs8, sKeyPkcs8Len, password.data(), password.size()));
BOOST_CHECK_EQUAL(sKey9.getKeySize(), dataSet.keySize);
PrivateKey sKey10;
BOOST_CHECK_NO_THROW(sKey10.loadPkcs8(sKeyPkcs8, sKeyPkcs8Len, pwCallback));
std::stringstream ss11;
ss11.write(reinterpret_cast<const char*>(sKeyPkcs8), sKeyPkcs8Len);
PrivateKey sKey11;
BOOST_CHECK_NO_THROW(sKey11.loadPkcs8(ss11, password.data(), password.size()));
std::stringstream ss12;
ss12.write(reinterpret_cast<const char*>(sKeyPkcs8), sKeyPkcs8Len);
PrivateKey sKey12;
BOOST_CHECK_NO_THROW(sKey12.loadPkcs8(ss12, pwCallback));
// load key using wrong password, Error is expected
PrivateKey sKey13;
BOOST_CHECK_THROW(sKey13.loadPkcs8Base64(sKeyPkcs8Base64, sKeyPkcs8Base64Len, wrongpw.data(), wrongpw.size()),
PrivateKey::Error);
BOOST_CHECK_EQUAL(sKey13.getKeyType(), KeyType::NONE);
BOOST_CHECK_EQUAL(sKey13.getKeySize(), 0);
// save key in base64-encoded pkcs8 format
OBufferStream os14;
BOOST_REQUIRE_NO_THROW(sKey.savePkcs8Base64(os14, password.data(), password.size()));
checkPkcs8Base64Encoding(os14.buf(), password, sKeyPkcs1Buf);
OBufferStream os15;
BOOST_REQUIRE_NO_THROW(sKey.savePkcs8Base64(os15, pwCallback));
checkPkcs8Base64Encoding(os15.buf(), password, sKeyPkcs1Buf);
// save key in pkcs8 format
OBufferStream os16;
BOOST_REQUIRE_NO_THROW(sKey.savePkcs8(os16, password.data(), password.size()));
checkPkcs8Encoding(os16.buf(), password, sKeyPkcs1Buf);
OBufferStream os17;
BOOST_REQUIRE_NO_THROW(sKey.savePkcs8(os17, pwCallback));
checkPkcs8Encoding(os17.buf(), password, sKeyPkcs1Buf);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(DerivePublicKey, T, KeyTestDataSets)
{
T dataSet;
auto sKeyPkcs1Base64 = reinterpret_cast<const uint8_t*>(dataSet.privateKeyPkcs1.data());
auto sKeyPkcs1Base64Len = dataSet.privateKeyPkcs1.size();
PrivateKey sKey;
sKey.loadPkcs1Base64(sKeyPkcs1Base64, sKeyPkcs1Base64Len);
// derive public key and compare
ConstBufferPtr pKeyBits = sKey.derivePublicKey();
OBufferStream os;
bufferSource(dataSet.publicKey) >> base64Decode() >> streamSink(os);
BOOST_CHECK_EQUAL_COLLECTIONS(pKeyBits->begin(), pKeyBits->end(),
os.buf()->begin(), os.buf()->end());
}
BOOST_AUTO_TEST_CASE(RsaDecryption)
{
RsaKey_Aes256Encrypted dataSet;
PrivateKey sKey;
sKey.loadPkcs1Base64(reinterpret_cast<const uint8_t*>(dataSet.privateKeyPkcs1.data()),
dataSet.privateKeyPkcs1.size());
BOOST_CHECK_EQUAL(sKey.getKeyType(), KeyType::RSA);
const uint8_t plaintext[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
// Ciphertext generated with OpenSSL 3.0.0
// printf ... | openssl pkeyutl -encrypt -inkey pub.pem -pubin -pkeyopt rsa_padding_mode:oaep | base64
const std::string ciphertext =
R"BASE64(BgVqf6yKhMytCeL6+/oEoyx9rahh2+a1iU0D17RgfX6Q/3eNEcC2xY5QomjI7k/no8yiTZbXT9R4
REE6ic0DjFSbFwJjC/P0/oTSQyUNn4xNO+aK0MGnyeN34A8c3bZfLuo2DU496SQF0B9I5SS3gEA9
rqdIAdbWoOCKi1EX5SXtAOPTsj5PHHH+UM52bxOrUPvGSl9tRaz5S6hVf2haSoio4nnG3/bA6pdb
hHjyHHA/oi1PlFRIe0EO2/riAdqdIW3eOqZGP5t5QAMmiP178A9YQdbSavTgBSuE20T01U82Ln+L
pNk+PE/mmM20iNBo8C9cAJVUju6T4DCNZk7H5Q==
)BASE64";
OBufferStream os;
bufferSource(ciphertext) >> base64Decode() >> streamSink(os);
auto decrypted = sKey.decrypt(os.buf()->data(), os.buf()->size());
BOOST_CHECK_EQUAL_COLLECTIONS(plaintext, plaintext + sizeof(plaintext),
decrypted->begin(), decrypted->end());
}
BOOST_AUTO_TEST_CASE(RsaEncryptDecrypt)
{
RsaKey_Aes256Encrypted dataSet;
PublicKey pKey;
pKey.loadPkcs8Base64(reinterpret_cast<const uint8_t*>(dataSet.publicKey.data()),
dataSet.publicKey.size());
BOOST_CHECK_EQUAL(pKey.getKeyType(), KeyType::RSA);
PrivateKey sKey;
sKey.loadPkcs1Base64(reinterpret_cast<const uint8_t*>(dataSet.privateKeyPkcs1.data()),
dataSet.privateKeyPkcs1.size());
BOOST_CHECK_EQUAL(sKey.getKeyType(), KeyType::RSA);
const uint8_t plaintext[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
auto ciphertext = pKey.encrypt(plaintext, sizeof(plaintext));
auto decrypted = sKey.decrypt(ciphertext->data(), ciphertext->size());
BOOST_CHECK_EQUAL_COLLECTIONS(plaintext, plaintext + sizeof(plaintext),
decrypted->begin(), decrypted->end());
}
BOOST_AUTO_TEST_CASE(UnsupportedDecryption)
{
OBufferStream os;
bufferSource("Y2lhbyFob2xhIWhlbGxvIQ==") >> base64Decode() >> streamSink(os);
auto ecKey = generatePrivateKey(EcKeyParams());
BOOST_CHECK_THROW(ecKey->decrypt(os.buf()->data(), os.buf()->size()), PrivateKey::Error);
auto hmacKey = generatePrivateKey(HmacKeyParams());
BOOST_CHECK_THROW(hmacKey->decrypt(os.buf()->data(), os.buf()->size()), PrivateKey::Error);
}
class RsaKeyGenParams
{
public:
using Params = RsaKeyParams;
using hasPublicKey = std::true_type;
using canSavePkcs1 = std::true_type;
static void
checkPublicKey(const Buffer&)
{
}
};
class EcKeyGenParams
{
public:
using Params = EcKeyParams;
using hasPublicKey = std::true_type;
using canSavePkcs1 = std::true_type;
static void
checkPublicKey(const Buffer& bits)
{
// EC key generation should use named curve format. See https://redmine.named-data.net/issues/5037
// OBJECT IDENTIFIER 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve)
const uint8_t oid[] = {0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07};
BOOST_CHECK_MESSAGE(std::search(bits.begin(), bits.end(), oid, oid + sizeof(oid)) != bits.end(),
"OID not found in " << toHex(bits));
}
};
class HmacKeyGenParams
{
public:
using Params = HmacKeyParams;
using hasPublicKey = std::false_type;
using canSavePkcs1 = std::false_type;
static void
checkPublicKey(const Buffer&)
{
}
};
using KeyGenParams = boost::mpl::vector<
#if OPENSSL_VERSION_NUMBER < 0x30000000L // FIXME #5154
HmacKeyGenParams,
#endif
RsaKeyGenParams,
EcKeyGenParams
>;
BOOST_AUTO_TEST_CASE_TEMPLATE(GenerateKey, T, KeyGenParams)
{
typename T::Params params;
auto sKey = generatePrivateKey(params);
BOOST_CHECK_EQUAL(sKey->getKeyType(), params.getKeyType());
BOOST_CHECK_EQUAL(sKey->getKeySize(), params.getKeySize());
const uint8_t data[] = {0x01, 0x02, 0x03, 0x04};
OBufferStream os;
BOOST_REQUIRE_NO_THROW(bufferSource(data, sizeof(data)) >>
signerFilter(DigestAlgorithm::SHA256, *sKey) >>
streamSink(os));
auto sig = os.buf();
bool result = false;
if (typename T::hasPublicKey()) {
auto pKeyBits = sKey->derivePublicKey();
BOOST_REQUIRE(pKeyBits != nullptr);
T::checkPublicKey(*pKeyBits);
PublicKey pKey;
pKey.loadPkcs8(pKeyBits->data(), pKeyBits->size());
BOOST_CHECK_NO_THROW(bufferSource(data, sizeof(data)) >>
verifierFilter(DigestAlgorithm::SHA256, pKey, sig->data(), sig->size()) >>
boolSink(result));
}
else {
#if OPENSSL_VERSION_NUMBER >= 0x1010100fL
BOOST_CHECK_THROW(sKey->derivePublicKey(), PrivateKey::Error);
#endif
BOOST_CHECK_NO_THROW(bufferSource(data, sizeof(data)) >>
verifierFilter(DigestAlgorithm::SHA256, *sKey, sig->data(), sig->size()) >>
boolSink(result));
}
BOOST_CHECK(result);
if (typename T::canSavePkcs1()) {
auto sKey2 = generatePrivateKey(params);
OBufferStream os1;
sKey->savePkcs1(os1);
OBufferStream os2;
sKey2->savePkcs1(os2);
BOOST_CHECK(*os1.buf() != *os2.buf());
}
else {
#if OPENSSL_VERSION_NUMBER >= 0x1010100fL
OBufferStream os1;
BOOST_CHECK_THROW(sKey->savePkcs1(os1), PrivateKey::Error);
#endif
}
}
BOOST_AUTO_TEST_CASE(GenerateKeyUnsupportedType)
{
BOOST_CHECK_THROW(generatePrivateKey(AesKeyParams()), std::invalid_argument);
}
BOOST_AUTO_TEST_SUITE_END() // TestPrivateKey
BOOST_AUTO_TEST_SUITE_END() // Transform
BOOST_AUTO_TEST_SUITE_END() // Security
} // namespace tests
} // namespace transform
} // namespace security
} // namespace ndn
| 42.22101 | 112 | 0.804317 | named-data |
04318d6c38883d021c4a33f68ab64ef65ea4cd44 | 30,092 | cpp | C++ | dist/dep/SuperStash/SuperStash/PapyrusSuperStash.cpp | Verteiron/SuperStash | 4592e5f2fe06e02a0b2abc3e289a9f323c12969f | [
"Unlicense"
] | 7 | 2016-02-03T04:50:53.000Z | 2021-06-03T19:36:06.000Z | dist/dep/SuperStash/SuperStash/PapyrusSuperStash.cpp | Verteiron/SuperStash | 4592e5f2fe06e02a0b2abc3e289a9f323c12969f | [
"Unlicense"
] | 8 | 2016-01-22T16:48:15.000Z | 2017-02-27T21:53:29.000Z | dist/dep/SuperStash/SuperStash/PapyrusSuperStash.cpp | Verteiron/SuperStash | 4592e5f2fe06e02a0b2abc3e289a9f323c12969f | [
"Unlicense"
] | 3 | 2018-02-06T04:04:48.000Z | 2021-06-03T19:36:07.000Z | #include <direct.h>
#include <functional>
#include <random>
#include <algorithm>
#include "skse/GameData.h"
#include "skse/GameRTTI.h"
#include "skse/PapyrusWornObject.h"
#include "skse/PapyrusSpell.h"
#include "json/json.h"
#include "fileutils.h"
#include "itemutils.h"
#include "jcutils.h"
#include "PapyrusSuperStash.h"
typedef std::vector<TESForm*> FormVec;
bool LoadJsonFromFile(const char * filePath, Json::Value &jsonData)
{
IFileStream currentFile;
if (!currentFile.Open(filePath))
{
_ERROR("%s: couldn't open file (%s) Error (%d)", __FUNCTION__, filePath, GetLastError());
return true;
}
char buf[512];
std::string jsonString;
while (!currentFile.HitEOF()){
currentFile.ReadString(buf, sizeof(buf) / sizeof(buf[0]));
jsonString.append(buf);
}
currentFile.Close();
Json::Features features;
features.all();
Json::Reader reader(features);
bool parseSuccess = reader.parse(jsonString, jsonData);
if (!parseSuccess) {
_ERROR("%s: Error occured parsing json for %s.", __FUNCTION__, filePath);
return true;
}
return false;
}
bool WriteItemData(TESForm* form, Json::Value jItemData)
{
Json::StyledWriter writer;
std::string jsonString = writer.write(jItemData);
if (!jsonString.length()) {
return true;
}
if (!jItemData["displayName"].isString()) {
return true;
}
char filePath[MAX_PATH];
sprintf_s(filePath, "%s/Items/%08x_%s.json", GetSSDirectory().c_str(), form->formID, jItemData["displayName"].asCString());
IFileStream currentFile;
IFileStream::MakeAllDirs(filePath);
if (!currentFile.Create(filePath))
{
_ERROR("%s: couldn't create preset file (%s) Error (%d)", __FUNCTION__, filePath, GetLastError());
return true;
}
currentFile.WriteBuf(jsonString.c_str(), jsonString.length());
currentFile.Close();
return false;
}
Json::Value GetMagicItemJSON(MagicItem * pMagicItem)
{
Json::Value jMagicItem;
if (!pMagicItem)
return jMagicItem;
jMagicItem["form"] = GetJCFormString(pMagicItem);
Json::Value jMagicEffects;
for (int i = 0; i < magicItemUtils::GetNumEffects(pMagicItem); i++) {
MagicItem::EffectItem * effectItem;
pMagicItem->effectItemList.GetNthItem(i, effectItem);
if (effectItem) {
Json::Value effectItemData;
effectItemData["form"] = GetJCFormString(effectItem->mgef);
//effectItemData["formID"] = (Json::UInt)effectItem->mgef->formID;
effectItemData["name"] = effectItem->mgef->fullName.name.data;
if (effectItem->area)
effectItemData["area"] = (Json::UInt)effectItem->area;
if (effectItem->magnitude)
effectItemData["magnitude"] = effectItem->magnitude;
if (effectItem->duration)
effectItemData["duration"] = (Json::UInt)effectItem->duration;
jMagicEffects.append(effectItemData);
}
}
if (!jMagicEffects.empty())
jMagicItem["magicEffects"] = jMagicEffects;
return jMagicItem;
}
void CreateEnchantmentFromJson(TESForm* form, BaseExtraList* bel, float maxCharge, Json::Value jEnchantment)
{
if (!form || !bel || !maxCharge || jEnchantment.empty())
return;
std::vector<EffectSetting*> effects;
std::vector<UInt32> durations;
std::vector<float> magnitudes;
std::vector<UInt32> areas;
int effectNum = 0;
for (auto & jMagicEffect : jEnchantment["magicEffects"]) {
EffectSetting* effect = DYNAMIC_CAST(GetJCStringForm(jMagicEffect["form"].asString()), TESForm, EffectSetting);
effects.push_back(effect);
durations.push_back((UInt32)jMagicEffect["duration"].asInt());
areas.push_back((UInt32)jMagicEffect["area"].asInt());
magnitudes.push_back((float)jMagicEffect["magnitude"].asFloat());
effectNum++;
}
CreateEnchantmentFromVectors(form, bel, maxCharge, effects, magnitudes, areas, durations);
}
void AddNIODyeData(TESForm* form, BaseExtraList* bel, Json::Value &jBaseExtraList)
{
if (g_itemDataInterface && (bel->HasType(kExtraData_Rank) || bel->HasType(kExtraData_UniqueID))) {
Json::Value jDyeColors;
ExtraRank* xRank = static_cast<ExtraRank*>(bel->GetByType(kExtraData_Rank));
ExtraUniqueID* xUID = static_cast<ExtraUniqueID*>(bel->GetByType(kExtraData_UniqueID));
SInt32 rankID = 0;
UInt16 uniqueID = 0;
if (xRank)
rankID = xRank->rank;
if (xUID)
uniqueID = xUID->uniqueId;
_DMESSAGE("RankID is %d, UniqueID is %d", rankID, uniqueID);
TESForm* uniqueForm = g_itemDataInterface->GetFormFromUniqueID(uniqueID);
//TESForm* ownerForm = g_itemDataInterface->GetOwnerOfUniqueID(uniqueID);
if (!uniqueForm) {
int i = 0;
while (uniqueForm != form && i < 0x32) {
uniqueForm = g_itemDataInterface->GetFormFromUniqueID(i);
i++;
}
if (uniqueForm == form)
uniqueID = i;
}
UInt32 iInvalidDyeEntry = g_itemDataInterface->GetItemDyeColor(uniqueID, 16); //Mask 16 is never used, so pull its value to get the "undyed" value (which changes every time)
std::vector<UInt32> dyes;
_DMESSAGE("dyes size is %d", dyes.size());
bool hasDye = false;
for (int i = 15; i >= 0; i--) {
UInt32 dyeColor = g_itemDataInterface->GetItemDyeColor(uniqueID, i);
if (dyeColor == iInvalidDyeEntry)
dyeColor = 0;
if (dyeColor)
hasDye = true;
if (hasDye)
dyes.insert(dyes.begin(), dyeColor);
if (dyeColor && (dyeColor != iInvalidDyeEntry))
_DMESSAGE("DyeColor for mask %d is 0x%08X (R:%02X G:%02X B:%02X A:%02X)", i, dyeColor, (dyeColor & 0xFF0000) >> 16, (dyeColor & 0xFF00) >> 8, dyeColor & 0xFF, dyeColor >> 24);
}
if (hasDye) {
for (int i = 0; i < dyes.size(); i++) {
jDyeColors.append(Json::UInt(dyes[i]));
}
if (!jDyeColors.empty())
jBaseExtraList["NIODyeColors"] = jDyeColors;
}
}
}
Json::Value GetExtraDataJSON(TESForm* form, BaseExtraList* bel)
{
Json::Value jBaseExtraList;
if (!form || !bel)
return jBaseExtraList;
const char * sFormName = NULL;
TESFullName* pFullName = DYNAMIC_CAST(form, TESForm, TESFullName);
if (pFullName)
sFormName = pFullName->name.data;
const char * sDisplayName = bel->GetDisplayName(form);
if (sDisplayName && (sDisplayName != sFormName)) {
jBaseExtraList["displayName"] = sDisplayName;
UInt32 itemID = ssCalcItemId(form, bel); //ItemID as used by WornObject and SkyUI, might be useful
if (itemID)
jBaseExtraList["itemID"] = (Json::Int)itemID;
}
if (form->formType == TESObjectWEAP::kTypeID || form->formType == TESObjectARMO::kTypeID) {
float itemHealth = referenceUtils::GetItemHealthPercent(form, bel);
if (itemHealth > 1.0)
jBaseExtraList["health"] = itemHealth;
if (form->formType == TESObjectWEAP::kTypeID) {
float itemMaxCharge = referenceUtils::GetItemMaxCharge(form, bel);
if (itemMaxCharge) {
jBaseExtraList["itemMaxCharge"] = itemMaxCharge;
jBaseExtraList["itemCharge"] = referenceUtils::GetItemCharge(form, bel);
}
}
//Support for NIOverride dyes
AddNIODyeData(form, bel, jBaseExtraList);
}
if (bel->HasType(kExtraData_Soul)) {
ExtraSoul * xSoul = static_cast<ExtraSoul*>(bel->GetByType(kExtraData_Soul));
if (xSoul) {
//count returns UInt32 but value is UInt8, so strip the garbage
UInt8 soulCount = xSoul->count & 0xFF;
if (soulCount)
jBaseExtraList["soulSize"] = (Json::UInt)(soulCount);
}
}
EnchantmentItem * enchantment = referenceUtils::GetEnchantment(bel);
if (enchantment) {
Json::Value enchantmentData;
enchantmentData = GetMagicItemJSON(enchantment);
if (!enchantmentData.empty())
jBaseExtraList["enchantment"] = enchantmentData;
}
if (!jBaseExtraList.empty()) { //We don't want Count to be the only item in ExtraData
ExtraCount* xCount = static_cast<ExtraCount*>(bel->GetByType(kExtraData_Count));
if (xCount)
jBaseExtraList["count"] = (Json::UInt)(xCount->count & 0xFFFF); //count returns UInt32 but value is UInt16, so strip the garbage
}
if (form->formType == TESObjectWEAP::kTypeID || form->formType == TESObjectARMO::kTypeID) {
Json::Value fileData = jBaseExtraList;
fileData["form"] = GetJCFormString(form);
WriteItemData(form, fileData);
}
return jBaseExtraList;
}
bool IsWorthLoading(Json::Value jBaseExtraData)
{
if (jBaseExtraData.empty())
return false;
return (jBaseExtraData["displayName"].isString()
|| jBaseExtraData["enchantment"].isObject()
|| jBaseExtraData["itemCharge"].isNumeric()
|| jBaseExtraData["soulSize"].isNumeric()
|| jBaseExtraData["rank"].isNumeric()
|| jBaseExtraData["uniqueID"].isNumeric());
}
bool IsWorthSaving(BaseExtraList * bel)
{
if (!bel)
{
return false;
}
for (UInt32 i = 1; i < 0xB3; i++) {
if (bel->HasType(i))
_DMESSAGE("BaseExtraList has type: %0x", i);
}
return (bel->HasType(kExtraData_Health)
|| bel->HasType(kExtraData_Enchantment)
|| bel->HasType(kExtraData_Charge)
|| bel->HasType(kExtraData_Soul)
|| bel->HasType(kExtraData_Rank)
|| bel->HasType(kExtraData_UniqueID));
}
//Removes (Fine), (Flawless), (Legendary) etc. Will also remove (foo).
std::string StripWeaponHealth(std::string displayName)
{
std::string result;
std::istringstream str(displayName);
std::vector<std::string> stringData;
std::string token;
while (std::getline(str, token, '(')) {
stringData.push_back(token);
}
result = stringData[0];
// trim trailing spaces
size_t endpos = result.find_last_not_of(" ");
if (std::string::npos != endpos)
{
result = result.substr(0, endpos + 1);
}
return result;
}
//Modified from PapyrusObjectReference.cpp!ExtraContainerFiller
class ExtraListJsonFiller
{
TESForm * m_form;
Json::Value m_json;
public:
ExtraListJsonFiller(TESForm* form) : m_form(form), m_json() { }
bool Accept(BaseExtraList* bel)
{
if (IsWorthSaving(bel)) {
m_json.append(GetExtraDataJSON(m_form, bel));
}
return true;
}
Json::Value GetJSON()
{
return m_json;
}
};
Json::Value _GetItemJSON(TESForm * form, InventoryEntryData * entryData = NULL, BaseExtraList* bel = NULL)
{
Json::Value formData;
if (!form)
return formData;
//Leveled items completely screw things up
if (DYNAMIC_CAST(form, TESForm, TESLevItem))
return formData;
formData["form"] = GetJCFormString(form);
//formData["formID"] = (Json::UInt)form->formID;
const char * formName = NULL;
TESFullName* pFullName = DYNAMIC_CAST(form, TESForm, TESFullName);
if (pFullName)
formName = pFullName->name.data;
formData["name"] = formName ? formName : "";
_DMESSAGE("Processing %s - %08x ==---", formName, form->formID);
//Get potion data for player-made potions
if (form->formType == AlchemyItem::kTypeID && IsPlayerPotion(form)) {
AlchemyItem * pAlchemyItem = DYNAMIC_CAST(form, TESForm, AlchemyItem);
Json::Value potionData = GetMagicItemJSON(pAlchemyItem);
if (!potionData.empty()) {
potionData["isPoison"] = pAlchemyItem->IsPoison();
formData["potionData"] = potionData;
}
}
//If there is a BaseExtraList, get more info
Json::Value formExtraData;
if (bel)
formExtraData = GetExtraDataJSON(form, bel);
if (!formExtraData.empty())
formData["extraData"] = formExtraData;
return formData;
}
Json::Value GetItemJSON(TESForm * form)
{
return _GetItemJSON(form, NULL, NULL);
}
Json::Value GetItemJSON(TESForm * form, InventoryEntryData * entryData)
{
return _GetItemJSON(form, entryData, NULL);
}
Json::Value GetItemJSON(TESForm * form, InventoryEntryData * entryData, BaseExtraList * bel)
{
return _GetItemJSON(form, entryData, bel);
}
Json::Value GetItemJSON(TESForm * form, BaseExtraList * bel)
{
return _GetItemJSON(form, NULL, bel);
}
//Modified from PapyrusObjectReference.cpp!ExtraContainerInfo
class ContainerJson
{
FormVec m_vec;
Json::Value m_json;
TESObjectREFR* m_ref;
TESContainer* m_base;
public:
ContainerJson(TESObjectREFR * pContainerRef) : m_vec(), m_ref(pContainerRef), m_base()
{
TESForm* pBaseForm = pContainerRef->baseForm;
if (pBaseForm)
m_base = DYNAMIC_CAST(pBaseForm, TESForm, TESContainer);
ExtraContainerChanges* pXContainerChanges = static_cast<ExtraContainerChanges*>(pContainerRef->extraData.GetByType(kExtraData_ContainerChanges));
if (!pXContainerChanges)
return;
EntryDataList * entryList = pXContainerChanges ? pXContainerChanges->data->objList : NULL;
m_json.clear();
Json::Value jContainerEntries;
m_json["containerEntries"] = jContainerEntries;
m_vec.reserve(128);
if (entryList) {
Json::Value jEntryDataList;
m_json["entryDataList"] = jEntryDataList;
entryList->Visit(*this);
}
std::sort(m_vec.begin(), m_vec.end());
}
bool Accept(InventoryEntryData* data)
{
if (data) {
AppendJsonFromInventoryEntry(data);
}
return true;
}
void AppendJsonFromContainerEntry(TESContainer::Entry * pEntry)
{
Json::Value jContainerEntry;
TESForm * thisForm = pEntry->form;
if (thisForm) {
jContainerEntry = GetItemJSON(thisForm);
if (!jContainerEntry.empty()) {
jContainerEntry["count"] = (Json::UInt)pEntry->count;
//jContainerEntry["writtenBy"] = "0";
m_json["containerEntries"].append(jContainerEntry);
}
}
}
void AppendJsonFromInventoryEntry(InventoryEntryData * entryData)
{
TESForm * thisForm = entryData->type;
if (!thisForm)
return;
m_vec.push_back(thisForm);
Json::Value jInventoryEntryData;
UInt32 countBase = m_base->CountItem(thisForm);
UInt32 countChanges = entryData->countDelta;
UInt32 countTotal = countBase + countChanges;
if (countTotal > 0) {
jInventoryEntryData = GetItemJSON(thisForm, entryData);
jInventoryEntryData["count"] = (Json::UInt)(countTotal);
//jInventoryEntryData["writtenBy"] = "1";
}
ExtendDataList* edl = entryData->extendDataList;
if (edl) {
Json::Value jExtendDataList;
ExtraListJsonFiller extraJsonFiller(thisForm);
edl->Visit(extraJsonFiller);
jExtendDataList = extraJsonFiller.GetJSON();
if (!jExtendDataList.empty()) {
jInventoryEntryData["extendDataList"] = jExtendDataList;
}
}
if (!jInventoryEntryData.empty())
m_json["entryDataList"].append(jInventoryEntryData);
}
bool IsValidEntry(TESContainer::Entry* pEntry)
{
if (pEntry) {
TESForm* pForm = pEntry->form;
if (DYNAMIC_CAST(pForm, TESForm, TESLevItem))
return false;
if (!std::binary_search(m_vec.begin(), m_vec.end(), pForm)) {
return true;
}
}
return false;
}
std::string GetJsonString() {
Json::StyledWriter writer;
std::string jsonString = writer.write(m_json);
return jsonString;
}
bool WriteTofile(std::string relativePath) {
std::string jsonString = GetJsonString();
if (!jsonString.length()) {
return true;
}
char filePath[MAX_PATH];
sprintf_s(filePath, "%s/%s", GetSSDirectory().c_str(), relativePath.c_str());
IFileStream currentFile;
IFileStream::MakeAllDirs(filePath);
if (!currentFile.Create(filePath))
{
_ERROR("%s: couldn't create preset file (%s) Error (%d)", __FUNCTION__, filePath, GetLastError());
return true;
}
currentFile.WriteBuf(jsonString.c_str(), jsonString.length());
currentFile.Close();
return false;
}
};
//Modified from PapyrusObjectReference.cpp!ExtraContainerFiller
class ContainerJsonFiller
{
ContainerJson& m_containerjson;
public:
// ContainerJson(TESObjectREFR * pContainerRef) : m_map(), m_vec(), m_ref(pContainerRef), m_base()
ContainerJsonFiller(ContainerJson& c_containerjson) : m_containerjson(c_containerjson) { }
bool Accept(TESContainer::Entry* pEntry)
{
SInt32 numItems = 0;
if (m_containerjson.IsValidEntry(pEntry)) {
m_containerjson.AppendJsonFromContainerEntry(pEntry);
}
return true;
}
};
class EntryFormFinder
{
TESForm* m_form;
public:
EntryFormFinder(TESForm* a_form) : m_form(a_form) {}
bool Accept(InventoryEntryData* pEntry)
{
if (pEntry->type == m_form) {
return true;
}
return false;
}
};
BaseExtraList * CreateBaseExtraListFromJson(TESForm* thisForm, Json::Value jBaseExtraData)
{
if (!thisForm || jBaseExtraData.empty())
return nullptr;
//The following seems to successfully create a new, working BEL without crashing anything.
//Not 100% sure about the initialization, but so far it doesn't seem to crash...
BaseExtraList * newBEL = (BaseExtraList *)FormHeap_Allocate(sizeof(BaseExtraList));
ASSERT(newBEL);
newBEL->m_data = nullptr;
//Is this right? Seems to work as is...
newBEL->m_presence = (BaseExtraList::PresenceBitfield*)FormHeap_Allocate(sizeof(BaseExtraList::PresenceBitfield));
ASSERT(newBEL->m_presence);
//Fill m_presence with 0s, otherwise the bad flags cause Skyrim to crash.
std::fill(newBEL->m_presence->bits, newBEL->m_presence->bits + 0x18, 0);
if (jBaseExtraData["displayName"].isString()) {
std::string displayName(jBaseExtraData["displayName"].asString());
displayName = StripWeaponHealth(displayName);
if (displayName.length())
referenceUtils::SetDisplayName(newBEL, displayName.c_str(), false);
}
if (jBaseExtraData["enchantment"].isObject()) {
//Armors don't have maxcharge, so provide a default.
float itemMaxCharge = 0xffff;
if (jBaseExtraData["itemMaxCharge"].isNumeric())
itemMaxCharge = jBaseExtraData["itemMaxCharge"].asFloat();
CreateEnchantmentFromJson(thisForm, newBEL, itemMaxCharge, jBaseExtraData["enchantment"]);
}
if (jBaseExtraData["itemCharge"].isNumeric())
referenceUtils::SetItemCharge(thisForm, newBEL, jBaseExtraData["itemCharge"].asFloat());
if (jBaseExtraData["health"].isNumeric())
referenceUtils::SetItemHealthPercent(thisForm, newBEL, jBaseExtraData["health"].asFloat());
if (jBaseExtraData["soulSize"].isInt()) {
UInt8 soulLevel = jBaseExtraData["soulSize"].asInt();
ExtraSoul * extraSoul = static_cast<ExtraSoul*>(newBEL->GetByType(kExtraData_Soul));
if (extraSoul) {
extraSoul->count = soulLevel;
}
else {
extraSoul = ExtraSoul::Create();
extraSoul->count = (UInt8)soulLevel;
newBEL->Add(kExtraData_Soul, extraSoul);
}
}
if (jBaseExtraData["count"].isInt()) {
UInt32 thisCount = jBaseExtraData["count"].asInt();
ExtraCount * extraCount = static_cast<ExtraCount*>(newBEL->GetByType(kExtraData_Count));
if (extraCount) {
extraCount->count = thisCount;
}
else {
extraCount = ExtraCount::Create();
extraCount->count = (UInt8)thisCount;
newBEL->Add(kExtraData_Count, extraCount);
}
}
return newBEL;
}
//This should only be called on empty containers, at least for now.
SInt32 FillContainerFromJson(TESObjectREFR* pContainerRef, Json::Value jContainerData)
{
SInt32 result = 0;
Json::Value jEntryDataList = jContainerData["entryDataList"];
if (jEntryDataList.empty() || jEntryDataList.type() != Json::arrayValue)
return result;
TESContainer* pContainer = NULL;
TESForm* pBaseForm = pContainerRef->baseForm;
if (pBaseForm)
pContainer = DYNAMIC_CAST(pBaseForm, TESForm, TESContainer);
if (!pContainer)
return result;
_MESSAGE("%s - %08x - Getting EntryList...", __FUNCTION__, pContainerRef->formID);
ExtraContainerChanges* pXContainerChanges = static_cast<ExtraContainerChanges*>(pContainerRef->extraData.GetByType(kExtraData_ContainerChanges));
if (!pXContainerChanges) {
return result;
}
EntryDataList * entryList = pXContainerChanges ? pXContainerChanges->data->objList : NULL;
_MESSAGE("%s - %08x - Starting EntryList count is %d", __FUNCTION__, pContainerRef->formID, entryList->Count());
for (auto & jEntryData : jEntryDataList) {
_MESSAGE("%s - %08x - Retrieving form %s", __FUNCTION__, pContainerRef->formID, jEntryData["form"].asCString());
TESForm * thisForm = GetJCStringForm(jEntryData["form"].asString());
_MESSAGE("%s - %08x - BEGIN Processing Form %08x (%s)", __FUNCTION__, pContainerRef->formID, thisForm ? thisForm->formID : 0, jEntryData["name"].asCString());
const char * sFormName = NULL;
if (thisForm) {
TESFullName* pTFullName = DYNAMIC_CAST(thisForm, TESForm, TESFullName);
if (pTFullName)
sFormName = pTFullName->name.data;
_MESSAGE("%s - %08x - Form %08x - Name is %s", __FUNCTION__, pContainerRef->formID, thisForm->formID, sFormName ? sFormName : "<NONE>");
}
if (thisForm && (thisForm->formID >> 24 == 0xff)) {
_MESSAGE("%s - %08x - Form %08x - Temporary form, sanity checking...", __FUNCTION__, pContainerRef->formID, thisForm->formID);
//This is a temporary form and should be sanity-checked, since these are not synced between saves.
TESFullName* pFullName = DYNAMIC_CAST(thisForm, TESForm, TESFullName);
if (!pFullName) {
thisForm = nullptr;
}
else {
if (jEntryData["name"].isString()) {
if (pFullName->name.data != jEntryData["name"].asString().c_str())
thisForm = nullptr;
}
}
}
if (!thisForm) {
_MESSAGE("%s - %08x - Form FF?????? - Temporary missing or did not match, creating a new one!", __FUNCTION__, pContainerRef->formID);
Json::Value jPotionData = jEntryData["potionData"];
if (!jPotionData.empty()) {
_MESSAGE("%s - Form FF?????? - Form is a Potion!", __FUNCTION__, pContainerRef->formID);
std::vector<EffectSetting*> effects;
std::vector<UInt32> durations;
std::vector<float> magnitudes;
std::vector<UInt32> areas;
int effectNum = 0;
for (auto & jMagicEffect : jPotionData["magicEffects"]) {
EffectSetting* effect = DYNAMIC_CAST(GetJCStringForm(jMagicEffect["form"].asString()), TESForm, EffectSetting);
effects.push_back(effect);
durations.push_back((UInt32)jMagicEffect["duration"].asInt());
areas.push_back((UInt32)jMagicEffect["area"].asInt());
magnitudes.push_back((float)jMagicEffect["magnitude"].asFloat());
effectNum++;
}
AlchemyItem* thisPotion = _CreateCustomPotionFromVector(effects, magnitudes, areas, durations);
if (thisPotion)
thisForm = thisPotion;
if (thisForm)
_MESSAGE("%s - %08x - Created Form %08x!", __FUNCTION__, pContainerRef->formID,thisForm->formID);
}
}
UInt32 count = jEntryData["count"].asInt();
_MESSAGE("%s - %08x - Form %08x - Count is %d", __FUNCTION__, pContainerRef->formID, thisForm->formID, count);
if (thisForm && count) {
InventoryEntryData * thisEntry = pXContainerChanges->data->FindItemEntry(thisForm);
if (thisEntry) {
_MESSAGE("%s - %08x - Form %08x - Existing count is %d, adjusting by %d", __FUNCTION__, pContainerRef->formID, thisForm->formID, pContainer->CountItem(thisForm), count - pContainer->CountItem(thisForm));
thisEntry->countDelta = count - pContainer->CountItem(thisForm);
}
else {
_MESSAGE("%s - %08x - Form %08x - No inventory entry for this form, creating a new one...", __FUNCTION__, pContainerRef->formID, thisForm->formID);
thisEntry = InventoryEntryData::Create(thisForm, count);
entryList->Push(thisEntry);
_MESSAGE("%s - %08x - Form %08x - Entry count is now %d", __FUNCTION__, pContainerRef->formID, thisForm->formID,entryList->Count());
}
Json::Value jExtendDataList = jEntryData["extendDataList"];
if (!jExtendDataList.empty() && jExtendDataList.type() == Json::arrayValue) {
_MESSAGE("%s - %08x - Form %08x - Processing extendDataList...", __FUNCTION__, pContainerRef->formID, thisForm->formID);
ExtendDataList * edl = thisEntry->extendDataList;
if (!edl) {
edl = ExtendDataList::Create();
thisEntry->extendDataList = edl;
_MESSAGE("%s - %08x - Form %08x - Created new EDL!", __FUNCTION__, pContainerRef->formID, thisForm->formID);
}
else {
_MESSAGE("%s - %08x - Form %08x - EDL already exists with %d entries.", __FUNCTION__, pContainerRef->formID, thisForm->formID, edl->Count());
}
//If anything in this plugin causes leaks or other Bad Things, it's probably this next bit.
for (auto & jBaseExtraData : jExtendDataList) {
if (IsWorthLoading(jBaseExtraData)) {
_MESSAGE("%s - %08x - Form %08x - Creating new BEL...", __FUNCTION__, pContainerRef->formID, thisForm->formID);
BaseExtraList * newBEL = CreateBaseExtraListFromJson(thisForm, jBaseExtraData);
if (newBEL->m_data)
edl->Push(newBEL);
_MESSAGE("%s - %08x - Form %08x - EDL count is now %d", __FUNCTION__, pContainerRef->formID, thisForm->formID,edl->Count());
}
}
}
_MESSAGE("%s - %08x - FINISH Processing Form %08x (%s)", __FUNCTION__, pContainerRef->formID, thisForm->formID, sFormName);
_MESSAGE("--------------");
}
//entryList->Dump();
}
_MESSAGE("%s - %08x - Ending EntryList count is %d", __FUNCTION__, pContainerRef->formID, entryList->Count());
return entryList->Count();
}
namespace papyrusSuperStash
{
void TraceConsole(StaticFunctionTag*, BSFixedString theString)
{
Console_Print(theString.data);
}
BSFixedString userDirectory(StaticFunctionTag*) {
return GetSSDirectory().c_str();
}
SInt32 RotateFile(StaticFunctionTag*, BSFixedString filename, SInt32 maxCount)
{
SInt32 ret = 0;
return ssRotateFile(filename.data, maxCount);
}
void DeleteStashFile(StaticFunctionTag*, BSFixedString filename, bool deleteBackups = false)
{
char filePath[MAX_PATH];
sprintf_s(filePath, "%s/Stashes/%s.json", GetSSDirectory().c_str(), filename.data);
if (!isReadable(filePath))
{
_MESSAGE("%s - File not found: %s", __FUNCTION__, filePath);
return;
}
if (!isInSSDir(filePath))
{
_MESSAGE("%s - user tried to delete a file outside the SS dir... naughty! File was %s", __FUNCTION__, filename.data);
return;
}
_MESSAGE("%s - Deleting file %s", __FUNCTION__, filePath);
SSDeleteFile(filePath);
if (deleteBackups)
{
for (int i = 0; i < 10; i++)
{
sprintf_s(filePath, "%s/Stashes/%s.%d.json", GetSSDirectory().c_str(), filename.data, i);
SSDeleteFile(filePath);
}
}
}
BSFixedString UUID(StaticFunctionTag*)
{
int bytes[16];
std::string s;
std::random_device rd;
std::mt19937 generator;
std::uniform_int_distribution<int> distByte(0, 255);
generator.seed(rd());
for (int i = 0; i < 16; i++) {
bytes[i] = distByte(generator);
}
bytes[6] &= 0x0f;
bytes[6] |= 0x40;
bytes[8] &= 0x3f;
bytes[8] |= 0x80;
char thisOctet[4];
for (int i = 0; i < 16; i++) {
sprintf_s(thisOctet, "%02x", bytes[i]);
s += thisOctet;
}
s.insert(20, "-");
s.insert(16, "-");
s.insert(12, "-");
s.insert(8, "-");
return s.c_str();
}
BSFixedString GetSourceMod(StaticFunctionTag*, TESForm* form)
{
if (!form)
{
return NULL;
}
UInt8 modIndex = form->formID >> 24;
if (modIndex > 255)
{
return NULL;
}
DataHandler* pDataHandler = DataHandler::GetSingleton();
ModInfo* modInfo = pDataHandler->modList.modInfoList.GetNthItem(modIndex);
return (modInfo) ? modInfo->name : NULL;
}
BSFixedString GetObjectJSON(StaticFunctionTag*, TESObjectREFR* pObject)
{
TESForm * form = pObject->baseForm;
BaseExtraList * bel = &pObject->extraData;
if (!(form && bel))
return NULL;
Json::StyledWriter writer;
Json::Value formData = GetItemJSON(form, bel);
std::string jsonData = writer.write(formData);
return jsonData.c_str();
}
BSFixedString GetContainerJSON(StaticFunctionTag*, TESObjectREFR* pContainerRef)
{
const char * result = NULL;
if (!pContainerRef) {
return result;
}
TESContainer* pContainer = NULL;
TESForm* pBaseForm = pContainerRef->baseForm;
if (pBaseForm)
pContainer = DYNAMIC_CAST(pBaseForm, TESForm, TESContainer);
ContainerJson containerJsonData = ContainerJson(pContainerRef);
//containerJsonData processes all the InventoryEntryData but still needs the ContainerEntries from the base object
ContainerJsonFiller containerJsonFiller = ContainerJsonFiller(containerJsonData);
pContainer->Visit(containerJsonFiller);
//containerJsonData.WriteTofile("/Stashes/superquick.json");
return containerJsonData.GetJsonString().c_str();
}
SInt32 FillContainerFromJSON(StaticFunctionTag*, TESObjectREFR* pContainerRef, BSFixedString filePath)
{
_MESSAGE("%s - %08x - Called with file %s", __FUNCTION__, pContainerRef->formID, filePath.data);
Json::Value jsonData;
LoadJsonFromFile(filePath.data, jsonData);
if (jsonData.empty())
return 0;
_MESSAGE("%s - %08x - File has valid data, filling container!", __FUNCTION__, pContainerRef->formID);
return FillContainerFromJson(pContainerRef, jsonData);
}
AlchemyItem* CreateCustomPotion(StaticFunctionTag*, VMArray<EffectSetting*> effects, VMArray<float> magnitudes, VMArray<UInt32> areas, VMArray<UInt32> durations, SInt32 forcePotionType)
{
return _CreateCustomPotion(effects, magnitudes, areas, durations, forcePotionType);
}
}
#include "skse/PapyrusVM.h"
#include "skse/PapyrusNativeFunctions.h"
void papyrusSuperStash::RegisterFuncs(VMClassRegistry* registry)
{
registry->RegisterFunction(
new NativeFunction1<StaticFunctionTag, void, BSFixedString>("TraceConsole", "SuperStash", papyrusSuperStash::TraceConsole, registry));
registry->RegisterFunction(
new NativeFunction0<StaticFunctionTag, BSFixedString>("userDirectory", "SuperStash", papyrusSuperStash::userDirectory, registry));
registry->RegisterFunction(
new NativeFunction2<StaticFunctionTag, SInt32, BSFixedString, SInt32>("RotateFile", "SuperStash", papyrusSuperStash::RotateFile, registry));
registry->RegisterFunction(
new NativeFunction2<StaticFunctionTag, void, BSFixedString, bool>("DeleteStashFile", "SuperStash", papyrusSuperStash::DeleteStashFile, registry));
registry->RegisterFunction(
new NativeFunction0<StaticFunctionTag, BSFixedString>("UUID", "SuperStash", papyrusSuperStash::UUID, registry));
registry->RegisterFunction(
new NativeFunction1<StaticFunctionTag, BSFixedString, TESForm*>("GetSourceMod", "SuperStash", papyrusSuperStash::GetSourceMod, registry));
registry->RegisterFunction(
new NativeFunction1<StaticFunctionTag, BSFixedString, TESObjectREFR*>("GetContainerJSON", "SuperStash", papyrusSuperStash::GetContainerJSON, registry));
registry->RegisterFunction(
new NativeFunction1<StaticFunctionTag, BSFixedString, TESObjectREFR*>("GetObjectJSON", "SuperStash", papyrusSuperStash::GetObjectJSON, registry));
registry->RegisterFunction(
new NativeFunction2<StaticFunctionTag, SInt32, TESObjectREFR*, BSFixedString>("FillContainerFromJSON", "SuperStash", papyrusSuperStash::FillContainerFromJSON, registry));
registry->RegisterFunction(
new NativeFunction5<StaticFunctionTag, AlchemyItem*, VMArray<EffectSetting*>, VMArray<float>, VMArray<UInt32>, VMArray<UInt32>, SInt32>("CreateCustomPotion", "SuperStash", papyrusSuperStash::CreateCustomPotion, registry));
}
| 31.910923 | 224 | 0.714675 | Verteiron |
0433461ac63415215708e9918cc6b534c007f6bc | 2,492 | hpp | C++ | sources/RenderSystem/OpenGLES/spOpenGLES2RenderSystem.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/RenderSystem/OpenGLES/spOpenGLES2RenderSystem.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/RenderSystem/OpenGLES/spOpenGLES2RenderSystem.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2020-02-15T09:17:41.000Z | 2020-05-21T14:10:40.000Z | /*
* OpenGL|ES 2 render system header
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#ifndef __SP_RENDERER_OPENGLES2_H__
#define __SP_RENDERER_OPENGLES2_H__
#include "Base/spStandard.hpp"
#if defined(SP_COMPILE_WITH_OPENGLES2)
#include "RenderSystem/OpenGL/spOpenGLPipelineProgrammable.hpp"
#include "RenderSystem/OpenGLES/spOpenGLES2Texture.hpp"
namespace sp
{
namespace video
{
//! OpenGL|ES 2 render system. This renderer supports OpenGL|ES 2.0.
class SP_EXPORT OpenGLES2RenderSystem : public GLProgrammableFunctionPipeline
{
public:
OpenGLES2RenderSystem();
~OpenGLES2RenderSystem();
/* === Render system information === */
io::stringc getVersion() const;
s32 getMultitexCount() const;
s32 getMaxLightCount() const;
bool queryVideoSupport(const EVideoFeatureSupport Query) const;
/* === Context functions === */
void setupConfiguration();
/* === Render states === */
void setRenderState(const video::ERenderStates Type, s32 State);
s32 getRenderState(const video::ERenderStates Type) const;
void disableTriangleListStates();
void disable3DRenderStates();
/* === Rendering functions === */
bool setupMaterialStates(const MaterialStates* Material, bool Forced = false);
/* === Hardware mesh buffers === */
//! \todo Not implemented yet
bool bindMeshBuffer(const MeshBuffer* Buffer);
//! \todo Not implemented yet
void unbindMeshBuffer();
//! \todo Not implemented yet
void drawMeshBufferPart(const MeshBuffer* Buffer, u32 StartOffset, u32 NumVertices);
void drawMeshBuffer(const MeshBuffer* MeshBuffer);
/* === Image drawing === */
// todo
/* === Primitive drawing === */
// todo
/* === Extra drawing functions === */
// todo
/* === 3D drawing functions === */
// todo
/* === Matrix controll === */
void updateModelviewMatrix();
};
} // /namespace video
} // /namespace sp
#endif
#endif
// ================================================================================
| 23.509434 | 92 | 0.564607 | rontrek |
04397f6084bea12cc87ab23ff745981aaef5f98c | 2,523 | cp | C++ | Linux/Sources/Application/Preferences_Dialog/CPrefsAlerts.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Linux/Sources/Application/Preferences_Dialog/CPrefsAlerts.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Linux/Sources/Application/Preferences_Dialog/CPrefsAlerts.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// CPrefsAlerts.cpp : implementation file
//
#include "CPrefsAlerts.h"
#include "CTabController.h"
#include "CPrefsAlertsMessage.h"
#include "CPrefsAlertsAttachment.h"
#include <JXColormap.h>
#include <JXStaticText.h>
#include <cassert>
/////////////////////////////////////////////////////////////////////////////
// CPrefsAlerts dialog
CPrefsAlerts::CPrefsAlerts(JXContainer* enclosure,
const HSizingOption hSizing,
const VSizingOption vSizing,
const JCoordinate x, const JCoordinate y,
const JCoordinate w, const JCoordinate h)
:CPrefsPanel(enclosure, hSizing, vSizing, x, y, w, h)
{
}
// Set up params for DDX
void CPrefsAlerts::SetPrefs(CPreferences* prefs)
{
mCopyPrefs = prefs;
mTabs->SetData(prefs);
}
// Get params from DDX
void CPrefsAlerts::UpdatePrefs(CPreferences* prefs)
{
// Get values
mTabs->UpdateData(prefs);
}
/////////////////////////////////////////////////////////////////////////////
// CPrefsDisplay message handlers
void CPrefsAlerts::OnCreate()
{
// begin JXLayout1
JXStaticText* obj1 =
new JXStaticText("Alerts Preferences", this,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 140,20);
assert( obj1 != NULL );
const JFontStyle obj1_style(kTrue, kFalse, 0, kFalse, (GetColormap())->GetBlackColor());
obj1->SetFontStyle(obj1_style);
mTabs =
new CTabController(this,
JXWidget::kHElastic, JXWidget::kVElastic, 10,25, 380,365);
assert( mTabs != NULL );
// end JXLayout1
// Create tab panels
CTabPanel* card = new CPrefsAlertsMessage(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0, 0, 380, 340);
mTabs->AppendCard(card, "Messages");
card = new CPrefsAlertsAttachment(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0, 0, 380, 340);
mTabs->AppendCard(card, "Attachments");
}
| 28.670455 | 129 | 0.660325 | mulberry-mail |
043c111d892737f5bc27f822506430fe64f6c7ca | 632 | cpp | C++ | src/Graphics/Clipping.cpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | 1 | 2022-01-24T18:15:56.000Z | 2022-01-24T18:15:56.000Z | src/Graphics/Clipping.cpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | null | null | null | src/Graphics/Clipping.cpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | null | null | null | #include "Clipping.hpp"
namespace Ondine::Graphics {
void Clipping::init(
VulkanContext &graphicsContext,
float clipFactor, float radius) {
mUBO.init(
graphicsContext.device(), sizeof(mData),
(int)VulkanBufferFlag::UniformBuffer);
uniform.init(
graphicsContext.device(),
graphicsContext.descriptorPool(),
graphicsContext.descriptorLayouts(),
makeArray<VulkanBuffer, AllocationType::Linear>(mUBO));
mData.clipFactor = clipFactor;
mData.clippingRadius = radius;
mUBO.fillWithStaging(
graphicsContext.device(), graphicsContext.commandPool(),
{(uint8_t *)&mData, sizeof(mData)});
}
}
| 23.407407 | 60 | 0.727848 | llGuy |
04432b156c7253de4ae2c0fb220a45a65f60ee92 | 2,091 | cc | C++ | code/foundation/debug/debughandler.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/foundation/debug/debughandler.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/foundation/debug/debughandler.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// debughandler.cc
// (C) 2008 Radon Labs GmbH
// (C) 2013-2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "debug/debughandler.h"
#include "debug/debugpagehandler.h"
#include "timing/time.h"
namespace Debug
{
__ImplementClass(Debug::DebugHandler, 'DBGH', Interface::InterfaceHandlerBase);
using namespace Util;
using namespace Http;
using namespace Interface;
//------------------------------------------------------------------------------
/**
*/
DebugHandler::DebugHandler()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
DebugHandler::~DebugHandler()
{
// empty
}
//------------------------------------------------------------------------------
/**
This method runs in the Debug thread's context and sets up the required
runtime.
*/
void
DebugHandler::Open()
{
n_assert(!this->IsOpen());
InterfaceHandlerBase::Open();
// setup core runtime, debug server and a http server proxy
this->debugServer = DebugServer::Create();
this->debugServer->Open();
this->httpServerProxy = HttpServerProxy::Create();
this->httpServerProxy->Open();
this->httpServerProxy->AttachRequestHandler(Debug::DebugPageHandler::Create());
}
//------------------------------------------------------------------------------
/**
*/
void
DebugHandler::Close()
{
n_assert(this->IsOpen());
this->httpServerProxy->Close();
this->httpServerProxy = 0;
this->debugServer->Close();
this->debugServer = 0;
InterfaceHandlerBase::Close();
}
//------------------------------------------------------------------------------
/**
The per-frame method just checks periodically whether there are
any pending HttpRequests to process...
*/
void
DebugHandler::DoWork()
{
n_assert(this->IsOpen());
this->httpServerProxy->HandlePendingRequests();
Timing::Sleep(0.1);
}
} // namespace Debug
| 24.313953 | 83 | 0.501674 | gscept |
044452cae1d45e0ccdc0e7523fea1f9b8ec5e9b3 | 1,664 | cpp | C++ | unittests/clangd/FSTests.cpp | Szelethus/clang-tools-extra | 4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022 | [
"Apache-2.0"
] | 16 | 2018-11-28T12:05:20.000Z | 2021-11-08T09:47:46.000Z | unittests/clangd/FSTests.cpp | Szelethus/clang-tools-extra | 4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022 | [
"Apache-2.0"
] | 4 | 2018-11-30T19:12:21.000Z | 2019-10-04T17:37:07.000Z | clangd/unittests/FSTests.cpp | dragon-tc-tmp/clang-tools-extra | e16e704b6f7d4185e55942883506c1bb9280cd2d | [
"Apache-2.0"
] | 15 | 2019-02-01T20:10:43.000Z | 2022-03-26T11:52:37.000Z | //===-- FSTests.cpp - File system related tests -----------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "FS.h"
#include "TestFS.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace clang {
namespace clangd {
namespace {
TEST(FSTests, PreambleStatusCache) {
llvm::StringMap<std::string> Files;
Files["x"] = "";
Files["y"] = "";
Files["main"] = "";
auto FS = buildTestFS(Files);
FS->setCurrentWorkingDirectory(testRoot());
PreambleFileStatusCache StatCache(testPath("main"));
auto ProduceFS = StatCache.getProducingFS(FS);
EXPECT_TRUE(ProduceFS->openFileForRead("x"));
EXPECT_TRUE(ProduceFS->status("y"));
EXPECT_TRUE(ProduceFS->status("main"));
EXPECT_TRUE(StatCache.lookup(testPath("x")).hasValue());
EXPECT_TRUE(StatCache.lookup(testPath("y")).hasValue());
// Main file is not cached.
EXPECT_FALSE(StatCache.lookup(testPath("main")).hasValue());
llvm::vfs::Status S("fake", llvm::sys::fs::UniqueID(0, 0),
std::chrono::system_clock::now(), 0, 0, 1024,
llvm::sys::fs::file_type::regular_file,
llvm::sys::fs::all_all);
StatCache.update(*FS, S);
auto ConsumeFS = StatCache.getConsumingFS(FS);
auto Cached = ConsumeFS->status(testPath("fake"));
EXPECT_TRUE(Cached);
EXPECT_EQ(Cached->getName(), S.getName());
}
} // namespace
} // namespace clangd
} // namespace clang
| 32.627451 | 80 | 0.624399 | Szelethus |
0447fac99f1324e984225268fcd10d12286272ba | 2,529 | cpp | C++ | kernel/system/node/Terminal.cpp | pro-hacker64/pranaOS | 01e5f0ba7fc7b561a08ba60ea6b3890202ac97c7 | [
"BSD-2-Clause"
] | null | null | null | kernel/system/node/Terminal.cpp | pro-hacker64/pranaOS | 01e5f0ba7fc7b561a08ba60ea6b3890202ac97c7 | [
"BSD-2-Clause"
] | null | null | null | kernel/system/node/Terminal.cpp | pro-hacker64/pranaOS | 01e5f0ba7fc7b561a08ba60ea6b3890202ac97c7 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2021, krishpranav
*
* SPDX-License-Identifier: BSD-2-Clause
*/
// includes
#include <assert.h>
#include "system/node/Handle.h"
#include "system/node/Terminal.h"
FsTerminal::FsTerminal() : FsNode(J_FILE_TYPE_TERMINAL) {}
bool FsTerminal::can_read(FsHandle &handle)
{
if (handle.has_flag(J_OPEN_SERVER))
{
return !client_to_server_buffer.empty() || !writers();
}
else
{
return !server_to_client_buffer.empty() || !server();
}
}
bool FsTerminal::can_write(FsHandle &handle)
{
if (handle.has_flag(J_OPEN_SERVER))
{
return !server_to_client_buffer.full() || !readers();
}
else
{
return !client_to_server_buffer.full() || !server();
}
}
ResultOr<size_t> FsTerminal::read(FsHandle &handle, void *buffer, size_t size)
{
if (handle.has_flag(J_OPEN_SERVER))
{
if (writers())
{
return client_to_server_buffer.read((char *)buffer, size);
}
else
{
return ERR_STREAM_CLOSED;
}
}
else
{
if (server())
{
return server_to_client_buffer.read((char *)buffer, size);
}
else
{
return ERR_STREAM_CLOSED;
}
}
}
ResultOr<size_t> FsTerminal::write(FsHandle &handle, const void *buffer, size_t size)
{
if (handle.has_flag(J_OPEN_SERVER))
{
if (readers())
{
return server_to_client_buffer.write((const char *)buffer, size);
}
else
{
return ERR_STREAM_CLOSED;
}
}
else
{
if (server())
{
return client_to_server_buffer.write((const char *)buffer, size);
}
else
{
return ERR_STREAM_CLOSED;
}
}
}
JResult FsTerminal::call(FsHandle &handle, IOCall request, void *args)
{
UNUSED(handle);
if (!server())
{
return ERR_STREAM_CLOSED;
}
IOCallTerminalSizeArgs *size_args = (IOCallTerminalSizeArgs *)args;
switch (request)
{
case IOCALL_TERMINAL_GET_SIZE:
size_args->width = _width;
size_args->height = _height;
return SUCCESS;
case IOCALL_TERMINAL_SET_SIZE:
if (size_args->width < 0 || size_args->height < 0)
{
return ERR_INVALID_ARGUMENT;
}
_width = size_args->width;
_height = size_args->height;
return SUCCESS;
default:
return ERR_INAPPROPRIATE_CALL_FOR_DEVICE;
}
} | 20.395161 | 85 | 0.573745 | pro-hacker64 |
04483acc24c83c398f3697a904add51650e374d6 | 2,259 | cpp | C++ | test/azuik/algorithm/sequential_test.cpp | abirbasak/tisa | db281d8b9c5e91ce3297abc42e8eb700b305e678 | [
"Apache-2.0"
] | null | null | null | test/azuik/algorithm/sequential_test.cpp | abirbasak/tisa | db281d8b9c5e91ce3297abc42e8eb700b305e678 | [
"Apache-2.0"
] | null | null | null | test/azuik/algorithm/sequential_test.cpp | abirbasak/tisa | db281d8b9c5e91ce3297abc42e8eb700b305e678 | [
"Apache-2.0"
] | null | null | null |
#include <azuik/algorithm/sequential.hpp>
#include <azuik/tool/unit_test.hpp>
#include <vector>
AZUIK_TEST_SUIT(sequential)
{
using namespace azuik;
AZUIK_TEST_CASE(all_of)
{
std::vector<int> v1{1, 2, 3, 4, 5};
std::vector<int> v2{2, 2, 2, 2, 2};
AZUIK_TEST(core::all_of(v1, 3) == false);
AZUIK_TEST(core::all_of(v2, 2) == true);
AZUIK_TEST(core::all_of(v2, 3) == false);
}
AZUIK_TEST_CASE(none_of)
{
std::vector<int> v1{1, 2, 3, 4, 5};
std::vector<int> v2{2, 2, 2, 2, 2};
AZUIK_TEST(core::none_of(v1, 3) == false);
AZUIK_TEST(core::none_of(v2, 20) == true);
AZUIK_TEST(core::none_of(v2, 3) == true);
AZUIK_TEST(core::none_of(v2, 2) == false);
}
AZUIK_TEST_CASE(any_of)
{
std::vector<int> v1{1, 2, 3, 4, 5};
std::vector<int> v2{2, 2, 2, 2, 2};
AZUIK_TEST(core::any_of(v1, 3) == true);
AZUIK_TEST(core::any_of(v2, 6) == false);
AZUIK_TEST(core::any_of(v2, 3) == false);
AZUIK_TEST(core::any_of(v2, 2) == true);
}
AZUIK_TEST_CASE(count)
{
std::vector<int> v1{1, 2, 3, 2, 5, 2, 5};
AZUIK_TEST(core::count(v1, 1) == 1);
AZUIK_TEST(core::count(v1, 2) == 3);
AZUIK_TEST(core::count(v1, 5) == 2);
AZUIK_TEST(core::count(v1, [](auto x) { return x % 2 == 0; }) == 3);
AZUIK_TEST(core::count(v1, [](auto x) { return x > 2; }) == 3);
}
AZUIK_TEST_CASE(find)
{
std::vector<int> v{0, 1, 2, 3, 4, 5};
AZUIK_TEST(*core::find(v, 3) == 3);
AZUIK_TEST(core::find(v, 10) == std::end(v));
AZUIK_TEST(*core::find(v, [](auto x) { return x == 3; }) == 3);
AZUIK_TEST(core::find(v, [](auto x) { return x == 10; }) == std::end(v));
}
AZUIK_TEST_CASE(find_not)
{
std::vector<int> v0{1, 1, 1, 3, 4, 5};
AZUIK_TEST(*core::find_not(v0, 1) == 3);
std::vector<int> v1{3, 3, 3, 3, 3, 3};
AZUIK_TEST(core::find_not(v1, 3) == std::end(v1));
std::vector<int> v2{0, 1, 2, 3, 4, 5};
AZUIK_TEST(*core::find_not(v2, [](auto x) { return x != 3; }) == 3);
AZUIK_TEST(core::find_not(v2, [](auto x) { return x != 10; }) == std::end(v2));
}
}
| 34.753846 | 87 | 0.518814 | abirbasak |
044bc714aec64dbebc9f319ffd4561e44964ec91 | 1,448 | cpp | C++ | Avni/Engine/GameEngine/Scene/Rectangle.cpp | avinashdamodhare/Avni | 014287c8500ae11a0e6c5141713735556d511414 | [
"MIT"
] | null | null | null | Avni/Engine/GameEngine/Scene/Rectangle.cpp | avinashdamodhare/Avni | 014287c8500ae11a0e6c5141713735556d511414 | [
"MIT"
] | null | null | null | Avni/Engine/GameEngine/Scene/Rectangle.cpp | avinashdamodhare/Avni | 014287c8500ae11a0e6c5141713735556d511414 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Rectangle
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Rectangle.h"
namespace Avni
{
Rectangle::Rectangle(Vector3D firstPoint, Vector3D secondPoint, Vector3D thirdPoint)
{
m_vFirstPoint = firstPoint; m_vSecondPoint = secondPoint; m_vThirdPoint = thirdPoint;
}
Rectangle::~Rectangle()
{
}
void Rectangle::Init()
{
Avni_Vertex_pos_diffuse vert[4];
vert[0].vertex = Vector4D(-1.0f, 1.0f, 0.0f,1.0f);
vert[1].vertex = Vector4D( 1.0f, 1.0f, 0.0f,1.0f);
vert[2].vertex = Vector4D( 1.0f,-1.0f, 0.0f,1.0f);
vert[3].vertex = Vector4D(-1.0f, -1.0f, 0.0f,1.0f);
vert[0].diffuseColor = Vector3D(1.0f,0.0f,0.0f);
vert[1].diffuseColor = Vector3D(0.0f,1.0f,0.0f);
vert[2].diffuseColor = Vector3D(0.0f,0.0f,1.0f);
vert[3].diffuseColor = Vector3D(1.0f,0.0f,1.0f);
u32 indices[] =
{
0, 1, 3,
3, 1, 2,
};
m_Mesh = SINGLETONMANAGER->GetRenderer()->CreateMesh(VERTEXTYPE_POS_DIFFUSE, 4, vert,indices, 6);
m_Material = SINGLETONMANAGER->GetMaterialManager()->GetMaterial(MATERIALNAME_BASIC);
}
void Rectangle::Uninit()
{
}
void Rectangle::Update(float _dt)
{
AvniRenderable render;
render.SetMesh(m_Mesh);
render.SetMaterial(m_Material);
SINGLETONMANAGER->GetRenderer()->AddObjectrenderList(render);
}
} | 26.327273 | 110 | 0.578039 | avinashdamodhare |
044bd1e314bfef54c26248f7ad05650453e6aa6b | 1,606 | cpp | C++ | toml/src/holder.cpp | Hun1eR/TOML | 7c47b3fd7b9d0321f0614cc8c51da8c7e458c22b | [
"MIT"
] | 5 | 2020-05-12T20:11:00.000Z | 2021-02-26T16:59:05.000Z | toml/src/holder.cpp | Hun1eR/TOML | 7c47b3fd7b9d0321f0614cc8c51da8c7e458c22b | [
"MIT"
] | null | null | null | toml/src/holder.cpp | Hun1eR/TOML | 7c47b3fd7b9d0321f0614cc8c51da8c7e458c22b | [
"MIT"
] | null | null | null | // ***********************************************************************
// Author : the_hunter
// Created : 04-01-2020
//
// Last Modified By : the_hunter
// Last Modified On : 04-01-2020
// ***********************************************************************
#include <toml/pch.h>
/// <summary>
/// </summary>
TomlHolder* TomlHolder::find(const cell handle)
{
if (handle_ == handle) {
return this;
}
for (auto& child : children_) {
auto* const holder = child.find(handle);
if (holder) {
return holder;
}
}
return nullptr;
}
/// <summary>
/// </summary>
TomlHolder* TomlHolder::add(toml_t& toml)
{
if (std::addressof(toml) == toml_) {
return this;
}
TomlHolder holder(toml);
const auto& it = std::find(children_.begin(), children_.end(), holder.handle_);
if (it != children_.end()) {
return std::addressof(*it);
}
children_.push_back(std::move(holder));
return std::addressof(children_.back());
}
/// <summary>
/// </summary>
bool TomlHolder::remove(const cell handle)
{
const auto& it = std::find(children_.begin(), children_.end(), handle);
if (it != children_.end()) {
children_.erase(it);
return true;
}
for (auto& child : children_) {
if (child.remove(handle)) {
return true;
}
}
return false;
}
/// <summary>
/// </summary>
bool TomlHolder::remove(const toml_t& toml)
{
const auto& it = std::find(children_.begin(), children_.end(), toml);
if (it != children_.end()) {
children_.erase(it);
return true;
}
for (auto& child : children_) {
if (child.remove(toml)) {
return true;
}
}
return false;
}
| 18.25 | 80 | 0.566002 | Hun1eR |
044cbc8bd701d169c519094723cfdad6bdd54676 | 13,516 | cpp | C++ | BinClone/CloneDetectorGUI/ClonePairsAsmFrame.cpp | wzj1695224/BinClone | 3b6dedb9a1f08be6dbcdce8f3278351ef5530ed8 | [
"Apache-2.0"
] | null | null | null | BinClone/CloneDetectorGUI/ClonePairsAsmFrame.cpp | wzj1695224/BinClone | 3b6dedb9a1f08be6dbcdce8f3278351ef5530ed8 | [
"Apache-2.0"
] | null | null | null | BinClone/CloneDetectorGUI/ClonePairsAsmFrame.cpp | wzj1695224/BinClone | 3b6dedb9a1f08be6dbcdce8f3278351ef5530ed8 | [
"Apache-2.0"
] | null | null | null | //******************************************************************************//
// Copyright 2014 Concordia University //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
//******************************************************************************//
// ClonePairsAsmFrame.cpp : implementation file
//
#include "stdafx.h"
#include "CloneDetectorGUI.h"
#include "ClonePairsAsmFrame.h"
#include "ClonePairsAsmView.h"
#include "MainFrm.h"
#include "BFFileHelper.h"
#include "NewDetectDialog.h"
#include "DControllerDialog.h"
#include "CSController.h"
#include "CloneFiles.h"
#include "BFFileHelper.h"
// ClonePairsAsmFrame
IMPLEMENT_DYNCREATE(ClonePairsAsmFrame, CMDIChildWnd)
ClonePairsAsmFrame::ClonePairsAsmFrame()
:m_bInitSplitter(false),
m_currentLine(-1),
m_numOfClonePairs(0),
m_xmlFile(_T("")),
m_idFromXmlFile(0),
m_syncScroll(true)
{
}
ClonePairsAsmFrame::~ClonePairsAsmFrame()
{
if(m_csController)
delete m_csController;
}
BOOL ClonePairsAsmFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/, CCreateContext* pContext)
{
CRect cr;
GetWindowRect( &cr );
int x = cr.Width();
int y = cr.Height();
// create a splitter with 2 row, 1 columns
if (!m_wndSplitter.CreateStatic(this, 2, 1, (WS_CHILD | WS_VISIBLE))) // | WS_BORDER | WS_CAPTION | WS_THICKFRAME))
{
TRACE0("Failed to CreateStaticSplitter\n");
return FALSE;
}
// add the second splitter pane - which is a nested splitter with 2 columns
if (!m_wndSplitter2.CreateStatic(
&m_wndSplitter, // our parent window is the first splitter
1, 2, // the new splitter is 1 rows, 2 columns
WS_CHILD | WS_VISIBLE | WS_BORDER | WS_CAPTION, // | WS_THICKFRAME, // style, WS_BORDER is needed
m_wndSplitter.IdFromRowCol(0, 0)
// new splitter is in the first row, 2nd column of first splitter
))
{
TRACE0("Failed to create nested splitter\n");
return FALSE;
}
if (!m_wndSplitter2.CreateView(0, 0, RUNTIME_CLASS(ClonePairsAsmView), CSize(x/2, (int) (y * 0.6)), pContext))
{
TRACE0("Failed to create first pane\n");
return FALSE;
}
// add the second splitter pane - an input view in column 1
if (!m_wndSplitter2.CreateView(0, 1,
RUNTIME_CLASS(ClonePairsAsmView), CSize(0, 0), pContext))
{
TRACE0("Failed to create second pane\n");
return FALSE;
}
// now add the ClonePairsList at the buttom window
if (!m_wndSplitter.CreateView(1, 0,
// RUNTIME_CLASS(ClonePairsAsmView), CSize(0, 0), pContext))
//RUNTIME_CLASS(ClonePairsListView), CSize(0, 0), pContext)) // v2.0
RUNTIME_CLASS(ClonePairsTreeView), CSize(0, 0), pContext)) // v2.1
{
TRACE0("Failed to create first pane\n");
return FALSE;
}
//ClonePairsAsmView* pViewList = (ClonePairsAsmView*)m_wndSplitter.GetPane(1,0);
//pViewList->initClonePairList();
m_bInitSplitter = true;
return TRUE;
}
void ClonePairsAsmFrame::OnSize(UINT nType, int cx, int cy)
{
CMDIChildWnd::OnSize(nType, cx, cy);
CRect cr;
GetWindowRect(&cr);
if (m_bInitSplitter && nType != SIZE_MINIMIZED )
{
m_wndSplitter.SetRowInfo( 0, (int) (cr.Height() * 0.6), 0 );
m_wndSplitter2.SetColumnInfo( 0, cr.Width()/2, 50);
m_wndSplitter2.SetColumnInfo( 1, cr.Width()/2, 50);
m_wndSplitter.RecalcLayout();
}
}
bool ClonePairsAsmFrame::init()
{
bool bSearchTargetFrag = theApp.getNewCDSearchFlag();
CString initialFragStr("");
if( bSearchTargetFrag)
{
initialFragStr = theApp.getInitalFragStr();
}
NewDetectDialog newDetectDlg(bSearchTargetFrag,initialFragStr);
newDetectDlg.DoModal();
if( newDetectDlg.m_ok)
{
try
{
//int windSize = CBFStrHelper::strToInt(newDetectDlg.m_windSize);
//int stride = CBFStrHelper::strToInt(newDetectDlg.m_stride);
//int maxKOpLvl = CBFStrHelper::strToInt(newDetectDlg.m_maxKOP);
//double ovLap = CBFStrHelper::strToFloat(newDetectDlg.m_maxOVF);
bool bfindExact = newDetectDlg.m_bFindExactClonesChk ? true : false;
bool bfindInExact = newDetectDlg.m_bFindInexactClonesChk ? true : false;
//int keyVectorsSize = CBFStrHelper::strToInt(newDetectDlg.m_keyVectorsSize);
double occurrenceThrs = CBFStrHelper::strToFloat(newDetectDlg.m_occurrenceThrs);
int regNormLvl = newDetectDlg.m_regNormalizedLevel;
bool bNormalizeToken = newDetectDlg.m_bNormalizeTokenChk ? true : false;
int inexactMTD = newDetectDlg.m_inexactMethodLevel;
int dbParamId = newDetectDlg.m_db_param_id;
LPCTSTR pSearchCodeFrag = NULL;
bool keepTmpFile = false;
CString dbName = newDetectDlg.m_dbName;
CString dbUser = newDetectDlg.m_dbUser;
CString dbPwd = newDetectDlg.m_dbPwd;
//CString targetFilePathAndName;
if( bSearchTargetFrag )
{
pSearchCodeFrag = newDetectDlg.m_searchCodeFragString;
keepTmpFile = newDetectDlg.m_keepTempFileChk ? true : false;
}
CMainFrame* pFrame = (CMainFrame*) AfxGetMainWnd();
pFrame->startProgress();
//CSDataBase postgres benfung Z:\Security20121108b\exp\Data02\btwhidcs.asm TRUE TRUE 0.5 30
//dbName = "CSDataBase"; dbUser = "postgres"; dbPwd = "benfung";
CDControllerDialog cdControlDlg;
m_targetFilePathAndName = newDetectDlg.m_targetAsmFile;
m_csController = new CCSController( dbName, dbUser, dbPwd);
cdControlDlg.init(m_csController, m_targetFilePathAndName,bfindExact,bfindInExact,occurrenceThrs,dbParamId,m_pClones);
cdControlDlg.DoModal();
pFrame->stopProgress();
if( cdControlDlg.m_result == true)
{
m_pClones = cdControlDlg.m_pClones;
return TRUE; // the only place to return true!
}
}
catch(...)
{
AfxMessageBox(_T("Caught an unknown exeception, can't continue!"),
MB_ICONSTOP,0);
}
}
return FALSE;
}
// Version 2.0
void ClonePairsAsmFrame::displayAsmContents(const CString & tarFile, const CString & tarContent, const CString & srcFile, const CString & srcContent)
{
ClonePairsAsmView* pViewA = (ClonePairsAsmView*) m_wndSplitter2.GetPane(0,0);
ClonePairsAsmView* pViewB = (ClonePairsAsmView*) m_wndSplitter2.GetPane(0,1);
pViewA->initView(tarFile,tarContent,1);
pViewB->initView(srcFile,srcContent,2);
}
void ClonePairsAsmFrame::displayTarAsmContents(const CString & tarFile, const CString & tarContent)
{
ClonePairsAsmView* pViewA = (ClonePairsAsmView*) m_wndSplitter2.GetPane(0,0);
pViewA->initView(tarFile,tarContent,1);
}
void ClonePairsAsmFrame::displaySrcAsmContents(const CString & srcFile, const CString & srcContent)
{
ClonePairsAsmView* pViewB = (ClonePairsAsmView*) m_wndSplitter2.GetPane(0,1);
pViewB->initView(srcFile,srcContent,2);
}
BEGIN_MESSAGE_MAP(ClonePairsAsmFrame, CMDIChildWnd)
ON_WM_SIZE()
ON_COMMAND(ID_VIEW_NEXT, &ClonePairsAsmFrame::OnViewNext)
ON_COMMAND(ID_VIEW_PREVIOUS, &ClonePairsAsmFrame::OnViewPrevious)
ON_COMMAND(ID_BUTTON_NEXT, &ClonePairsAsmFrame::OnButtonNext)
ON_COMMAND(ID_BUTTON_PREV, &ClonePairsAsmFrame::OnButtonPrev)
ON_COMMAND(ID_VIEW_SYNCHRONIZEDSCROLLING, &ClonePairsAsmFrame::OnViewSynchronizedscrolling)
ON_UPDATE_COMMAND_UI(ID_VIEW_SYNCHRONIZEDSCROLLING, &ClonePairsAsmFrame::OnUpdateViewSynchronizedscrolling)
END_MESSAGE_MAP()
// ClonePairsAsmFrame message handlers
bool ClonePairsAsmFrame::fillSelectedClonePairsOnViews(int p_selLine)
{
ClonePair clonePair;
if( m_pCurSelCloneFile.getClonePair(p_selLine,clonePair))
{
Region regA = clonePair.m_regionA;
Region regB = clonePair.m_regionB;
ClonePairsAsmView* pViewA = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,0);
SetActiveView(pViewA);
pViewA->highLightLines(clonePair.m_regionA.m_start,clonePair.m_regionA.m_end);
ClonePairsAsmView* pViewB = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,1);
SetActiveView(pViewB);
pViewB->highLightLines(clonePair.m_regionB.m_start,clonePair.m_regionB.m_end);
ClonePairsAsmView* pViewList = (ClonePairsAsmView*)m_wndSplitter.GetPane(1,0);
SetActiveView(pViewList);
pViewList->highLightLines(p_selLine,p_selLine);
return true;
}
return false;
}
// Version 2
bool ClonePairsAsmFrame::fillSelectedClonePairsOnViews2(int listLine, int tarStart, int tarEnd, int srcStart, int srcEnd)
{
ClonePairsAsmView* pViewA = NULL;
ClonePairsAsmView* pViewB = NULL;
ClonePairsAsmView* pViewList = NULL;
if( tarStart >=0 && tarEnd >=0 )
{
pViewA = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,0);
SetActiveView(pViewA);
pViewA->highLightLines(tarStart,tarEnd);
}
if( srcStart >=0 && srcEnd >=0 )
{
pViewB = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,1);
SetActiveView(pViewB);
pViewB->highLightLines(srcStart,srcEnd);
}
if( listLine >= 0)
{
pViewList = (ClonePairsAsmView*)m_wndSplitter.GetPane(1,0);
SetActiveView(pViewList);
pViewList->highLightLines(listLine,listLine);
}
if( pViewA) SetActiveView(pViewA);
if( pViewB) SetActiveView(pViewB);
if( pViewList) SetActiveView(pViewList);
return true;
}
void ClonePairsAsmFrame::ReSyncScroll()
{
ClonePairsTreeView* pViewList = (ClonePairsTreeView*)m_wndSplitter.GetPane(1,0);
pViewList->ReSyncScroll(this);
}
void ClonePairsAsmFrame::OnViewNext()
{
// get the current lines to display
if( m_numOfClonePairs <= 0)
return;
// version 2.1
ClonePairsTreeView* pViewList = (ClonePairsTreeView*)m_wndSplitter.GetPane(1,0);
pViewList->Next();
#if 0
int tmp = m_currentLine;
//if( (tmp < 0) || ( tmp >= (int) m_pCurSelCloneFile.getNumberOfClonePairs()-1))
if( (tmp < 0) || ( tmp >= (int) m_numOfClonePairs-1))
{
tmp = 0;
}
else
{
tmp++;
}
if( tmp == m_currentLine)
return;
ClonePairsAsmView* pViewList = (ClonePairsAsmView*)m_wndSplitter.GetPane(1,0);
pViewList->selectedLine(tmp);
pViewList->highLightLines(tmp,tmp);
m_currentLine = tmp;
/*
if( fillSelectedClonePairsOnViews(tmp))
{
m_currentLine = tmp;
}
*/
#endif
}
void ClonePairsAsmFrame::OnViewPrevious()
{
if( m_numOfClonePairs <= 0)
return;
// version 2.1
ClonePairsTreeView* pViewList = (ClonePairsTreeView*)m_wndSplitter.GetPane(1,0);
pViewList->Previous();
#if 0
int tmp = m_currentLine;
if( tmp < 0)
{
tmp = 0;
}
else if( tmp == 0)
{
tmp = m_numOfClonePairs-1;
//tmp = m_pCurSelCloneFile.getNumberOfClonePairs()-1;
}
else
{
tmp--;
}
if( tmp == m_currentLine)
return;
ClonePairsAsmView* pViewList = (ClonePairsAsmView*)m_wndSplitter.GetPane(1,0);
pViewList->selectedLine(tmp);
pViewList->highLightLines(tmp,tmp);
m_currentLine = tmp;
/*
if( fillSelectedClonePairsOnViews(tmp))
{
m_currentLine = tmp;
}
*/
#endif
}
bool ClonePairsAsmFrame::selectedParticularLine(int p_line)
{
if( fillSelectedClonePairsOnViews(p_line))
{
m_currentLine = p_line;
return true;
}
return false;
}
void ClonePairsAsmFrame::OnButtonNext()
{
// TODO: Add your command handler code here
OnViewNext();
}
void ClonePairsAsmFrame::OnButtonPrev()
{
// TODO: Add your command handler code here
OnViewPrevious();
}
void ClonePairsAsmFrame::SyncScroll(int fromView, UINT nScrollCode, int pos)
{
ClonePairsAsmView* pView;
if( fromView == 2) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,0);
}
else if( fromView == 1) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,1);
}
else {
return;
}
pView->SyncScroll(nScrollCode,pos);
}
void ClonePairsAsmFrame::SyncVWScroll(int fromView, UINT nFlags, short zDelta, CPoint pt)
{
ClonePairsAsmView* pView;
if( fromView == 2) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,0);
}
else if( fromView == 1) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,1);
}
else {
return;
}
pView->SyncVWScroll(nFlags,zDelta,pt);
}
void ClonePairsAsmFrame::KeySynchro(int fromView, UINT nChar)
{
ClonePairsAsmView* pView;
if( fromView == 2) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,0);
}
else if( fromView == 1) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,1);
}
else {
return;
}
pView->KeySynchro(nChar);
}
void ClonePairsAsmFrame::KeySynchro(int fromView, UINT nChar, UINT nRepCnt, UINT nFlags)
{
ClonePairsAsmView* pView;
if( fromView == 2) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,0);
}
else if( fromView == 1) {
pView = (ClonePairsAsmView*)m_wndSplitter2.GetPane(0,1);
}
else {
return;
}
pView->KeySynchro(nChar);
}
void ClonePairsAsmFrame::OnViewSynchronizedscrolling()
{
// TODO: Add your command handler code here
if( m_syncScroll )
m_syncScroll = false;
else
m_syncScroll = true;
}
void ClonePairsAsmFrame::OnUpdateViewSynchronizedscrolling(CCmdUI *pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->SetCheck(m_syncScroll ? 1 : 0 );
}
| 27.360324 | 174 | 0.697544 | wzj1695224 |
044e839427ad721528cc97efa6b4592cf84ab092 | 5,301 | cpp | C++ | fawnkv/cache.cpp | abcinje/FAWN-KV | 6c557b3793010eb0b2f08d4bd0d47b5e68801080 | [
"Apache-2.0"
] | 50 | 2015-04-24T23:12:20.000Z | 2022-01-27T06:03:11.000Z | fawnkv/cache.cpp | abcinje/FAWN-KV | 6c557b3793010eb0b2f08d4bd0d47b5e68801080 | [
"Apache-2.0"
] | null | null | null | fawnkv/cache.cpp | abcinje/FAWN-KV | 6c557b3793010eb0b2f08d4bd0d47b5e68801080 | [
"Apache-2.0"
] | 12 | 2015-02-24T01:34:10.000Z | 2021-12-22T04:39:03.000Z | /* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* Cache tester by Jason Franklin (jfrankli@cs.cmu.edu) */
/* Derived from fe_tester.cpp */
using namespace std;
#include <iostream>
#include <sstream>
#include <string>
#include "fe.h"
#include "dbid.h"
#include "hashutil.h"
#include "timing.h"
using fawn::HashUtil;
using fawn::DBID;
#include <unistd.h>
#include <map>
#include <list>
#include <pthread.h>
int total = 0;
int numGets = 0;
struct timeval start;
string* value;
bool printedStats;
void put_cb(unsigned int continuation)
{
#ifdef DEBUG
cout << "Woah! Got to put_cb." << endl;
#endif
}
void get_cb(DBID* p_key, string* p_value, unsigned int continuation, bool success, bool cached)
{
#ifdef DEBUG
cout << "Woah! Got to get_cb. " << endl;
#endif
#ifdef DEBUG
cout << "\t Key: " << p_key->actual_data_str() << endl;
if (p_value) {
cout << "\t Value: " << *p_value << endl;
}
else {
cout << "\t Value: NULL" << endl;
}
cout << "\t Continuation Id: " << continuation << endl;
cout << "\t Get Success?: " << (success ? "yes!" : "no") << " Success #: " ;
#endif
if (p_value->compare(value->c_str())) {
cout << "ERROR: returned value does not match expected value." << endl;
cout << "value is: " << *p_value << endl;
}
numGets++;
if (numGets % 100000 == 0)
cout << "Number of successful gets: " << numGets << endl;
if (((double)numGets) >= ((double)(0.9)*total) && !printedStats) {
struct timeval end;
gettimeofday(&end, NULL);
double diff = timeval_diff(&start, &end);
cout << "Num Queries: " << total << " time: " << diff << endl;
cout << "Query Rate: " << (total / diff) << " qps" << endl;
printedStats = true;
}
if (success) {
//if (numGets % 100 == 0)
//cout << "Successful gets: " << ++numGets << endl;
} else {
cout << "Fail" << endl;
cout << endl; // flush!
}
if (!cached && p_key)
delete p_key;
if (!cached && p_value) {
delete p_value;
}
//cout << "exiting get cb" << endl;
}
void *localThreadLoop(void *p)
{
FrontEnd* fe = (FrontEnd*) p;
// TODO: Fix Hack. Just used to keep client around.
while(1) {
fe->log_stats();
sleep(1);
}
return NULL;
}
void usage()
{
cerr << "./fe_tester <My IP> <Corpus Size> <Bias Size> <Num Gets> <Cache Entries>\n" <<endl;
}
int main(int argc, char **argv)
{
if (argc != 6) {
usage();
exit(-1);
}
string p_myIP(argv[1]);
int corpus = atoi(argv[2]);
int bias = atoi(argv[3]);
int num_gets = atoi(argv[4]);
int num_cache_entries = atoi(argv[5]); /* N log N entries, where N = num wimpies */
cout << "Corpus: " << corpus << endl
<< " Bias: " << bias << endl
<< " Queries: " << num_gets << endl
<< " Cache Entries: " << num_cache_entries << endl;
total = num_gets;
/* Initialize ring with cache enabled */
FrontEnd* p_fe = FrontEnd::Instance(p_myIP, true, num_cache_entries);
value = new string(256, 'v');
printedStats = false;
pthread_t localThreadId_;
pthread_create(&localThreadId_, NULL,
localThreadLoop, (void*)p_fe);
p_fe->register_put_cb(&put_cb);
p_fe->register_get_cb(&get_cb);
srand ( time(NULL) );
struct timespec req;
req.tv_sec = 0;
req.tv_nsec = 50000;
cout << "Enter 'start' to start performing puts." << endl;
string tempstr;
cin >> tempstr;
/* Load database */
for (int i = 0; i < corpus; i++) {
ostringstream s;
s << "key" << i;
string ps_key = s.str();
if (i % 1000000 == 0)
cout << "inserting: " << ps_key << endl;
u_int32_t key_id = HashUtil::MakeHashedKey(ps_key);
DBID* key = new DBID((char *)&key_id, sizeof(u_int32_t));
p_fe->put(key, value, i);
delete key;
nanosleep(&req, NULL);
}
cout << "Enter 'start' to start performing gets." << endl;
cin >> tempstr;
/* Fetch items at random */
int num = 0;
gettimeofday(&start, NULL);
for (int i = 0; i < num_gets; i++) {
/* Biasing */
int rand_val = rand() % 100;
double prob_pick_hot_item = ((double) (corpus - bias)) / corpus;
int perc_pick_hot_item = (int) (prob_pick_hot_item * ((double) 100));
//cout << "Random value (between 0 and 100): " << rand_val << endl;
//cout << "Probability of picking hot item: " << prob_pick_hot_item << endl;
//cout << "Percentage of picking hot item: " << perc_pick_hot_item << endl;
if (rand_val <= perc_pick_hot_item) {
num = rand()% bias;
//cout << "Fetching hot item " << num << endl;
} else {
//cout << "Cold item fetch: " << num << endl;
num = rand()%corpus;
if (num <= bias) {
num = ((int)((corpus-bias)*(rand_val/100))) + bias;
}
}
ostringstream out2;
out2 << "key" << num;
string ps_key = out2.str();
u_int32_t key_id = HashUtil::MakeHashedKey(ps_key);
DBID* key_p = new DBID((char *)&key_id, sizeof(u_int32_t));
if (key_p == NULL) {
cout << "ERROR: Malloc of ID failed. Out of Memory." << endl;
} /* XXX - and yet, we then pass it to get? */
p_fe->get(key_p, 2);
delete key_p;
}
pthread_join(localThreadId_, NULL);
cout << "Exiting front-end manager." << endl;
FrontEnd::Destroy();
return 0;
}
| 23.25 | 96 | 0.578947 | abcinje |
045185e9a7de6380d4642e9c3f1a14fdf08b35ae | 368 | cpp | C++ | ieee_sep/PriceResponse.cpp | Tylores/ieee_sep | 1928bed8076f4bfe702d34e436c6a85f197b0832 | [
"BSD-2-Clause"
] | null | null | null | ieee_sep/PriceResponse.cpp | Tylores/ieee_sep | 1928bed8076f4bfe702d34e436c6a85f197b0832 | [
"BSD-2-Clause"
] | null | null | null | ieee_sep/PriceResponse.cpp | Tylores/ieee_sep | 1928bed8076f4bfe702d34e436c6a85f197b0832 | [
"BSD-2-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////
// PriceResponse.cpp
// Implementation of the Class PriceResponse
// Created on: 13-Apr-2020 2:51:37 PM
// Original author: svanausdall
///////////////////////////////////////////////////////////
#include "PriceResponse.h"
PriceResponse::PriceResponse(){
}
PriceResponse::~PriceResponse(){
} | 19.368421 | 59 | 0.478261 | Tylores |
045574fdcfead4456567e22425f5a6a7f1112fd5 | 960 | cpp | C++ | src/terark/io/todo/inter_thread_pipe.cpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 44 | 2020-12-21T05:14:38.000Z | 2022-03-15T11:27:32.000Z | src/terark/io/todo/inter_thread_pipe.cpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 2 | 2020-12-28T10:42:03.000Z | 2021-05-21T07:22:47.000Z | src/terark/io/todo/inter_thread_pipe.cpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 21 | 2020-12-22T09:40:16.000Z | 2021-12-07T18:16:00.000Z | #include "inter_thread_pipe.cpp"
namespace terark {
class inter_thread_pipe_impl
{
boost::mutex m_mutex;
boost::condition m_cond;
unsigned char *m_bufp, *m_putp, *m_getp;
size_t m_size;
long m_timeout;
public:
bool eof()
{
boost::mutex::scoped_lock lock(m_mutex);
return (m_size+(m_get-m_putp)) % m_size == 1;
}
size_t read(void* vbuf, size_t length)
{
boost::mutex::scoped_lock lock(m_mutex);
}
size_t write(void* vbuf, size_t length)
{
}
void flush()
{
}
};
inter_thread_pipe::inter_thread_pipe(size_t capacity)
: mio(new capacity)
{
}
inter_thread_pipe::~inter_thread_pipe()
{
delete capacity;
}
bool inter_thread_pipe::eof()
{
return mio->eof();
}
size_t inter_thread_pipe::read(void* vbuf, size_t length)
{
return mio->read(vbuf, length);
}
size_t inter_thread_pipe::write(void* vbuf, size_t length)
{
}
void inter_thread_pipe::flush()
{
}
} // namespace thread
| 13.913043 | 59 | 0.669792 | rockeet |
04574bdfa853a46cbd3fce70c2c4afd53c394027 | 35,298 | hpp | C++ | include/RootMotion/FinalIK/Grounding.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/Grounding.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/Grounding.hpp | marksteward/BeatSaber-Quest-Codegen | a76f063f71cef207a9f048ad7613835f554911a7 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.LayerMask
#include "UnityEngine/LayerMask.hpp"
// Including type: UnityEngine.RaycastHit
#include "UnityEngine/RaycastHit.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
// Skipping declaration: Vector3 because it is already included!
}
// Forward declaring namespace: RootMotion::FinalIK
namespace RootMotion::FinalIK {
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Size: 0xA5
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.Grounding
// [TokenAttribute] Offset: FFFFFFFF
class Grounding : public ::Il2CppObject {
public:
// Nested type: RootMotion::FinalIK::Grounding::Quality
struct Quality;
// Nested type: RootMotion::FinalIK::Grounding::Leg
class Leg;
// Nested type: RootMotion::FinalIK::Grounding::Pelvis
class Pelvis;
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality
// [TokenAttribute] Offset: FFFFFFFF
struct Quality/*, public System::Enum*/ {
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: Quality
constexpr Quality(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::Enum
operator System::Enum() noexcept {
return *reinterpret_cast<System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Fastest
static constexpr const int Fastest = 0;
// Get static field: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Fastest
static RootMotion::FinalIK::Grounding::Quality _get_Fastest();
// Set static field: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Fastest
static void _set_Fastest(RootMotion::FinalIK::Grounding::Quality value);
// static field const value: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Simple
static constexpr const int Simple = 1;
// Get static field: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Simple
static RootMotion::FinalIK::Grounding::Quality _get_Simple();
// Set static field: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Simple
static void _set_Simple(RootMotion::FinalIK::Grounding::Quality value);
// static field const value: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Best
static constexpr const int Best = 2;
// Get static field: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Best
static RootMotion::FinalIK::Grounding::Quality _get_Best();
// Set static field: static public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality Best
static void _set_Best(RootMotion::FinalIK::Grounding::Quality value);
// Get instance field: public System.Int32 value__
int _get_value__();
// Set instance field: public System.Int32 value__
void _set_value__(int value);
}; // RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality
#pragma pack(pop)
static check_size<sizeof(Grounding::Quality), 0 + sizeof(int)> __RootMotion_FinalIK_Grounding_QualitySizeCheck;
static_assert(sizeof(Grounding::Quality) == 0x4);
// [TooltipAttribute] Offset: 0xE9FDE8
// public UnityEngine.LayerMask layers
// Size: 0x4
// Offset: 0x10
UnityEngine::LayerMask layers;
// Field size check
static_assert(sizeof(UnityEngine::LayerMask) == 0x4);
// [TooltipAttribute] Offset: 0xE9FE20
// public System.Single maxStep
// Size: 0x4
// Offset: 0x14
float maxStep;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE9FE58
// public System.Single heightOffset
// Size: 0x4
// Offset: 0x18
float heightOffset;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE9FE90
// public System.Single footSpeed
// Size: 0x4
// Offset: 0x1C
float footSpeed;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE9FEC8
// public System.Single footRadius
// Size: 0x4
// Offset: 0x20
float footRadius;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE9FF00
// public System.Single footCenterOffset
// Size: 0x4
// Offset: 0x24
float footCenterOffset;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE9FF4C
// public System.Single prediction
// Size: 0x4
// Offset: 0x28
float prediction;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE9FF84
// [RangeAttribute] Offset: 0xE9FF84
// public System.Single footRotationWeight
// Size: 0x4
// Offset: 0x2C
float footRotationWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xE9FFD8
// public System.Single footRotationSpeed
// Size: 0x4
// Offset: 0x30
float footRotationSpeed;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xEA0010
// [RangeAttribute] Offset: 0xEA0010
// public System.Single maxFootRotationAngle
// Size: 0x4
// Offset: 0x34
float maxFootRotationAngle;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xEA0068
// public System.Boolean rotateSolver
// Size: 0x1
// Offset: 0x38
bool rotateSolver;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: rotateSolver and: pelvisSpeed
char __padding10[0x3] = {};
// [TooltipAttribute] Offset: 0xEA00A0
// public System.Single pelvisSpeed
// Size: 0x4
// Offset: 0x3C
float pelvisSpeed;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xEA00D8
// [RangeAttribute] Offset: 0xEA00D8
// public System.Single pelvisDamper
// Size: 0x4
// Offset: 0x40
float pelvisDamper;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xEA012C
// public System.Single lowerPelvisWeight
// Size: 0x4
// Offset: 0x44
float lowerPelvisWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xEA0164
// public System.Single liftPelvisWeight
// Size: 0x4
// Offset: 0x48
float liftPelvisWeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xEA019C
// public System.Single rootSphereCastRadius
// Size: 0x4
// Offset: 0x4C
float rootSphereCastRadius;
// Field size check
static_assert(sizeof(float) == 0x4);
// [TooltipAttribute] Offset: 0xEA01D4
// public System.Boolean overstepFallsDown
// Size: 0x1
// Offset: 0x50
bool overstepFallsDown;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: overstepFallsDown and: quality
char __padding16[0x3] = {};
// [TooltipAttribute] Offset: 0xEA020C
// public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality quality
// Size: 0x4
// Offset: 0x54
RootMotion::FinalIK::Grounding::Quality quality;
// Field size check
static_assert(sizeof(RootMotion::FinalIK::Grounding::Quality) == 0x4);
// private RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Leg[] <legs>k__BackingField
// Size: 0x8
// Offset: 0x58
::Array<RootMotion::FinalIK::Grounding::Leg*>* legs;
// Field size check
static_assert(sizeof(::Array<RootMotion::FinalIK::Grounding::Leg*>*) == 0x8);
// private RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Pelvis <pelvis>k__BackingField
// Size: 0x8
// Offset: 0x60
RootMotion::FinalIK::Grounding::Pelvis* pelvis;
// Field size check
static_assert(sizeof(RootMotion::FinalIK::Grounding::Pelvis*) == 0x8);
// private System.Boolean <isGrounded>k__BackingField
// Size: 0x1
// Offset: 0x68
bool isGrounded;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: isGrounded and: root
char __padding20[0x7] = {};
// private UnityEngine.Transform <root>k__BackingField
// Size: 0x8
// Offset: 0x70
UnityEngine::Transform* root;
// Field size check
static_assert(sizeof(UnityEngine::Transform*) == 0x8);
// private UnityEngine.RaycastHit <rootHit>k__BackingField
// Size: 0x2C
// Offset: 0x78
UnityEngine::RaycastHit rootHit;
// Field size check
static_assert(sizeof(UnityEngine::RaycastHit) == 0x2C);
// private System.Boolean initiated
// Size: 0x1
// Offset: 0xA4
bool initiated;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: Grounding
Grounding(UnityEngine::LayerMask layers_ = {}, float maxStep_ = {}, float heightOffset_ = {}, float footSpeed_ = {}, float footRadius_ = {}, float footCenterOffset_ = {}, float prediction_ = {}, float footRotationWeight_ = {}, float footRotationSpeed_ = {}, float maxFootRotationAngle_ = {}, bool rotateSolver_ = {}, float pelvisSpeed_ = {}, float pelvisDamper_ = {}, float lowerPelvisWeight_ = {}, float liftPelvisWeight_ = {}, float rootSphereCastRadius_ = {}, bool overstepFallsDown_ = {}, RootMotion::FinalIK::Grounding::Quality quality_ = {}, ::Array<RootMotion::FinalIK::Grounding::Leg*>* legs_ = {}, RootMotion::FinalIK::Grounding::Pelvis* pelvis_ = {}, bool isGrounded_ = {}, UnityEngine::Transform* root_ = {}, UnityEngine::RaycastHit rootHit_ = {}, bool initiated_ = {}) noexcept : layers{layers_}, maxStep{maxStep_}, heightOffset{heightOffset_}, footSpeed{footSpeed_}, footRadius{footRadius_}, footCenterOffset{footCenterOffset_}, prediction{prediction_}, footRotationWeight{footRotationWeight_}, footRotationSpeed{footRotationSpeed_}, maxFootRotationAngle{maxFootRotationAngle_}, rotateSolver{rotateSolver_}, pelvisSpeed{pelvisSpeed_}, pelvisDamper{pelvisDamper_}, lowerPelvisWeight{lowerPelvisWeight_}, liftPelvisWeight{liftPelvisWeight_}, rootSphereCastRadius{rootSphereCastRadius_}, overstepFallsDown{overstepFallsDown_}, quality{quality_}, legs{legs_}, pelvis{pelvis_}, isGrounded{isGrounded_}, root{root_}, rootHit{rootHit_}, initiated{initiated_} {}
// Get instance field: public UnityEngine.LayerMask layers
UnityEngine::LayerMask _get_layers();
// Set instance field: public UnityEngine.LayerMask layers
void _set_layers(UnityEngine::LayerMask value);
// Get instance field: public System.Single maxStep
float _get_maxStep();
// Set instance field: public System.Single maxStep
void _set_maxStep(float value);
// Get instance field: public System.Single heightOffset
float _get_heightOffset();
// Set instance field: public System.Single heightOffset
void _set_heightOffset(float value);
// Get instance field: public System.Single footSpeed
float _get_footSpeed();
// Set instance field: public System.Single footSpeed
void _set_footSpeed(float value);
// Get instance field: public System.Single footRadius
float _get_footRadius();
// Set instance field: public System.Single footRadius
void _set_footRadius(float value);
// Get instance field: public System.Single footCenterOffset
float _get_footCenterOffset();
// Set instance field: public System.Single footCenterOffset
void _set_footCenterOffset(float value);
// Get instance field: public System.Single prediction
float _get_prediction();
// Set instance field: public System.Single prediction
void _set_prediction(float value);
// Get instance field: public System.Single footRotationWeight
float _get_footRotationWeight();
// Set instance field: public System.Single footRotationWeight
void _set_footRotationWeight(float value);
// Get instance field: public System.Single footRotationSpeed
float _get_footRotationSpeed();
// Set instance field: public System.Single footRotationSpeed
void _set_footRotationSpeed(float value);
// Get instance field: public System.Single maxFootRotationAngle
float _get_maxFootRotationAngle();
// Set instance field: public System.Single maxFootRotationAngle
void _set_maxFootRotationAngle(float value);
// Get instance field: public System.Boolean rotateSolver
bool _get_rotateSolver();
// Set instance field: public System.Boolean rotateSolver
void _set_rotateSolver(bool value);
// Get instance field: public System.Single pelvisSpeed
float _get_pelvisSpeed();
// Set instance field: public System.Single pelvisSpeed
void _set_pelvisSpeed(float value);
// Get instance field: public System.Single pelvisDamper
float _get_pelvisDamper();
// Set instance field: public System.Single pelvisDamper
void _set_pelvisDamper(float value);
// Get instance field: public System.Single lowerPelvisWeight
float _get_lowerPelvisWeight();
// Set instance field: public System.Single lowerPelvisWeight
void _set_lowerPelvisWeight(float value);
// Get instance field: public System.Single liftPelvisWeight
float _get_liftPelvisWeight();
// Set instance field: public System.Single liftPelvisWeight
void _set_liftPelvisWeight(float value);
// Get instance field: public System.Single rootSphereCastRadius
float _get_rootSphereCastRadius();
// Set instance field: public System.Single rootSphereCastRadius
void _set_rootSphereCastRadius(float value);
// Get instance field: public System.Boolean overstepFallsDown
bool _get_overstepFallsDown();
// Set instance field: public System.Boolean overstepFallsDown
void _set_overstepFallsDown(bool value);
// Get instance field: public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality quality
RootMotion::FinalIK::Grounding::Quality _get_quality();
// Set instance field: public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Quality quality
void _set_quality(RootMotion::FinalIK::Grounding::Quality value);
// Get instance field: private RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Leg[] <legs>k__BackingField
::Array<RootMotion::FinalIK::Grounding::Leg*>* _get_$legs$k__BackingField();
// Set instance field: private RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Leg[] <legs>k__BackingField
void _set_$legs$k__BackingField(::Array<RootMotion::FinalIK::Grounding::Leg*>* value);
// Get instance field: private RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Pelvis <pelvis>k__BackingField
RootMotion::FinalIK::Grounding::Pelvis* _get_$pelvis$k__BackingField();
// Set instance field: private RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Pelvis <pelvis>k__BackingField
void _set_$pelvis$k__BackingField(RootMotion::FinalIK::Grounding::Pelvis* value);
// Get instance field: private System.Boolean <isGrounded>k__BackingField
bool _get_$isGrounded$k__BackingField();
// Set instance field: private System.Boolean <isGrounded>k__BackingField
void _set_$isGrounded$k__BackingField(bool value);
// Get instance field: private UnityEngine.Transform <root>k__BackingField
UnityEngine::Transform* _get_$root$k__BackingField();
// Set instance field: private UnityEngine.Transform <root>k__BackingField
void _set_$root$k__BackingField(UnityEngine::Transform* value);
// Get instance field: private UnityEngine.RaycastHit <rootHit>k__BackingField
UnityEngine::RaycastHit _get_$rootHit$k__BackingField();
// Set instance field: private UnityEngine.RaycastHit <rootHit>k__BackingField
void _set_$rootHit$k__BackingField(UnityEngine::RaycastHit value);
// Get instance field: private System.Boolean initiated
bool _get_initiated();
// Set instance field: private System.Boolean initiated
void _set_initiated(bool value);
// public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Leg[] get_legs()
// Offset: 0x182EBD4
::Array<RootMotion::FinalIK::Grounding::Leg*>* get_legs();
// private System.Void set_legs(RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Leg[] value)
// Offset: 0x182EBDC
void set_legs(::Array<RootMotion::FinalIK::Grounding::Leg*>* value);
// public RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Pelvis get_pelvis()
// Offset: 0x182EBE4
RootMotion::FinalIK::Grounding::Pelvis* get_pelvis();
// private System.Void set_pelvis(RootMotion.FinalIK.Grounding/RootMotion.FinalIK.Pelvis value)
// Offset: 0x182EBEC
void set_pelvis(RootMotion::FinalIK::Grounding::Pelvis* value);
// public System.Boolean get_isGrounded()
// Offset: 0x182EBF4
bool get_isGrounded();
// private System.Void set_isGrounded(System.Boolean value)
// Offset: 0x182EBFC
void set_isGrounded(bool value);
// public UnityEngine.Transform get_root()
// Offset: 0x182EC08
UnityEngine::Transform* get_root();
// private System.Void set_root(UnityEngine.Transform value)
// Offset: 0x182EC10
void set_root(UnityEngine::Transform* value);
// public UnityEngine.RaycastHit get_rootHit()
// Offset: 0x182EC18
UnityEngine::RaycastHit get_rootHit();
// private System.Void set_rootHit(UnityEngine.RaycastHit value)
// Offset: 0x182EC30
void set_rootHit(UnityEngine::RaycastHit value);
// public System.Boolean get_rootGrounded()
// Offset: 0x182EC50
bool get_rootGrounded();
// public UnityEngine.Vector3 get_up()
// Offset: 0x1829148
UnityEngine::Vector3 get_up();
// private System.Boolean get_useRootRotation()
// Offset: 0x182FFC0
bool get_useRootRotation();
// public UnityEngine.RaycastHit GetRootHit(System.Single maxDistanceMlp)
// Offset: 0x182ECA4
UnityEngine::RaycastHit GetRootHit(float maxDistanceMlp);
// public System.Boolean IsValid(ref System.String errorMessage)
// Offset: 0x182F084
bool IsValid(ByRef<::Il2CppString*> errorMessage);
// public System.Void Initiate(UnityEngine.Transform root, UnityEngine.Transform[] feet)
// Offset: 0x182860C
void Initiate(UnityEngine::Transform* root, ::Array<UnityEngine::Transform*>* feet);
// public System.Void Update()
// Offset: 0x1828E0C
void Update();
// public UnityEngine.Vector3 GetLegsPlaneNormal()
// Offset: 0x182AC64
UnityEngine::Vector3 GetLegsPlaneNormal();
// public System.Void Reset()
// Offset: 0x1828170
void Reset();
// public System.Void LogWarning(System.String message)
// Offset: 0x182F304
void LogWarning(::Il2CppString* message);
// public System.Single GetVerticalOffset(UnityEngine.Vector3 p1, UnityEngine.Vector3 p2)
// Offset: 0x1830090
float GetVerticalOffset(UnityEngine::Vector3 p1, UnityEngine::Vector3 p2);
// public UnityEngine.Vector3 Flatten(UnityEngine.Vector3 v)
// Offset: 0x18301F8
UnityEngine::Vector3 Flatten(UnityEngine::Vector3 v);
// public UnityEngine.Vector3 GetFootCenterOffset()
// Offset: 0x18302FC
UnityEngine::Vector3 GetFootCenterOffset();
// public System.Void .ctor()
// Offset: 0x1827DB0
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static Grounding* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::Grounding::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<Grounding*, creationType>()));
}
}; // RootMotion.FinalIK.Grounding
#pragma pack(pop)
static check_size<sizeof(Grounding), 164 + sizeof(bool)> __RootMotion_FinalIK_GroundingSizeCheck;
static_assert(sizeof(Grounding) == 0xA5);
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::Grounding*, "RootMotion.FinalIK", "Grounding");
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::Grounding::Quality, "RootMotion.FinalIK", "Grounding/Quality");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_legs
// Il2CppName: get_legs
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Array<RootMotion::FinalIK::Grounding::Leg*>* (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_legs)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_legs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::set_legs
// Il2CppName: set_legs
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)(::Array<RootMotion::FinalIK::Grounding::Leg*>*)>(&RootMotion::FinalIK::Grounding::set_legs)> {
static const MethodInfo* get() {
static auto* value = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("RootMotion.FinalIK", "Grounding/Leg"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "set_legs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_pelvis
// Il2CppName: get_pelvis
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<RootMotion::FinalIK::Grounding::Pelvis* (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_pelvis)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_pelvis", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::set_pelvis
// Il2CppName: set_pelvis
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)(RootMotion::FinalIK::Grounding::Pelvis*)>(&RootMotion::FinalIK::Grounding::set_pelvis)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("RootMotion.FinalIK", "Grounding/Pelvis")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "set_pelvis", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_isGrounded
// Il2CppName: get_isGrounded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_isGrounded)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_isGrounded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::set_isGrounded
// Il2CppName: set_isGrounded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)(bool)>(&RootMotion::FinalIK::Grounding::set_isGrounded)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "set_isGrounded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_root
// Il2CppName: get_root
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Transform* (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_root)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_root", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::set_root
// Il2CppName: set_root
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)(UnityEngine::Transform*)>(&RootMotion::FinalIK::Grounding::set_root)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Transform")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "set_root", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_rootHit
// Il2CppName: get_rootHit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::RaycastHit (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_rootHit)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_rootHit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::set_rootHit
// Il2CppName: set_rootHit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)(UnityEngine::RaycastHit)>(&RootMotion::FinalIK::Grounding::set_rootHit)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "RaycastHit")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "set_rootHit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_rootGrounded
// Il2CppName: get_rootGrounded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_rootGrounded)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_rootGrounded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_up
// Il2CppName: get_up
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector3 (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_up)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_up", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::get_useRootRotation
// Il2CppName: get_useRootRotation
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::get_useRootRotation)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "get_useRootRotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::GetRootHit
// Il2CppName: GetRootHit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::RaycastHit (RootMotion::FinalIK::Grounding::*)(float)>(&RootMotion::FinalIK::Grounding::GetRootHit)> {
static const MethodInfo* get() {
static auto* maxDistanceMlp = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "GetRootHit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{maxDistanceMlp});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::IsValid
// Il2CppName: IsValid
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (RootMotion::FinalIK::Grounding::*)(ByRef<::Il2CppString*>)>(&RootMotion::FinalIK::Grounding::IsValid)> {
static const MethodInfo* get() {
static auto* errorMessage = &::il2cpp_utils::GetClassFromName("System", "String")->this_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "IsValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{errorMessage});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::Initiate
// Il2CppName: Initiate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)(UnityEngine::Transform*, ::Array<UnityEngine::Transform*>*)>(&RootMotion::FinalIK::Grounding::Initiate)> {
static const MethodInfo* get() {
static auto* root = &::il2cpp_utils::GetClassFromName("UnityEngine", "Transform")->byval_arg;
static auto* feet = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("UnityEngine", "Transform"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "Initiate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{root, feet});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::GetLegsPlaneNormal
// Il2CppName: GetLegsPlaneNormal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector3 (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::GetLegsPlaneNormal)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "GetLegsPlaneNormal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::Reset
// Il2CppName: Reset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::Reset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::LogWarning
// Il2CppName: LogWarning
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::Grounding::*)(::Il2CppString*)>(&RootMotion::FinalIK::Grounding::LogWarning)> {
static const MethodInfo* get() {
static auto* message = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "LogWarning", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{message});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::GetVerticalOffset
// Il2CppName: GetVerticalOffset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (RootMotion::FinalIK::Grounding::*)(UnityEngine::Vector3, UnityEngine::Vector3)>(&RootMotion::FinalIK::Grounding::GetVerticalOffset)> {
static const MethodInfo* get() {
static auto* p1 = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
static auto* p2 = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "GetVerticalOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{p1, p2});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::Flatten
// Il2CppName: Flatten
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector3 (RootMotion::FinalIK::Grounding::*)(UnityEngine::Vector3)>(&RootMotion::FinalIK::Grounding::Flatten)> {
static const MethodInfo* get() {
static auto* v = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "Flatten", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{v});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::GetFootCenterOffset
// Il2CppName: GetFootCenterOffset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::Vector3 (RootMotion::FinalIK::Grounding::*)()>(&RootMotion::FinalIK::Grounding::GetFootCenterOffset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::Grounding*), "GetFootCenterOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::Grounding::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 54.472222 | 1,472 | 0.719644 | marksteward |
0458248d635d9eaf290b63bf7eee5df92aa1bcc6 | 8,981 | cpp | C++ | Testcase/RegStream/SRC/device.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 1 | 2021-02-08T20:31:46.000Z | 2021-02-08T20:31:46.000Z | Testcase/RegStream/SRC/device.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | null | null | null | Testcase/RegStream/SRC/device.cpp | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 4 | 2019-11-14T03:47:33.000Z | 2021-03-08T01:18:05.000Z | /***************************************************************************
//
// DEVICE.CPP
//
// TAPI Service provider for TSP++ version 3.00
// Handles raw device events and the physical connection to the hardware.
//
// Copyright (C) 1999 Test
// All rights reserved
//
// Generated by the TSPWizard (C) JulMar Technology, Inc.
//
/***************************************************************************/
/*----------------------------------------------------------------------------
INCLUDE FILES
-----------------------------------------------------------------------------*/
#include "stdafx.h"
#include <process.h>
#include "Test.h"
#include <spbstrm.h>
/*****************************************************************************
** Procedure: MainConnThread
**
** Arguments: 'pDevice' - Device object
**
** Returns: void
**
** Description: Main connection thread
**
*****************************************************************************/
static unsigned __stdcall MainConnThread(void* pParam)
{
reinterpret_cast<CTestDevice*>(pParam)->ConnectionThread();
_endthreadex(0);
return 0;
}// ConnThread
/*****************************************************************************
** Procedure: CTestDevice::CTestDevice
**
** Arguments: void
**
** Returns: void
**
** Description: Constructor for the device object
**
*****************************************************************************/
CTestDevice::CTestDevice() : m_hConnThread(0)
{
// Create the stop event.
m_hevtStop = CreateEvent (NULL, true, false, NULL);
InitializeCriticalSection(&m_csData);
// TODO: place any constructor code here
}// CTestDevice::CTestDevice
/*****************************************************************************
** Procedure: CTestDevice::~CTestDevice
**
** Arguments: void
**
** Returns: void
**
** Description: Destructor for the device object
**
*****************************************************************************/
CTestDevice::~CTestDevice()
{
// Stop the input thread and wait for it to terminate.
SetEvent (m_hevtStop);
WaitForSingleObject(m_hConnThread, 5000);
CloseHandle(m_hConnThread);
// Close all our synchronization object handles
CloseHandle(m_hevtStop);
DeleteCriticalSection(&m_csData);
// TODO: destroy any allocated memory here
}// CTestDevice::~CTestDevice
/*****************************************************************************
** Procedure: CTestDevice::read
**
** Arguments: 'istm' - Input iostream
**
** Returns: iostream reference
**
** Description: This is called to read information in from the registry.
**
*****************************************************************************/
TStream& CTestDevice::read(TStream& istm)
{
// Always call the base class!
CTSPIDevice::read(istm);
// TODO: Add any additional information which was stored by the
// user-interface component of the TSP.
istm >> m_strTest;
istm >> m_dwTest;
char chBuff[512];
wsprintf(chBuff, "Loaded %s, %d", m_strTest.c_str(), m_dwTest);
MessageBox(NULL, chBuff, "Device::read", MB_OK | MB_SERVICE_NOTIFICATION);
return istm;
}// CTestDevice::read
/*****************************************************************************
** Procedure: CTestDevice::Init
**
** Arguments: 'dwProviderId' - TAPI provider ID
** 'dwBaseLine' - Starting line index from TAPI system
** 'dwBasePhone' - Starting phone index from TAPI system
** 'dwLines' - Number of lines owned by this device
** 'dwPhones' - Number of phones owned by this device
** 'hProvider' - Opaque Provider handle from TAPI
** 'lpfnCompletion' - Completion PROC for any ASYNCH requests.
**
** Returns: true/false whether TAPI should continue loading the device.
**
** Description: This function is called during providerInit to initialize
** each device identified by TAPI (group of lines/phones).
** It is overriden to create threads and other init-time work
** that might fail (and therefore shouldn't be done in the
** constructor).
**
*****************************************************************************/
bool CTestDevice::Init(DWORD dwProviderId, DWORD dwBaseLine, DWORD dwBasePhone,
DWORD dwLines, DWORD dwPhones, HPROVIDER hProvider,
ASYNC_COMPLETION lpfnCompletion)
{
// Add the switch information so others can identify this provider.
SetSwitchInfo(_T("Switch"));
// Turn on the interval timer for this device for once every second
SetIntervalTimer(1000);
// Pass through to the base class and let it initialize the line and phone
// devices. After this call, each of the objects will be available.
// In addition, the providerID information will be filled in.
if (CTSPIDevice::Init (dwProviderId, dwBaseLine, dwBasePhone, dwLines, dwPhones, hProvider, lpfnCompletion))
{
// Create our connection thread which manages the connection to the hardware.
UINT uiThread;
m_hConnThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, MainConnThread, static_cast<void*>(this), 0, &uiThread));
// If the thread failed to create, output an error and tell TAPI to stop
// loading us (fatal initialization error).
if (m_hConnThread == NULL)
{
_TSP_DTRACE(_T("Failed to create input thread\n"), GetLastError());
return false;
}
// Tell TAPI to continue loading our provider.
return true;
}
return false;
}// CTestDevice::Init
/*****************************************************************************
** Procedure: CTestDevice::ConnectionThread
**
** Arguments: void
**
** Returns: Thread return code
**
** Description: This thread manages the communication connection to the hardware.
**
*****************************************************************************/
unsigned CTestDevice::ConnectionThread()
{
// Loop around trying to connect and then receiving data
bool fConnected = false;
while (WaitForSingleObject(m_hevtStop, 0) == WAIT_TIMEOUT)
{
// TODO: Remove this sleep command once the thread pauses waiting
// for events from the hardware. This was iserted so that the generated
// provider doesn't soak up CPU time when tested.
Sleep(1000);
// Keep trying to connect
while (!fConnected)
{
// TODO: Connect to the hardware device
fConnected = true;
}
// TODO: Receive a packet/event from the switch
// TODO: Parse the packet into a TEvent
TEvent* pEvent = NULL;
// Determine the owner of the event
CTSPIConnection* pConnOwner = LocateOwnerFromEvent(pEvent);
// RECOMMENDATION:
// Since the worker thread class is not being used, the wizard has assumed
// that you intend to develop your own thread implementation. It is recommended
// that the dispatch code be performed on a different thread than the one
// receiving the input events from the device.
// Dispatch the request to the owner
if (pConnOwner != NULL)
pConnOwner->ReceiveData(static_cast<LPCVOID>(pEvent));
}
return 0;
}// CTestDevice::ConnectionThread
/*****************************************************************************
** Procedure: CTestDevice::LocateOwnerFromEvent
**
** Arguments: 'pEvent' - Event received from the hardware
**
** Returns: CTSPIConnection which "owns" the event.
**
** Description: This function examines the received event and determines
** which connection object the event belongs to.
**
*****************************************************************************/
CTSPIConnection* CTestDevice::LocateOwnerFromEvent(TEvent* pEvent)
{
CTSPIConnection* pConnOwner = NULL;
// TODO: Examine the event and determine which line or phone object it
// refers to.
//
// Many telephony systems send a "station identifier" or owner with
// each event so that link monitoring software can properly track things.
//
// You can associate an identifier with lines and phones by calling the
// CTSPILineConnection::SetPermanentLineID and CTSPIPhoneConnection::SetPermanentPhoneID
// functions, then they can be found as follows:
DWORD dwIdentifier = 0;
bool fIsLineEvent = false;
if (pConnOwner == NULL && fIsLineEvent)
{
pConnOwner = FindLineConnectionByPermanentID(dwIdentifier);
}
// Another item that comes with many events is the call-id. This uniquely
// identifies the call on the hardware.
DWORD dwCallID = 0;
// If we received a call-id, check for in-switch calls (station-to-station)
// and see if another call object is sharing this call-id. If this is the
// case, determine which call the event refers to.
if (pConnOwner == NULL && dwCallID != 0)
{
const CTSPICallHub* pHub = FindCallHub(dwCallID);
if (pHub != NULL)
{
if (pHub->GetHubCount() > 1)
{
// TODO: Determine which call it refers to
}
else
{
CTSPICallAppearance* pCall = pHub->GetCall(0);
pConnOwner = pCall->GetLineOwner();
}
}
}
return pConnOwner;
}// CTestDevice::LocateOwnerFromEvent
| 32.075 | 124 | 0.598597 | markjulmar |
0458dd8edcb53ef5e536b8cd245044111b4ed444 | 4,837 | cpp | C++ | tools/vsimporter/src/utils/clangoptparser.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | 1 | 2016-02-08T02:29:19.000Z | 2016-02-08T02:29:19.000Z | tools/vsimporter/src/utils/clangoptparser.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | null | null | null | tools/vsimporter/src/utils/clangoptparser.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | null | null | null | //******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "utils.h"
#include "sbassert.h"
#include "tokenizer.h"
#include "clangoptparser.h"
static String reduceLinkerToken(const String& token)
{
static const char* const _prefixes[] = {"-weak", "-reexport", "-lazy", "-upward"};
static StringVec prefixes(_prefixes, _prefixes + sizeof(_prefixes) / sizeof(char*));
StringVec::const_iterator pIt = prefixes.begin();
for (; pIt != prefixes.end(); ++pIt) {
size_t prefixLen = pIt->length();
if (token.length() > prefixLen && strBeginsWith(token, *pIt) &&
(token[prefixLen] == '_' || token[prefixLen] == '-'))
return "-" + token.substr(prefixLen + 1);
}
return token;
}
// "Expand" -Wl and -Xlinker tokens
// This is OK to do since we're interested in a small subset of flags.
// Preserving correctness is not important.
static void replaceWlArgs(const StringVec& inArgs, StringVec& outArgs)
{
for (auto arg : inArgs) {
if (strBeginsWith(arg, "-Wl,")) {
StringVec tokens;
tokenize(arg, tokens, ",", "", "", "", "");
outArgs.insert(outArgs.end(), tokens.begin() + 1, tokens.end());
} else if (arg != "-Xlinker") {
outArgs.push_back(arg);
}
}
}
void processLDFlags(const String& ldFlags, StringVec& libs)
{
// Tokenize flags
StringVec ldFlagTokens;
tokenize(ldFlags, ldFlagTokens, " \t", "", "\"'", "", "", true, false);
// Expand -Wl, and -Xlinker tokens to make parsing easier
StringVec ldFlagsFixed;
replaceWlArgs(ldFlagTokens, ldFlagsFixed);
String savedToken;
for (auto opt : ldFlagsFixed) {
if (savedToken.empty()) {
opt = reduceLinkerToken(opt);
if (opt == "-library" || opt == "-framework") {
savedToken = opt;
} else if (strBeginsWith(opt, "-l")) {
String libName = strEndsWith(opt, ".o") ? opt.substr(2) : "lib" + opt.substr(2) + ".?";
libs.push_back(libName);
} else if (strEndsWith(opt, ".a") || strEndsWith(opt, ".dylib") || strEndsWith(opt, ".o")) {
libs.push_back(opt);
}
} else {
if (savedToken == "-library") {
libs.push_back(opt);
} else if (savedToken == "-framework") {
std::string frameworkName = opt.substr(0, opt.find(',')) + ".framework";
libs.push_back(frameworkName);
}
savedToken.clear();
}
}
}
static void reduceClangTokens(StringVec& otherFlagTokens)
{
String savedToken;
auto tokensIt = otherFlagTokens.begin();
while (tokensIt != otherFlagTokens.end()) {
if (!savedToken.empty()) {
*tokensIt = savedToken + *tokensIt;
savedToken.clear();
} else if (*tokensIt == "-I" || *tokensIt == "-iquote" || *tokensIt == "-F") {
savedToken = *tokensIt;
tokensIt = otherFlagTokens.erase(tokensIt);
continue; // don't increment iterator
}
tokensIt++;
}
}
static String makeRelativePath(const String& path, const String& oldProjDir, const String& newProjDir)
{
String absPath = joinPaths(oldProjDir, path);
String relPath = getRelativePath(newProjDir, absPath);
return winPath(relPath);
}
void processClangFlags(String& clangFlags, const String& absProjDirOld, const String& absProjDirNew)
{
// Tokenize the flags
StringVec clangFlagTokens;
tokenize(clangFlags, clangFlagTokens, " \t", "", "\"'", "", "", true, false);
reduceClangTokens(clangFlagTokens);
auto tokensIt = clangFlagTokens.begin();
while (tokensIt != clangFlagTokens.end()) {
if (strBeginsWith(*tokensIt, "-iquote")) {
String newPath = makeRelativePath(tokensIt->substr(7), absProjDirOld, absProjDirNew);
*tokensIt = "-iquote" + quoteIfNeeded(newPath);
} else if (strBeginsWith(*tokensIt, "-I")) {
String newPath = makeRelativePath(tokensIt->substr(2), absProjDirOld, absProjDirNew);
*tokensIt = "-I" + quoteIfNeeded(newPath);
} else if (strBeginsWith(*tokensIt, "-F")) {
tokensIt = clangFlagTokens.erase(tokensIt);
continue; // don't increment iterator
} else {
*tokensIt = quoteIfNeeded(*tokensIt);
}
tokensIt++;
}
clangFlags = joinStrings(clangFlagTokens, " ");
} | 34.798561 | 102 | 0.63097 | Art52123103 |
045f2913515fbfd8aecd92e1ef4129543c36341c | 6,545 | inl | C++ | include/Rexrn/LocCpp/StringBuilder.inl | Rexrn/LocCpp | db97d8caee5b138fc1392edbef48e7b2b4be30ef | [
"MIT"
] | 2 | 2019-02-19T14:51:13.000Z | 2020-12-27T10:05:37.000Z | include/Rexrn/LocCpp/StringBuilder.inl | Rexrn/LocCpp | db97d8caee5b138fc1392edbef48e7b2b4be30ef | [
"MIT"
] | null | null | null | include/Rexrn/LocCpp/StringBuilder.inl | Rexrn/LocCpp | db97d8caee5b138fc1392edbef48e7b2b4be30ef | [
"MIT"
] | null | null | null | #pragma once
#include <Rexrn/LocCpp/StringBuilder.hpp>
namespace rexrn::loc
{
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
typename StringBuilder<NumSupportedLanguages, CharType>::StringType // return type
StringBuilder<NumSupportedLanguages, CharType>::build(std::uint16_t lang_, std::size_t textIndex_, FormatVariables formatVariables_) const
{
StringType result;
if (_templates.size() > textIndex_)
{
auto const& templ = _templates[textIndex_];
if (!templ.hasTranslation(lang_))
{
if (templ.hasTranslation(_fallbackLanguage))
lang_ = _fallbackLanguage;
else
return StringType{};
}
auto const& formatPoints = templ.formatPoints[lang_];
result = templ.formatBase[lang_].value();
// Optimize for big strings.
result.reserve(4 * 1024);
std::size_t offset = 0;
for (std::size_t i = 0; i < formatPoints.size(); i++)
{
auto const& token = formatPoints[i];
// Try to find the token name inside formatVariables_:
StringType tokenName(token.second);
auto itVarName = formatVariables_.find(tokenName);
// Use either value from formatVariables_ or unformatted "$(TokenName)" if variable name not found:
StringType const& val = (itVarName != formatVariables_.end()) ? itVarName->second : tokenName;
// Insert the value from above:
result.insert(token.first + offset, val);
// Track offset because string gets longer as we insert values to it
offset += val.size();
}
result.shrink_to_fit();
}
return result;
}
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
void StringBuilder<NumSupportedLanguages, CharType>::setTemplate(std::size_t templateIndex_, std::array<StringType, NumSupportedLanguages> const & templateTranslations_)
{
if (_templates.size() <= templateIndex_) {
_templates.resize(templateIndex_ + 1);
}
LocStringTemplate templ;
for (std::size_t i = 0; i < NumSupportedLanguages; ++i)
{
// Initialize std::optional
templ.formatBase[i] = StringType{};
this->prepareSingleTemplate( templateTranslations_[i], templ.formatBase[i].value(), templ.formatPoints[i]) ;
}
_templates[templateIndex_] = std::move(templ);
}
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
void StringBuilder<NumSupportedLanguages, CharType>::setTemplateTranslation(std::size_t templateIndex_, std::uint16_t lang_, StringType translation_)
{
if (_templates.size() <= templateIndex_) {
_templates.resize(templateIndex_ + 1);
}
// Clear previous format points
_templates[templateIndex_].formatPoints[lang_].clear();
// Initialize std::optional
_templates[templateIndex_].formatBase[lang_] = StringType{};
this->prepareSingleTemplate(
translation_,
_templates[templateIndex_].formatBase[lang_].value(),
_templates[templateIndex_].formatPoints[lang_]
);
}
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
void StringBuilder<NumSupportedLanguages, CharType>::removeTemplateTranslation(std::size_t templateIndex_, std::uint16_t lang_)
{
if (templateIndex_ >= _templates.size())
return;
_templates[templateIndex_].formatBase[lang_].reset();
_templates[templateIndex_].formatPoints[lang_].clear();
}
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
void StringBuilder<NumSupportedLanguages, CharType>::removeTranslation(std::uint16_t lang_)
{
for(std::size_t i = 0; i < _templates.size(); ++i)
{
_templates[i].formatBase[lang_].reset();
_templates[i].formatPoints[lang_].clear();
}
}
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
bool StringBuilder<NumSupportedLanguages, CharType>::templateHasTranslation(std::size_t templateIndex_, std::uint16_t lang_) const
{
if (templateIndex_ >= _templates.size())
return false;
return _templates[templateIndex_].hasTranslation(lang_);
}
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
void StringBuilder<NumSupportedLanguages, CharType>::prepareSingleTemplate(StringType translation_, StringType& formatBase_, std::vector<typename LocStringTemplate::FormatPoint> &formatPoints_)
{
std::size_t tokenStart = std::numeric_limits<std::size_t>::max();
// Performance improvement: reserve up to 32 format points in vector.
formatPoints_.reserve(32);
for (std::size_t chIndex = 0; chIndex < translation_.size(); chIndex++)
{
// Detect token beginning:
if (tokenStart == std::numeric_limits<std::size_t>::max())
{
if (translation_[chIndex] == '$' &&
chIndex < translation_.size() - 1 && translation_[chIndex + 1] == '(')
{
tokenStart = chIndex;
}
}
else
{
// Detect token end:
if (translation_[chIndex] == ')')
{
// Store token name and its
CharType const* tokenNameStart = translation_.data() + tokenStart + 2;
std::size_t tokenLength = chIndex - tokenStart;
std::size_t tokenNameLength = tokenLength - 2;
StringViewType tokenName( tokenNameStart, tokenNameLength );
// Check if can do in-place constant replacement.
auto itConstant = _constants.find(tokenName);
if (itConstant != _constants.end())
{
translation_.replace(tokenStart, tokenLength + 1, itConstant->second);
chIndex += itConstant->second.size();
chIndex -= tokenLength + 1;
}
else // This is not constant
{
auto[itFoundTokenName, added] = _tokenNames.insert(StringType(tokenName));
// Create new format point at tokenStart.
formatPoints_.push_back({ tokenStart, *itFoundTokenName });
translation_.replace(tokenStart, tokenLength + 1, "");
chIndex -= tokenLength + 1;
}
// Reset tokenStart to search for next tokens.
tokenStart = std::numeric_limits<std::size_t>::max();
}
}
}
formatPoints_.shrink_to_fit();
formatBase_ = std::move(translation_);
}
//////////////////////////////////////////////////////////////
template <std::uint16_t NumSupportedLanguages, typename CharType>
void StringBuilder<NumSupportedLanguages, CharType>::setConstant(StringType name_, StringType value_)
{
auto[it, added] = _tokenNames.insert( std::move(name_) );
_constants[StringViewType(*it)] = std::move(value_);
}
} | 32.889447 | 193 | 0.676394 | Rexrn |
04615137b3eb762ff5b563dc5b4a1b131ad07f30 | 1,210 | cpp | C++ | benchmark/parallel_benchmark.cpp | shohirose/openmp-examples | ccec9ea6f47d2af2be3cad2bcbb2e064019cfe5d | [
"Unlicense"
] | null | null | null | benchmark/parallel_benchmark.cpp | shohirose/openmp-examples | ccec9ea6f47d2af2be3cad2bcbb2e064019cfe5d | [
"Unlicense"
] | null | null | null | benchmark/parallel_benchmark.cpp | shohirose/openmp-examples | ccec9ea6f47d2af2be3cad2bcbb2e064019cfe5d | [
"Unlicense"
] | null | null | null | #include <benchmark/benchmark.h>
#include "function.hpp"
using namespace shirose;
std::vector<Point>& getPoints() {
static std::vector<Point> points = generatePoints(10'000'000);
return points;
}
template <typename Counter>
void BM_PiCalculation(benchmark::State& state) {
const auto& points = getPoints();
for (auto _ : state) {
const auto numPoints = state.range(0);
const auto pi = calcPi(points.data(), numPoints, Counter{});
benchmark::DoNotOptimize(pi);
}
}
BENCHMARK_TEMPLATE(BM_PiCalculation, SequentialSTLCounter)
->RangeMultiplier(4)
->Range(1 << 10, 1 << 22);
BENCHMARK_TEMPLATE(BM_PiCalculation, OpenMPCounter)
->RangeMultiplier(4)
->Range(1 << 10, 1 << 22);
BENCHMARK_TEMPLATE(BM_PiCalculation, MicrosoftPPLCounter)
->RangeMultiplier(4)
->Range(1 << 10, 1 << 22);
BENCHMARK_TEMPLATE(BM_PiCalculation, ChunkedMicrosoftPPLCounter)
->RangeMultiplier(4)
->Range(1 << 10, 1 << 22);
BENCHMARK_TEMPLATE(BM_PiCalculation, ParallelSTLCounter)
->RangeMultiplier(4)
->Range(1 << 10, 1 << 22);
BENCHMARK_TEMPLATE(BM_PiCalculation, ParallelOrVectorizedSTLCounter)
->RangeMultiplier(4)
->Range(1 << 10, 1 << 22);
BENCHMARK_MAIN(); | 26.304348 | 68 | 0.701653 | shohirose |
04659c9e2da229a731232cabd88a89ea8275136e | 3,931 | cpp | C++ | src/Storages/MergeTree/MergeTreeBlockOutputStream.cpp | ontkey/daisy | b5c9b7b1cc496c1fd45cb5678c273b089d899c63 | [
"Apache-2.0"
] | 5 | 2021-05-14T02:46:44.000Z | 2021-11-23T04:58:20.000Z | src/Storages/MergeTree/MergeTreeBlockOutputStream.cpp | ontkey/daisy | b5c9b7b1cc496c1fd45cb5678c273b089d899c63 | [
"Apache-2.0"
] | 5 | 2021-05-21T06:26:01.000Z | 2021-08-04T04:57:36.000Z | src/Storages/MergeTree/MergeTreeBlockOutputStream.cpp | ontkey/daisy | b5c9b7b1cc496c1fd45cb5678c273b089d899c63 | [
"Apache-2.0"
] | 8 | 2021-05-12T01:38:18.000Z | 2022-02-10T06:08:41.000Z | #include <Storages/MergeTree/MergeTreeBlockOutputStream.h>
#include <Storages/MergeTree/MergeTreeDataPartInMemory.h>
#include <Storages/MergeTree/SequenceInfo.h>
#include <Storages/StorageMergeTree.h>
#include <Interpreters/PartLog.h>
#include <common/logger_useful.h>
namespace DB
{
Block MergeTreeBlockOutputStream::getHeader() const
{
return metadata_snapshot->getSampleBlock();
}
void MergeTreeBlockOutputStream::writePrefix()
{
/// Only check "too many parts" before write,
/// because interrupting long-running INSERT query in the middle is not convenient for users.
storage.delayInsertOrThrowIfNeeded();
}
void MergeTreeBlockOutputStream::write(const Block & block)
{
auto part_blocks = storage.writer.splitBlockIntoParts(block, max_parts_per_block, metadata_snapshot);
/// Daisy : starts
Int32 parts = static_cast<Int32>(part_blocks.size());
Int32 part_index = 0;
for (auto & current_block : part_blocks)
{
Stopwatch watch;
if (ignorePartBlock(parts, part_index))
{
part_index++;
continue;
}
SequenceInfoPtr part_seq;
if (seq_info)
{
part_seq = seq_info->shallowClone(part_index, parts);
}
MergeTreeData::MutableDataPartPtr part = storage.writer.writeTempPart(current_block, metadata_snapshot, part_seq, context);
part_index++;
/// Daisy : ends
/// If optimize_on_insert setting is true, current_block could become empty after merge
/// and we didn't create part.
if (!part)
continue;
/// Part can be deduplicated, so increment counters and add to part log only if it's really added
if (storage.renameTempPartAndAdd(part, &storage.increment, nullptr, storage.getDeduplicationLog()))
{
PartLog::addNewPart(storage.getContext(), part, watch.elapsed());
/// Initiate async merge - it will be done if it's good time for merge and if there are space in 'background_pool'.
storage.background_executor.triggerTask();
}
}
}
/// Daisy : starts
inline bool MergeTreeBlockOutputStream::ignorePartBlock(Int32 parts, Int32 part_index) const
{
if (missing_seq_ranges.empty())
{
return false;
}
const auto & last_seq_range = missing_seq_ranges.back();
assert(parts == last_seq_range.parts);
if (parts != last_seq_range.parts)
{
/// This shall not happen. If it does happen, the table partition algorithm
/// in table definition has been changed. We just persist the blocks in favor
/// of avoiding data loss (there can be data duplication)
LOG_WARNING(
storage.log,
"Recovery phase. Expecting parts={}, but got={} for start_sn={}, end_sn={}. Partition algorithm is probably changed",
parts,
last_seq_range.parts,
last_seq_range.start_sn,
last_seq_range.end_sn);
return false;
}
/// Recovery phase, only persist missing sequence ranges to avoid duplicate data
for (const auto & seq_range : missing_seq_ranges)
{
if (seq_range.part_index == part_index)
{
/// The part block is in missing sequence ranges, persist it
LOG_INFO(
storage.log,
"Recovery phase. Persisting missing parts={} part_index={} for start_sn={}, end_sn={}",
parts,
part_index,
last_seq_range.start_sn,
last_seq_range.end_sn);
return false;
}
}
LOG_INFO(
storage.log,
"Recovery phase. Skipping persisting parts={} part_index={} for start_sn={}, end_sn={} because it was previously persisted",
parts,
part_index,
last_seq_range.start_sn,
last_seq_range.end_sn);
return true;
}
/// Daisy : ends
}
| 30.472868 | 132 | 0.642585 | ontkey |
04677afd725f6008b38309523f910adb7a2da0c3 | 1,178 | hh | C++ | build/ARM/params/L2Cache_Controller.hh | nomorecoke/Multimedia_IP_Cache_management | e49052a2a26dd69c5d2c55687072a4a7a0dd1236 | [
"BSD-3-Clause"
] | 5 | 2019-12-12T16:26:09.000Z | 2022-03-17T03:23:33.000Z | build/ARM/params/L2Cache_Controller.hh | nomorecoke/Multimedia_IP_Cache_management | e49052a2a26dd69c5d2c55687072a4a7a0dd1236 | [
"BSD-3-Clause"
] | null | null | null | build/ARM/params/L2Cache_Controller.hh | nomorecoke/Multimedia_IP_Cache_management | e49052a2a26dd69c5d2c55687072a4a7a0dd1236 | [
"BSD-3-Clause"
] | null | null | null | #ifndef __PARAMS__L2Cache_Controller__
#define __PARAMS__L2Cache_Controller__
class L2Cache_Controller;
#include <cstddef>
#include "params/MessageBuffer.hh"
#include <cstddef>
#include "params/MessageBuffer.hh"
#include <cstddef>
#include "params/MessageBuffer.hh"
#include <cstddef>
#include "params/MessageBuffer.hh"
#include <cstddef>
#include "params/RubyCache.hh"
#include <cstddef>
#include "base/types.hh"
#include <cstddef>
#include "params/MessageBuffer.hh"
#include <cstddef>
#include "params/MessageBuffer.hh"
#include <cstddef>
#include "base/types.hh"
#include <cstddef>
#include "params/MessageBuffer.hh"
#include "params/RubyController.hh"
struct L2Cache_ControllerParams
: public RubyControllerParams
{
L2Cache_Controller * create();
MessageBuffer * GlobalRequestFromL2Cache;
MessageBuffer * GlobalRequestToL2Cache;
MessageBuffer * L1RequestFromL2Cache;
MessageBuffer * L1RequestToL2Cache;
CacheMemory * L2cache;
Cycles request_latency;
MessageBuffer * responseFromL2Cache;
MessageBuffer * responseToL2Cache;
Cycles response_latency;
MessageBuffer * triggerQueue;
};
#endif // __PARAMS__L2Cache_Controller__
| 25.608696 | 45 | 0.780136 | nomorecoke |
046940751ecb2b3f0ff0513e1ec5ba4250939af4 | 5,839 | cpp | C++ | src/tests/rt_base/test_base_meta_data.cpp | wizardst/Rockit | 8c6c5e59b6069735e95e34cca2607b9b6541b520 | [
"Apache-2.0"
] | null | null | null | src/tests/rt_base/test_base_meta_data.cpp | wizardst/Rockit | 8c6c5e59b6069735e95e34cca2607b9b6541b520 | [
"Apache-2.0"
] | null | null | null | src/tests/rt_base/test_base_meta_data.cpp | wizardst/Rockit | 8c6c5e59b6069735e95e34cca2607b9b6541b520 | [
"Apache-2.0"
] | 2 | 2022-01-04T20:29:44.000Z | 2022-01-04T20:39:31.000Z | /*
* Copyright 2018 Rockchip Electronics Co. LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* author: rimon.xu@rock-chips.com
* date: 20181031
*/
#include <string.h>
#include "rt_base_tests.h" // NOLINT
#include "rt_metadata.h" // NOLINT
enum {
kKeyTestInt32 = MKTAG('t', 'i', '3', '2'),
kKeyTestInt64 = MKTAG('t', 'i', '6', '4'),
kKeyTestString = MKTAG('t', 's', 't', 'r'),
kKeyTestFloat = MKTAG('t', 'f', 'l', 't'),
kKeyTestPtr = MKTAG('t', 'p', 't', 'r'),
kKeyTestNone = MKTAG('t', 'n', 'o', 'e'),
};
enum {
kKeyCodecBitrates = MKTAG('c', 'b', 'i', 't'), // INT64
kKeyCodecCLayouts = MKTAG('a', 'c', 'l', 'a'), // INT64
kKeyCodecChannels = MKTAG('a', 'c', 'h', 'a'),
kKeyCodecSampleRate = MKTAG('a', 's', 'r', 'a'),
kKeyCodecPointer = MKTAG('a', 'p', 't', 'r'),
};
struct TrackInfo {
INT64 mChannelLayout;
INT32 mChannels;
INT64 mBitrate;
INT32 mSampleRate;
void* mThis;
};
RT_RET unit_test_metadata_more(INT32 index, INT32 total_index) {
struct TrackInfo track_info;
RtMetaData* metadata = new RtMetaData();
rt_memset(&track_info, 0, sizeof(struct TrackInfo));
track_info.mBitrate = 20000000;
track_info.mChannelLayout = 2000;
track_info.mChannels = 2;
track_info.mSampleRate = 44100;
track_info.mThis = &track_info;
metadata->setInt64(kKeyCodecCLayouts, track_info.mChannelLayout);
metadata->setInt64(kKeyCodecBitrates, track_info.mBitrate);
metadata->setInt32(kKeyCodecChannels, track_info.mChannels);
metadata->setInt32(kKeyCodecSampleRate, track_info.mSampleRate);
metadata->setPointer(kKeyCodecPointer, track_info.mThis);
metadata->findInt64(kKeyCodecCLayouts, &(track_info.mChannelLayout));
metadata->findInt64(kKeyCodecBitrates, &(track_info.mBitrate));
metadata->findInt32(kKeyCodecChannels, &(track_info.mChannels));
metadata->findInt32(kKeyCodecSampleRate, &(track_info.mSampleRate));
metadata->findPointer(kKeyCodecPointer, &(track_info.mThis));
struct TrackInfo* binder = (struct TrackInfo*)(track_info.mThis);
RT_LOGD("bitrate=%lld, layouts=%lld, channels=%d, sample_rate=%d",
binder->mBitrate, binder->mChannelLayout,
binder->mChannels, binder->mSampleRate);
delete metadata;
metadata = NULL;
return RT_OK;
}
RT_RET unit_test_metadata(INT32 index, INT32 total_index) {
RtMetaData *metadata = NULL;
metadata = new RtMetaData();
{
/********* base test *************/
INT32 test1;
INT64 test2;
float test3;
const char *test4;
void *test5;
metadata->setInt32(kKeyTestInt32, 123);
metadata->setInt64(kKeyTestInt64, 123456ll);
metadata->setCString(kKeyTestString, "string");
metadata->setFloat(kKeyTestFloat, 1.23f);
metadata->setPointer(kKeyTestPtr, metadata);
CHECK_EQ(metadata->findInt32(kKeyTestInt32, &test1), RT_TRUE);
CHECK_EQ(metadata->findInt64(kKeyTestInt64, &test2), RT_TRUE);
CHECK_EQ(metadata->findFloat(kKeyTestFloat, &test3), RT_TRUE);
CHECK_EQ(metadata->findCString(kKeyTestString, &test4), RT_TRUE);
CHECK_EQ(metadata->findPointer(kKeyTestPtr, &test5), RT_TRUE);
CHECK_EQ(test1, 123);
CHECK_EQ(test2, 123456ll);
CHECK_EQ(test3, 1.23f);
CHECK_EQ(strncmp(test4, "string", 5), 0);
CHECK_EQ(test5, metadata);
/********** end ***************/
}
{
/********** return test ********/
INT32 test1 = 0;
CHECK_EQ(metadata->findInt32(kKeyTestNone, &test1), RT_FALSE);
CHECK_EQ(metadata->hasData(kKeyTestNone), RT_FALSE);
CHECK_EQ(metadata->setInt32(kKeyTestNone, 1), RT_FALSE);
CHECK_EQ(metadata->hasData(kKeyTestNone), RT_TRUE);
CHECK_EQ(metadata->setInt32(kKeyTestNone, 2), RT_TRUE);
CHECK_EQ(metadata->setInt32(kKeyTestNone, 3), RT_TRUE);
CHECK_EQ(metadata->setInt32(kKeyTestNone, 4), RT_TRUE);
CHECK_EQ(metadata->hasData(kKeyTestNone), RT_TRUE);
CHECK_EQ(metadata->findInt32(kKeyTestNone, &test1), RT_TRUE);
CHECK_EQ(test1, 4);
/********** end ***************/
}
{
/********* remove test ********/
INT32 test1 = 0;
CHECK_EQ(metadata->remove(kKeyTestNone), RT_TRUE);
CHECK_EQ(metadata->findInt32(kKeyTestNone, &test1), RT_FALSE);
/********** end ***************/
}
{
/********* clear test *********/
metadata->clear();
CHECK_EQ(metadata->hasData(kKeyTestInt32), RT_FALSE);
CHECK_EQ(metadata->hasData(kKeyTestInt64), RT_FALSE);
CHECK_EQ(metadata->hasData(kKeyTestFloat), RT_FALSE);
CHECK_EQ(metadata->hasData(kKeyTestString), RT_FALSE);
CHECK_EQ(metadata->hasData(kKeyTestPtr), RT_FALSE);
CHECK_EQ(metadata->hasData(kKeyTestNone), RT_FALSE);
/********** end ***************/
}
delete metadata;
metadata = NULL;
return RT_OK;
__FAILED:
delete metadata;
metadata = NULL;
return RT_ERR_UNKNOWN;
}
| 36.49375 | 76 | 0.609522 | wizardst |
046a17c4df78713e47c16ea2981e5a66642dd18d | 2,357 | cpp | C++ | tests/util.cpp | jnalanko/cobs | 7d1c031c4abec1f46a035c5186ae0aacec0aba55 | [
"MIT"
] | 69 | 2019-04-19T05:51:41.000Z | 2022-01-28T20:38:56.000Z | tests/util.cpp | jnalanko/cobs | 7d1c031c4abec1f46a035c5186ae0aacec0aba55 | [
"MIT"
] | 19 | 2019-05-24T11:05:27.000Z | 2021-11-23T14:55:03.000Z | tests/util.cpp | iqbal-lab-org/cobs | f4e7200d8076929f49c6035062261d90c57e4619 | [
"MIT"
] | 12 | 2019-03-22T11:39:22.000Z | 2021-11-23T20:32:34.000Z | /*******************************************************************************
* tests/util.cpp
*
* Copyright (c) 2018 Florian Gauger
* Copyright (c) 2018 Timo Bingmann
*
* All rights reserved. Published under the MIT License in the LICENSE file.
******************************************************************************/
#include <cobs/util/misc.hpp>
#include <cobs/util/query.hpp>
#include <gtest/gtest.h>
#include <stdint.h>
void is_aligned(void* ptr, size_t alignment) {
ASSERT_EQ((uintptr_t)ptr % alignment, 0);
}
TEST(util, allocate_aligned) {
auto ptr1 = cobs::allocate_aligned<uint8_t>(10, cobs::get_page_size());
is_aligned(ptr1, cobs::get_page_size());
auto ptr2 = cobs::allocate_aligned<uint16_t>(1337, 16);
is_aligned(ptr2, 16);
cobs::deallocate_aligned(ptr1);
cobs::deallocate_aligned(ptr2);
}
void test_kmer(const char* kmer_data,
const char* kmer_correct, bool is_good) {
char kmer_buffer[31];
bool good = cobs::canonicalize_kmer(kmer_data, kmer_buffer, 31);
die_unequal(std::string(kmer_buffer, 31),
std::string(kmer_correct, 31));
die_unequal(good, is_good);
}
TEST(util, kmer_canonicalize) {
// one already canonical one
test_kmer("AGGAAAGTCTTTTACGCTGGGGTAAGAGTGA",
"AGGAAAGTCTTTTACGCTGGGGTAAGAGTGA", true);
// two k-mers which need to be flipped
test_kmer("TGGAAAGTCTTTTACGCTGGGGTAAGAGTGA",
"TCACTCTTACCCCAGCGTAAAAGACTTTCCA", true);
test_kmer("TTTTTTGTCTTTTACGCTGGGGTTTAAAAAA",
"TTTTTTAAACCCCAGCGTAAAAGACAAAAAA", true);
// special case, lexicographically smaller until center
test_kmer("AAAAAAAAAAAAAAAATTTTTTTTTTTTTTT",
"AAAAAAAAAAAAAAAATTTTTTTTTTTTTTT", true);
// one kmer already canonical but containing invalid letters
test_kmer("AGGAAAGTCTTTTACGCTGGGXXXAGAGTGA",
"AGGAAAGTCTTTTACGCTGGG\0\0\0AGAGTGA", false);
// one k-mer needing flipping containing invalid letters
test_kmer("TGGAAAGTCTTTTACGCTGGGXXXAGAGTGA",
"TCACTCT\0\0\0CCCAGCGTAAAAGACTTTCCA", false);
// one kmer containing the invalid letter at the center
test_kmer("AAAAAAAAAAAAAAAXTTTTTTTTTTTTTTT",
"AAAAAAAAAAAAAAA\0TTTTTTTTTTTTTTT", false);
}
/******************************************************************************/
| 37.412698 | 80 | 0.630462 | jnalanko |
046b1a0167c7cbc0c617c99be661bd3f11b19834 | 29,623 | cpp | C++ | qt-ticket/src/paywidget.cpp | waitWindComing/QT | c8401679b7265785ec8c7e97eea7e1e37631f37d | [
"Apache-2.0"
] | null | null | null | qt-ticket/src/paywidget.cpp | waitWindComing/QT | c8401679b7265785ec8c7e97eea7e1e37631f37d | [
"Apache-2.0"
] | null | null | null | qt-ticket/src/paywidget.cpp | waitWindComing/QT | c8401679b7265785ec8c7e97eea7e1e37631f37d | [
"Apache-2.0"
] | null | null | null | #include "paywidget.h"
#include "stepindicator.h"
#include "tipswidget.h"
#include "dueeditor.h"
#include "reduceeditor.h"
#include "neteditor.h"
#include "confirmcodewidget.h"
#include "issuedticketdlg.h"
#include "issueeditor.h"
#include "companycustomer.h"
#include "customer.h"
#include "consume.h"
#include "ticket.h"
#include "userule.h"
#include "issuerule.h"
#include "utils.h"
#include <QToolBar>
#include <QMessageBox>
#include <QMap>
#include <QJson/Serializer>
#include <QJson/Parser>
#include <qDebug>
PayWidget::PayWidget(qulonglong &managerId, QString &managerName, int &level, QString &token, qulonglong &companyId, QString &companyName, double &latitude, double &longitude, QWidget *parent) :
QWidget(parent),
_managerId(managerId),
_managerName(managerName),
_level(level),
_token(token),
_companyId(companyId),
_companyName(companyName),
_latitude(latitude),
_longitude(longitude),
_skipStepTwo(false),
_stepIndicator(NULL),
_netEditor(NULL),
_issueEditor(NULL),
_customer(NULL),
_consume(NULL)
{
QString title = trUtf8("消费者本次消费:");
QList<QString> tips;
tips << trUtf8("输入消费者的手机号码;");
tips << trUtf8("本次的消费额度(应付);");
tips << trUtf8("若消费者为新用户,系统将会自动替该用户注册,并将注册信息通过短信发送到用户到手机;");
_tipsWidget = new TipsWidget(title, tips, this);
_tipsWidget->setGeometry(0, 0, 250, 540);
createStepIndicatorWithStepTwo();
_infoBar = new QToolBar(this);
_infoBar->setLayoutDirection(Qt::LeftToRight);
_payInfo = new QLabel(this);
_infoBar->addWidget(_payInfo);
_buttonBar = new QToolBar(this);
_buttonBar->setLayoutDirection(Qt::RightToLeft);
_infoBar->setGeometry(250, 540 - 54, 500, 54);
_buttonBar->setGeometry(250 + 500, 540 - 54, 1024 - 250 - 500, 54);
_buttonBar->setIconSize(QSize(52, 52));
initActionsForFirstStep();
_dueEditor = new DueEditor(_managerId, _managerName, _level, _token, _companyId, _companyName, _latitude, _longitude, this);
_dueEditor->setGeometry(250, 0, 1024 - 250, 540 - 54);
connect(_dueEditor, SIGNAL(editingFinished()), this, SLOT(handleDueEditingFinshed()));
connect(_dueEditor, SIGNAL(editingUnFinished()), this, SLOT(handleDueEditingUnFinshed()));
_reduceEditor = new ReduceEditor(_managerId, _managerName, _level, _token, _companyId, _companyName, _latitude, _longitude, _tickets, _useRules, this);
_reduceEditor->setGeometry(250, 0, 1024 - 250, 540 - 54);
requestUseRules();
requestIssueRules();
goStepOne();
}
PayWidget::~PayWidget()
{
if (_customer) delete _customer;
if (_consume) delete _consume;
for (QList<Ticket *>::iterator i = _tickets.begin(); i!= _tickets.end(); ++i) {
delete *i;
}
for (QList<UseRule *>::iterator i = _useRules.begin(); i!= _useRules.end(); ++i) {
delete *i;
}
if (_stepIndicator != NULL) delete _stepIndicator;
}
void PayWidget::handleDueEditingFinshed()
{
_nextAction->setEnabled(true);
_nextAction->disconnect();
connect(_nextAction, SIGNAL(triggered()), this, SLOT(requestCustomer()));
}
void PayWidget::handleDueEditingUnFinshed()
{
_nextAction->setEnabled(false);
_nextAction->disconnect();
}
void PayWidget::goStepOne()
{
qDebug() << "goStepOne()";
if (sender() == _previousAction) {
_nextAction->setEnabled(true);
_nextAction->disconnect();
connect(_nextAction, SIGNAL(triggered()), this, SLOT(requestCustomer()));
} else {
if (_customer) {
delete _customer;
_customer = NULL;
}
if (_consume) {
delete _consume;
_consume = NULL;
}
for (QList<Ticket *>::iterator i = _tickets.begin(); i!= _tickets.end(); ++i) {
delete *i;
}
_tickets.clear();
_dueEditor->clear();
_nextAction->setEnabled(false);
}
_previousAction->setEnabled(false);
if (_netEditor != NULL) {
delete _netEditor;
_netEditor = NULL;
}
if (_issueEditor != NULL) {
delete _issueEditor;
_issueEditor = NULL;
}
_reduceEditor->hide();
_dueEditor->show();
QString currentStep = trUtf8("应付");
_stepIndicator->setCurrentStep(currentStep);
}
void PayWidget::goStepTwo()
{
qDebug() << "goStepTwo()";
if (sender() == _previousAction) {
delete _netEditor;
_netEditor = NULL;
}
_nextAction->setEnabled(true);
_nextAction->disconnect();
connect(_nextAction, SIGNAL(triggered()), this, SLOT(goStepThree()));
_previousAction->setEnabled(true);
_previousAction->disconnect();
connect(_previousAction, SIGNAL(triggered()), this, SLOT(goStepOne()));
_dueEditor->hide();
_reduceEditor->show();
QString currentStep = trUtf8("优惠");
_stepIndicator->setCurrentStep(currentStep);
QString title = trUtf8("选择消费者可用到优惠券:");
QList<QString> tips;
tips << trUtf8("优惠券有折扣券和代金券两种,这两种优惠券不能混合同时使用");
tips << trUtf8("折扣券只能使用一张");
tips << trUtf8("代金券可以同时使用多张");
delete _tipsWidget;
_tipsWidget = new TipsWidget(title, tips, this);
_tipsWidget->setGeometry(0, 0, 250, 540);
_tipsWidget->show();
}
void PayWidget::goStepThree()
{
qDebug() << "goStepThree()";
_nextAction->setEnabled(true);
_nextAction->disconnect();
connect(_nextAction, SIGNAL(triggered()), this, SLOT(goStepFour()));
_previousAction->setEnabled(true);
_previousAction->disconnect();
if (_skipStepTwo) {
connect(_previousAction, SIGNAL(triggered()), this, SLOT(goStepOne()));
} else {
connect(_previousAction, SIGNAL(triggered()), this, SLOT(goStepTwo()));
}
_dueEditor->hide();
_reduceEditor->hide();
QList<Ticket *> selectedTickets = getSelectedTickets();
QList<UseRule *> candidateUseRules = getCandidateUseRules();
_netEditor = new NetEditor(_managerId, _managerName, _level, _token, _companyId, _companyName, _latitude, _longitude, selectedTickets, candidateUseRules, _dueEditor->getDue(), this);
connect(_netEditor, SIGNAL(summaryUpdated(QString &)), this, SLOT(handleSummaryUpdated(QString &)));
_netEditor->setGeometry(250, 0, 1024 - 250, 540 - 54);
_netEditor->show();
QString currentStep = trUtf8("实付");
_stepIndicator->setCurrentStep(currentStep);
QString title = trUtf8("计算消费者优惠额度和实付额度:");
QList<QString> tips;
tips << trUtf8("若定义了多条使用规则,则系统会列出这些使用规则,需要选择一条使用规则");
tips << trUtf8("系统会根据选择到使用规则计算当前到优惠额度");
tips << trUtf8("若是代金券,系统会更新代金券抵扣后的剩余可抵扣额度");
tips << trUtf8("若是一次性折扣券,本次使用完后将不能再次使用");
tips << trUtf8("使用优惠券需要用户提供3为确认码,否则不能使用。用户的3位确认码在用户首次注册时会通过短信发送到用户的手机上,也可以通过APP查看");
delete _tipsWidget;
_tipsWidget = new TipsWidget(title, tips, this);
_tipsWidget->setGeometry(0, 0, 250, 540);
_tipsWidget->show();
}
void PayWidget::goStepFour()
{
qDebug() << "goStepFour()";
QString title = trUtf8("发优惠券:");
QList<QString> tips;
tips << trUtf8("系统会列出发放规则,需要选择一条发放规则");
tips << trUtf8("系统会根据当前用户实付金额和所选的发放规则计算出发给用户的优惠券优惠券");
tips << trUtf8("用户可以通过APP查看收到的优惠券");
delete _tipsWidget;
_tipsWidget = new TipsWidget(title, tips, this);
_tipsWidget->setGeometry(0, 0, 250, 540);
_tipsWidget->show();
_netPaid = _netEditor->getNet();
if (_customer == NULL) {
postCustomer();
} else {
QList<Ticket *> selectedTickets = getSelectedTickets();
if (!selectedTickets.isEmpty()) {
_nextAction->setEnabled(false);
_previousAction->setEnabled(false);
_netEditor->setEnabled(false);
_confirmCodeWidget = new ConfirmCodeWidget(_managerId, _token, _customer->getCustomerId(), this);
_confirmCodeWidget->setGeometry(780, 150, 240, 400);
connect(_confirmCodeWidget, SIGNAL(pass()), this, SLOT(handleConfirmCodePass()));
connect(_confirmCodeWidget, SIGNAL(skip()), this, SLOT(handleConfirmCodeSkip()));
_confirmCodeWidget->show();
_confirmCodeWidget->focus();
} else {
postConsume();
}
}
}
void PayWidget::handleConfirmCodePass()
{
qDebug() << "PayWidget::handleConfirmCodePass()";
postConsume();
_confirmCodeWidget->close();
_confirmCodeWidget->deleteLater();
}
void PayWidget::handleConfirmCodeSkip()
{
qDebug() << "PayWidget::handleConfirmCodeSkip()";
_netPaid = _dueEditor->getDue();
postConsume();
_confirmCodeWidget->close();
_confirmCodeWidget->deleteLater();
}
void PayWidget::requestUseRules()
{
qDebug() << "PayWidget::requestUseRules()";
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/useRules")).arg(_managerId)));
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
_useRulesReply = _qnam.get(request);
connect(_useRulesReply, SIGNAL(finished()), this, SLOT(handleGetUseRulesFinished()));
}
void PayWidget::handleGetUseRulesFinished()
{
qDebug() << "PayWidget::handleGetUseRulesFinished()";
if (_useRulesReply != NULL) {
_useRulesReply->close();
_useRulesReply->deleteLater();
if (_useRulesReply->error() == QNetworkReply::NoError) {
QByteArray json = _useRulesReply->readAll();
QJson::Parser parser;
bool ok;
QVariantList rules = parser.parse (json, &ok).toList();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
for (QVariantList::iterator i = rules.begin(); i != rules.end(); ++i) {
_useRules.append(UseRule::fromJson(*i));
}
} else if (_useRulesReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
}
}
}
void PayWidget::requestIssueRules()
{
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/issueRules")).arg(_managerId)));
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
_issueRulesReply = _qnam.get(request);
connect(_issueRulesReply, SIGNAL(finished()), this, SLOT(handleGetIssueRulesFinished()));
}
void PayWidget::handleGetIssueRulesFinished() {
if (_issueRulesReply != NULL) {
_issueRulesReply->close();
_issueRulesReply->deleteLater();
if (_issueRulesReply->error() == QNetworkReply::NoError) {
QByteArray json = _issueRulesReply->readAll();
QJson::Parser parser;
bool ok;
QVariantList rules = parser.parse (json, &ok).toList();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
for (QVariantList::iterator it = rules.begin(); it != rules.end(); ++it) {
_issueRules.append(IssueRule::fromJson(*it));
}
} else if (_issueRulesReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
}
}
}
void PayWidget::requestCustomer()
{
qDebug() << "PayWidget::requestCustomer()";
_nextAction->setEnabled(false);
_previousAction->setEnabled(false);
if (_customer != NULL) {
delete _customer;
_customer = NULL;
}
for (QList<Ticket *>::iterator i = _tickets.begin(); i!= _tickets.end(); ++i) {
delete *i;
}
_tickets.clear();
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/customers?customerName=%2")).arg(_managerId).arg(_dueEditor->getCustomer())));
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
_getCustomerReply = _qnam.get(request);
connect(_getCustomerReply, SIGNAL(finished()), this, SLOT(handleGetCustomerFinished()));
}
void PayWidget::handleGetCustomerFinished()
{
qDebug() << "PayWidget::handleGetCustomerFinished()";
_nextAction->setEnabled(true);
_previousAction->setEnabled(true);
if (_getCustomerReply != NULL) {
_getCustomerReply->close();
_getCustomerReply->deleteLater();
if (_getCustomerReply->error() == QNetworkReply::NoError) {
QByteArray json = _getCustomerReply->readAll();
QJson::Parser parser;
bool ok;
QVariantList customers = parser.parse (json, &ok).toList();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
for (QVariantList::iterator i = customers.begin(); i != customers.end(); ++i) {
_customer = Customer::fromJson(*i);
break; // we will have only one
}
if (_customer != NULL) {
requestTickets();
} else {
_skipStepTwo = true;
createStepIndicatorWithoutStepTwo();
goStepThree();
}
} else if (_getCustomerReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
}
}
}
void PayWidget::requestTickets()
{
qDebug() << "PayWidget::requestTickets()";
for (QList<Ticket *>::iterator i = _tickets.begin(); i!= _tickets.end(); ++i) {
delete *i;
}
_tickets.clear();
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/customers/%2/tickets?state=valid&validCompany=me")).arg(_managerId).arg(_customer->getCustomerId())));
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
_ticketsReply = _qnam.get(request);
connect(_ticketsReply, SIGNAL(finished()), this, SLOT(handleGetTicketsFinished()));
}
void PayWidget::handleGetTicketsFinished()
{
qDebug() << "PayWidget::handleGetTicketsFinished()";
if (_ticketsReply != NULL) {
_ticketsReply->close();
_ticketsReply->deleteLater();
if (_ticketsReply->error() == QNetworkReply::NoError) {
QByteArray json = _ticketsReply->readAll();
QJson::Parser parser;
bool ok;
QVariantList tickets = parser.parse (json, &ok).toList();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
for (QVariantList::iterator i = tickets.begin(); i != tickets.end(); ++i) {
Ticket *ticket = Ticket::fromJson(*i);
_tickets.append(ticket);
}
} else if (_ticketsReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
} else if (_ticketsReply->error() == QNetworkReply::ContentOperationNotPermittedError) {
qDebug() << "low balance!";
QMessageBox::warning(this, trUtf8("余额不足"), trUtf8("因余额不足而导致操作失败,请充值!"));
}
}
if (_tickets.size() == 0) {
_skipStepTwo = true;
createStepIndicatorWithoutStepTwo();
goStepThree();
} else {
_skipStepTwo = false;
createStepIndicatorWithStepTwo();
goStepTwo();
}
}
void PayWidget::createStepIndicatorWithStepTwo()
{
if (_stepIndicator != NULL) delete _stepIndicator;
QList<QString> steps;
steps << trUtf8("应付") << trUtf8("优惠") << trUtf8("实付") << trUtf8("发优惠券");
QString currentStep = trUtf8("应付");
_stepIndicator = new StepIndicator(steps, currentStep, this);
_stepIndicator->setGeometry(0, 540, 1024, 60);
_stepIndicator->show();
}
void PayWidget::createStepIndicatorWithoutStepTwo()
{
if (_stepIndicator != NULL) delete _stepIndicator;
QList<QString> steps;
steps << trUtf8("应付") << trUtf8("实付") << trUtf8("发优惠券");
QString currentStep = trUtf8("应付");
_stepIndicator = new StepIndicator(steps, currentStep, this);
_stepIndicator->setGeometry(0, 540, 1024, 60);
_stepIndicator->show();
}
QList<Ticket *> PayWidget::getSelectedTickets()
{
QList<Ticket *> selectedTickets;
for (QList<Ticket *>::iterator i = _tickets.begin(); i != _tickets.end(); ++i) {
if ((*i)->getCheckState() == Qt::Checked) {
selectedTickets.append(*i);
}
}
return selectedTickets;
}
QList<UseRule *> PayWidget::getCandidateUseRules()
{
QList<UseRule *> candidateUseRules;
Ticket *selectedTicket = NULL;
for (QList<Ticket *>::iterator i = _tickets.begin(); i != _tickets.end(); ++i) {
if ((*i)->getCheckState() == Qt::Checked) {
selectedTicket = *i;
break;
}
}
if (selectedTicket != NULL && Ticket::Groupon != selectedTicket->getType()) {
for (QList<UseRule *>::iterator i = _useRules.begin(); i != _useRules.end(); ++i) {
QList<Company> issuedByCompanies = (*i)->getIssuedByCompanies();
if (issuedByCompanies.size() == 0) { // 自身
if (selectedTicket->getCompany().getCompanyId() == _companyId
&& ((Ticket::Discount == selectedTicket->getType() && UseRule::Discount == (*i)->getType())
|| (Ticket::Deduction == selectedTicket->getType() && UseRule::Deduction == (*i)->getType()))) {
candidateUseRules.append(*i);
}
} else {
if (issuedByCompanies.contains(selectedTicket->getCompany())
&& ((Ticket::Discount == selectedTicket->getType() && UseRule::Discount == (*i)->getType())
|| (Ticket::Deduction == selectedTicket->getType() && UseRule::Deduction == (*i)->getType()))) {
candidateUseRules.append(*i);
}
}
}
}
for (QList<UseRule *>::iterator i = candidateUseRules.begin(); i != candidateUseRules.end(); ++i) {
(*i)->setCheckState(Qt::Unchecked);
}
if (!candidateUseRules.isEmpty()) {
candidateUseRules.first()->setCheckState(Qt::Checked);
}
return candidateUseRules;
}
void PayWidget::initActionsForFirstStep()
{
_infoBar->setGeometry(250, 540 - 54, 500, 54);
_buttonBar->setGeometry(250 + 500, 540 - 54, 1024 - 250 - 500, 54);
_buttonBar->setIconSize(QSize(50, 50));
_buttonBar->clear();
_nextAction = _buttonBar->addAction(QIcon(":/ticket/next.png"), trUtf8("下一步"));
_buttonBar->addSeparator();
_previousAction = _buttonBar->addAction(QIcon(":/ticket/previous.png"), trUtf8("上一步"));
_payInfo->clear();
}
void PayWidget::initActionsForLastStep()
{
_infoBar->setGeometry(250, 540 - 54, 300, 54);
_buttonBar->setGeometry(250 + 300, 540 - 54, 1024 - 250 - 300, 54);
_buttonBar->setIconSize(QSize(133, 28));
_buttonBar->clear();
_issueAction = _buttonBar->addAction(QIcon(":/ticket/issue.png"), trUtf8("发券"));
_buttonBar->addSeparator();
_cancelAction = _buttonBar->addAction(QIcon(":/ticket/cancel.png"), trUtf8("取消发券"));
}
void PayWidget::cancel()
{
initActionsForFirstStep();
goStepOne();
}
void PayWidget::postTicket()
{
qDebug() << "PayWidget::postTicket";
IssueRule *selectedRule = _issueEditor->getSelectedIssueRule();
if (selectedRule == NULL) {
initActionsForFirstStep();
goStepOne();
return;
}
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/companyCustomers/%2/tickets")).arg(_managerId).arg(_consume->getCompanyCustomer()->getCompanyCustomerId())));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
QVariantMap variant;
variant.insert("consumeId", _consume->getConsumeId());
variant.insert("ruleId", selectedRule->getRuleId());
bool ok;
QJson::Serializer serializer;
QByteArray data = serializer.serialize(variant, &ok);
Q_ASSERT(ok);
_postTicketReply = _qnam.post(request, data);
connect(_postTicketReply, SIGNAL(finished()), this, SLOT(handlePostTicketFinished()));
}
void PayWidget::handlePostTicketFinished()
{
qDebug() << "PayWidget::handlePostTicketFinished()";
if (_postTicketReply != NULL) {
_postTicketReply->close();
_postTicketReply->deleteLater();
if (_postTicketReply->error() == QNetworkReply::NoError) {
QByteArray json = _postTicketReply->readAll();
QJson::Parser parser;
bool ok;
QVariantMap ticket = parser.parse (json, &ok).toMap();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
Ticket *issueTicket = Ticket::fromJson(ticket);
if (issueTicket != NULL) {
IssuedTicketDlg dlg(issueTicket, this);
dlg.exec();
delete issueTicket;
}
initActionsForFirstStep();
goStepOne();
} else if (_postTicketReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
}
}
}
void PayWidget::postCustomer()
{
qDebug() << "PayWidget::postCustomer";
_nextAction->setEnabled(false);
_previousAction->setEnabled(false);
if (_customer != NULL) delete _customer;
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/customers")).arg(_managerId)));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
QVariantMap variant;
variant.insert("name", _dueEditor->getCustomer());
bool ok;
QJson::Serializer serializer;
QByteArray data = serializer.serialize(variant, &ok);
Q_ASSERT(ok);
_postCustomerReply = _qnam.post(request, data);
connect(_postCustomerReply, SIGNAL(finished()), this, SLOT(handlePostCustomerFinished()));
}
void PayWidget::handlePostCustomerFinished()
{
qDebug() << "PayWidget::handlePostCustomerFinished()";
_nextAction->setEnabled(true);
_previousAction->setEnabled(true);
if (_postCustomerReply != NULL) {
_postCustomerReply->close();
_postCustomerReply->deleteLater();
if (_postCustomerReply->error() == QNetworkReply::NoError) {
QByteArray json = _postCustomerReply->readAll();
QJson::Parser parser;
bool ok;
QVariantMap customer = parser.parse (json, &ok).toMap();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
_customer = Customer::fromJson(customer);
postConsume();
} else if (_postCustomerReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
}
}
}
void PayWidget::postConsume()
{
qDebug() << "PayWidget::postConsume";
_nextAction->setEnabled(false);
_previousAction->setEnabled(false);
if (_consume != NULL) delete _consume;
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/customers/%2/consumes")).arg(_managerId).arg(_customer->getCustomerId())));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
QVariantMap variant;
variant.insert("amount", _dueEditor->getDue());
variant.insert("netPaid", _netPaid);
QMap<CompanyProduct, int> selectedProducts = _dueEditor->getSelectedCompanyProducts();
if (selectedProducts.size() != 0) {
QVariantList companyProducts;
QMapIterator<CompanyProduct, int> i(selectedProducts);
while (i.hasNext()) {
i.next();
QVariantMap companyProduct;
companyProduct.insert("companyProductId", i.key().getCompanyProductId());
companyProduct.insert("quantity", i.value());
companyProducts.append(companyProduct);
}
variant.insert("companyProducts", companyProducts);
}
bool ok;
QJson::Serializer serializer;
QByteArray data = serializer.serialize(variant, &ok);
Q_ASSERT(ok);
_postConsumeReply = _qnam.post(request, data);
connect(_postConsumeReply, SIGNAL(finished()), this, SLOT(handlePostConsumeFinished()));
}
void PayWidget::handlePostConsumeFinished()
{
qDebug() << "PayWidget::handlePostConsumeFinished()";
_nextAction->setEnabled(true);
_previousAction->setEnabled(true);
if (_postConsumeReply != NULL) {
_postConsumeReply->close();
_postConsumeReply->deleteLater();
if (_postConsumeReply->error() == QNetworkReply::NoError) {
QByteArray json = _postConsumeReply->readAll();
QJson::Parser parser;
bool ok;
QVariantMap consume = parser.parse (json, &ok).toMap();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
_consume = Consume::fromJson(consume);
putTickets();
} else if (_postConsumeReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
}
}
}
void PayWidget::putTickets()
{
qDebug() << "PayWidget::putTickets()";
_nextAction->setEnabled(false);
_previousAction->setEnabled(false);
UseRule *useRule = _netEditor->getSelectedUseRule();
bool allPutted = true;
for (QList<Ticket *>::iterator i = _tickets.begin(); i != _tickets.end(); ++i) {
if ((*i)->getCheckState() == Qt::Checked) {
if (!(*i)->getValidAfterUse() || (*i)->getSaveAfterUse() != 0) {
putTicket(*i, useRule);
allPutted = false;
break;
}
}
}
if (allPutted) {
_nextAction->setEnabled(true);
_previousAction->setEnabled(true);
stepFour();
}
}
void PayWidget::putTicket(Ticket *ticket, UseRule *useRule)
{
qDebug() << "PayWidget::putTicket()";
QNetworkRequest request(QUrl((Utils::getHost().append("/managers/%1/tickets/%2")).arg(_managerId).arg(ticket->getTicketId())));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader(QByteArray("X-AUTH-TOKEN"), _token.toUtf8());
QVariantMap variant;
variant.insert("consumeId", _consume->getConsumeId());
variant.insert("save", ticket->getSaveAfterUse());
if (useRule != NULL) {
variant.insert("ruleId", useRule->getRuleId());
}
if (ticket->getValidAfterUse()) {
variant.insert("state", 0);
} else {
variant.insert("state", 1);
}
if (ticket->getType() == Ticket::Deduction) {
variant.insert("leftDeduction", ticket->getLeftDeductionAfterUse());
}
bool ok;
QJson::Serializer serializer;
QByteArray data = serializer.serialize(variant, &ok);
Q_ASSERT(ok);
_putTicketReply = _qnam.put(request, data);
connect(_putTicketReply, SIGNAL(finished()), this, SLOT(handlePutTicketFinished()));
}
void PayWidget::handlePutTicketFinished()
{
qDebug() << "PayWidget::handlePutTicketFinished()";
if (_putTicketReply != NULL) {
_putTicketReply->close();
_putTicketReply->deleteLater();
if (_putTicketReply->error() == QNetworkReply::NoError) {
QByteArray json = _putTicketReply->readAll();
QJson::Parser parser;
bool ok;
QVariantMap ticket = parser.parse (json, &ok).toMap();
if (!ok) {
qDebug() << "some error happend on server";
return;
}
Ticket *newTicket = Ticket::fromJson(ticket);
qDebug() << "ticket putted: " << newTicket->getTicketId();
// remove from _tickets
QMutableListIterator<Ticket *> i(_tickets);
while (i.hasNext()) {
Ticket *t = i.next();
if (t->getTicketId() == newTicket->getTicketId()) {
i.remove();
break;
}
}
putTickets();
} else if (_putTicketReply->error() == QNetworkReply::AuthenticationRequiredError) {
qDebug() << "authentication error";
QMessageBox::critical(this, trUtf8("认证失败"), trUtf8("请退出系统重新认证!"));
}
}
}
void PayWidget::stepFour()
{
initActionsForLastStep();
connect(_issueAction, SIGNAL(triggered()), this, SLOT(postTicket()));
connect(_cancelAction, SIGNAL(triggered()), this, SLOT(cancel()));
_dueEditor->hide();
_reduceEditor->hide();
delete _netEditor;
_netEditor = NULL;
_issueEditor = new IssueEditor(_managerId, _managerName, _level, _token, _companyId, _companyName, _latitude, _longitude, _issueRules, _netPaid, this);
_issueEditor->setGeometry(250, 0, 1024 - 250, 540 - 54);
_issueEditor->show();
QString currentStep = trUtf8("发优惠券");
_stepIndicator->setCurrentStep(currentStep);
int candidateRulesCount = _issueEditor->getCandidateRulesCount();
QString info = trUtf8("实付: %1元, 可选发券规则%2条");
info = info.arg((_netPaid) / 100.0, 0, 'f', 2).arg(candidateRulesCount);
_payInfo->setText(info);
}
void PayWidget::handleSummaryUpdated(QString &info)
{
_payInfo->setText(info);
}
| 36.081608 | 194 | 0.625831 | waitWindComing |
046c002867a6b4e94ad016444a1160eb17f3229d | 1,383 | cpp | C++ | merge_sort.cpp | mzmmoazam/OpenCV-using-C-plus-plus | 4c43848ba6aec938eeaeb3c85021c91f4c2e273c | [
"MIT"
] | null | null | null | merge_sort.cpp | mzmmoazam/OpenCV-using-C-plus-plus | 4c43848ba6aec938eeaeb3c85021c91f4c2e273c | [
"MIT"
] | null | null | null | merge_sort.cpp | mzmmoazam/OpenCV-using-C-plus-plus | 4c43848ba6aec938eeaeb3c85021c91f4c2e273c | [
"MIT"
] | null | null | null | #include <iostream>
// divide and conquer
using namespace std;
void printArray(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void merge(int a[], int l, int m, int r)
{
int leftn = m - l + 1, rightn = r - m;
int L[leftn], R[rightn], i = 0, j = 0, k = l;
for (i = 0; i < leftn; i++)
L[i] = a[l + i];
for (j = 0; j < rightn; j++)
R[j] = a[m + j + 1];
i = 0, j = 0, k = l;
while (i < leftn && j < rightn)
{
if (L[i] < R[j])
a[k] = L[i], i++;
else
a[k] = R[j], j++;
k++;
}
if (i < leftn)
a[k] = L[i], i++, k++;
if (j < rightn)
a[k] = R[j], j++, k++;
}
void mergeSort(int a[], int l, int r)
{
if (l < r)
{
int m = (l + r - 1) / 2;
// cout << l << "knkn" << r << "rrrr" << m << "mmm";
mergeSort(a, l, m);
mergeSort(a, m + 1, r);
merge(a, l, m, r);
}
}
int main()
{
int a[50], n, i, j, temp;
cout << "Enter the number of elements ?" << endl;
cin >> n;
cout << "Enter the " << n << " numbers :" << endl;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
cout << "Here is the list of numbers" << endl;
printArray(a, n);
mergeSort(a, 0, n);
printArray(a, n);
cout << endl;
return 0;
} | 16.662651 | 60 | 0.386117 | mzmmoazam |
04783220c2acdb14e951f98c2e8e3299b01cb339 | 2,833 | cpp | C++ | contrib/groff/src/preproc/eqn/mark.cpp | ivadasz/DragonFlyBSD | 460227f342554313be3c7728ff679dd4a556cce9 | [
"BSD-3-Clause"
] | 3 | 2017-03-06T14:12:57.000Z | 2019-11-23T09:35:10.000Z | contrib/groff/src/preproc/eqn/mark.cpp | jorisgio/DragonFlyBSD | d37cc9027d161f3e36bf2667d32f41f87606b2ac | [
"BSD-3-Clause"
] | null | null | null | contrib/groff/src/preproc/eqn/mark.cpp | jorisgio/DragonFlyBSD | d37cc9027d161f3e36bf2667d32f41f87606b2ac | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
/* Copyright (C) 1989, 1990, 1991, 1992, 2009
Free Software Foundation, Inc.
Written by James Clark (jjc@jclark.com)
This file is part of groff.
groff is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or
(at your option) any later version.
groff 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, see <http://www.gnu.org/licenses/>. */
#include "eqn.h"
#include "pbox.h"
class mark_box : public pointer_box {
public:
mark_box(box *);
int compute_metrics(int);
void output();
void debug_print();
};
// we push down marks so that they don't interfere with spacing
box *make_mark_box(box *p)
{
list_box *b = p->to_list_box();
if (b != 0) {
b->list.p[0] = make_mark_box(b->list.p[0]);
return b;
}
else
return new mark_box(p);
}
mark_box::mark_box(box *pp) : pointer_box(pp)
{
}
void mark_box::output()
{
p->output();
}
int mark_box::compute_metrics(int style)
{
int res = p->compute_metrics(style);
if (res)
error("multiple marks and lineups");
printf(".nr " WIDTH_FORMAT " 0\\n[" WIDTH_FORMAT "]\n", uid, p->uid);
printf(".nr " HEIGHT_FORMAT " \\n[" HEIGHT_FORMAT "]\n", uid, p->uid);
printf(".nr " DEPTH_FORMAT " \\n[" DEPTH_FORMAT "]\n", uid, p->uid);
printf(".nr " MARK_REG " 0\n");
return FOUND_MARK;
}
void mark_box::debug_print()
{
fprintf(stderr, "mark { ");
p->debug_print();
fprintf(stderr, " }");
}
class lineup_box : public pointer_box {
public:
lineup_box(box *);
void output();
int compute_metrics(int style);
void debug_print();
};
// we push down lineups so that they don't interfere with spacing
box *make_lineup_box(box *p)
{
list_box *b = p->to_list_box();
if (b != 0) {
b->list.p[0] = make_lineup_box(b->list.p[0]);
return b;
}
else
return new lineup_box(p);
}
lineup_box::lineup_box(box *pp) : pointer_box(pp)
{
}
void lineup_box::output()
{
p->output();
}
int lineup_box::compute_metrics(int style)
{
int res = p->compute_metrics(style);
if (res)
error("multiple marks and lineups");
printf(".nr " WIDTH_FORMAT " 0\\n[" WIDTH_FORMAT "]\n", uid, p->uid);
printf(".nr " HEIGHT_FORMAT " \\n[" HEIGHT_FORMAT "]\n", uid, p->uid);
printf(".nr " DEPTH_FORMAT " \\n[" DEPTH_FORMAT "]\n", uid, p->uid);
printf(".nr " MARK_REG " 0\n");
return FOUND_LINEUP;
}
void lineup_box::debug_print()
{
fprintf(stderr, "lineup { ");
p->debug_print();
fprintf(stderr, " }");
}
| 23.221311 | 72 | 0.662902 | ivadasz |
047a0b542d2327d0501f058fe4257e0a4214cd23 | 3,774 | hpp | C++ | external/windows/boost/include/boost/spirit/core/non_terminal/parser_id.hpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | 1 | 2016-05-17T03:36:52.000Z | 2016-05-17T03:36:52.000Z | external/windows/boost/include/boost/spirit/core/non_terminal/parser_id.hpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | null | null | null | external/windows/boost/include/boost/spirit/core/non_terminal/parser_id.hpp | foxostro/CheeseTesseract | 737ebbd19cee8f5a196bf39a11ca793c561e56cb | [
"MIT"
] | null | null | null | /*=============================================================================
Copyright (c) 2001-2003 Joel de Guzman
Copyright (c) 2001 Daniel Nuffer
http://spirit.sourceforge.net/
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_PARSER_ID_HPP)
#define BOOST_SPIRIT_PARSER_ID_HPP
#if defined(BOOST_SPIRIT_DEBUG)
# include <ostream>
#endif
///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit {
///////////////////////////////////////////////////////////////////////////
//
// parser_id class
//
///////////////////////////////////////////////////////////////////////////
class parser_id
{
public:
parser_id() : p(0) {}
explicit parser_id(void const* prule) : p(prule) {}
parser_id(std::size_t l_) : l(l_) {}
bool operator==(parser_id const& x) const { return p == x.p; }
bool operator!=(parser_id const& x) const { return !(*this == x); }
bool operator<(parser_id const& x) const { return p < x.p; }
std::size_t to_long() const { return l; }
private:
union
{
void const* p;
std::size_t l;
};
};
#if defined(BOOST_SPIRIT_DEBUG)
inline std::ostream&
operator<<(std::ostream& out, parser_id const& rid)
{
out << (unsigned int)rid.to_long();
return out;
}
#endif
///////////////////////////////////////////////////////////////////////////
//
// parser_tag_base class: base class of all parser tags
//
///////////////////////////////////////////////////////////////////////////
struct parser_tag_base {};
///////////////////////////////////////////////////////////////////////////
//
// parser_address_tag class: tags a parser with its address
//
///////////////////////////////////////////////////////////////////////////
struct parser_address_tag : parser_tag_base
{
parser_id id() const
{ return parser_id(reinterpret_cast<std::size_t>(this)); }
};
///////////////////////////////////////////////////////////////////////////
//
// parser_tag class: tags a parser with an integer ID
//
///////////////////////////////////////////////////////////////////////////
template <int N>
struct parser_tag : parser_tag_base
{
static parser_id id()
{ return parser_id(std::size_t(N)); }
};
///////////////////////////////////////////////////////////////////////////
//
// dynamic_parser_tag class: tags a parser with a dynamically changeable
// integer ID
//
///////////////////////////////////////////////////////////////////////////
class dynamic_parser_tag : public parser_tag_base
{
public:
dynamic_parser_tag()
: tag(std::size_t(0)) {}
parser_id
id() const
{
return
tag.to_long()
? tag
: parser_id(reinterpret_cast<std::size_t>(this));
}
void set_id(parser_id id) { tag = id; }
private:
parser_id tag;
};
///////////////////////////////////////////////////////////////////////////////
}} // namespace boost::spirit
#endif
| 31.714286 | 80 | 0.372284 | foxostro |
047c14c675f9d6841f5786e631c8cbc190fc5b25 | 48,326 | cc | C++ | test/unittests/compiler/int64-lowering-unittest.cc | devcode1981/v8 | 10f26c08b9e6cdddc7d033c5572ae68e2383d2a4 | [
"BSD-3-Clause"
] | 1 | 2022-03-15T16:20:56.000Z | 2022-03-15T16:20:56.000Z | test/unittests/compiler/int64-lowering-unittest.cc | devcode1981/v8 | 10f26c08b9e6cdddc7d033c5572ae68e2383d2a4 | [
"BSD-3-Clause"
] | null | null | null | test/unittests/compiler/int64-lowering-unittest.cc | devcode1981/v8 | 10f26c08b9e6cdddc7d033c5572ae68e2383d2a4 | [
"BSD-3-Clause"
] | 1 | 2021-03-08T00:27:58.000Z | 2021-03-08T00:27:58.000Z | // Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/int64-lowering.h"
#include "src/codegen/interface-descriptors.h"
#include "src/codegen/machine-type.h"
#include "src/codegen/signature.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/linkage.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/node.h"
#include "src/compiler/wasm-compiler.h"
#include "src/wasm/value-type.h"
#include "src/wasm/wasm-module.h"
#include "test/unittests/compiler/graph-unittest.h"
#include "test/unittests/compiler/node-test-utils.h"
#include "testing/gmock-support.h"
using testing::AllOf;
using testing::Capture;
using testing::CaptureEq;
namespace v8 {
namespace internal {
namespace compiler {
class Int64LoweringTest : public GraphTest {
public:
Int64LoweringTest()
: GraphTest(),
machine_(zone(), MachineRepresentation::kWord32,
MachineOperatorBuilder::Flag::kAllOptionalOps) {
value_[0] = 0x1234567890ABCDEF;
value_[1] = 0x1EDCBA098765432F;
value_[2] = 0x1133557799886644;
}
MachineOperatorBuilder* machine() { return &machine_; }
void LowerGraph(Node* node, Signature<MachineRepresentation>* signature) {
Node* zero = graph()->NewNode(common()->Int32Constant(0));
Node* ret = graph()->NewNode(common()->Return(), zero, node,
graph()->start(), graph()->start());
NodeProperties::MergeControlToEnd(graph(), common(), ret);
Int64Lowering lowering(graph(), machine(), common(), zone(), signature);
lowering.LowerGraph();
}
void LowerGraphWithSpecialCase(
Node* node, std::unique_ptr<Int64LoweringSpecialCase> special_case,
MachineRepresentation rep) {
Node* zero = graph()->NewNode(common()->Int32Constant(0));
Node* ret = graph()->NewNode(common()->Return(), zero, node,
graph()->start(), graph()->start());
NodeProperties::MergeControlToEnd(graph(), common(), ret);
// Create a signature for the outer wasm<>js call; for these tests we focus
// on lowering the special cases rather than the wrapper node at the
// JavaScript boundaries.
Signature<MachineRepresentation>::Builder sig_builder(zone(), 1, 0);
sig_builder.AddReturn(rep);
Int64Lowering lowering(graph(), machine(), common(), zone(),
sig_builder.Build(), std::move(special_case));
lowering.LowerGraph();
}
void LowerGraph(Node* node, MachineRepresentation return_type,
MachineRepresentation rep = MachineRepresentation::kWord32,
int num_params = 0) {
Signature<MachineRepresentation>::Builder sig_builder(zone(), 1,
num_params);
sig_builder.AddReturn(return_type);
for (int i = 0; i < num_params; i++) {
sig_builder.AddParam(rep);
}
LowerGraph(node, sig_builder.Build());
}
void CompareCallDescriptors(const CallDescriptor* lhs,
const CallDescriptor* rhs) {
EXPECT_THAT(lhs->CalleeSavedFPRegisters(), rhs->CalleeSavedFPRegisters());
EXPECT_THAT(lhs->CalleeSavedRegisters(), rhs->CalleeSavedRegisters());
EXPECT_THAT(lhs->FrameStateCount(), rhs->FrameStateCount());
EXPECT_THAT(lhs->InputCount(), rhs->InputCount());
for (size_t i = 0; i < lhs->InputCount(); i++) {
EXPECT_THAT(lhs->GetInputLocation(i), rhs->GetInputLocation(i));
EXPECT_THAT(lhs->GetInputType(i), rhs->GetInputType(i));
}
EXPECT_THAT(lhs->ReturnCount(), rhs->ReturnCount());
for (size_t i = 0; i < lhs->ReturnCount(); i++) {
EXPECT_THAT(lhs->GetReturnLocation(i), rhs->GetReturnLocation(i));
EXPECT_THAT(lhs->GetReturnType(i), rhs->GetReturnType(i));
}
EXPECT_THAT(lhs->flags(), rhs->flags());
EXPECT_THAT(lhs->kind(), rhs->kind());
}
int64_t value(int i) { return value_[i]; }
int32_t low_word_value(int i) {
return static_cast<int32_t>(value_[i] & 0xFFFFFFFF);
}
int32_t high_word_value(int i) {
return static_cast<int32_t>(value_[i] >> 32);
}
void TestComparison(
const Operator* op,
Matcher<Node*> (*high_word_matcher)(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher),
Matcher<Node*> (*low_word_matcher)(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher)) {
LowerGraph(
graph()->NewNode(op, Int64Constant(value(0)), Int64Constant(value(1))),
MachineRepresentation::kWord32);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn(IsWord32Or(
high_word_matcher(IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1))),
IsWord32And(
IsWord32Equal(IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1))),
low_word_matcher(IsInt32Constant(low_word_value(0)),
IsInt32Constant(low_word_value(1))))),
start(), start()));
}
private:
MachineOperatorBuilder machine_;
int64_t value_[3];
};
TEST_F(Int64LoweringTest, Int64Constant) {
LowerGraph(Int64Constant(value(0)), MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsInt32Constant(low_word_value(0)),
IsInt32Constant(high_word_value(0)), start(), start()));
}
#if defined(V8_TARGET_LITTLE_ENDIAN)
#define LOAD_VERIFY(kLoad) \
Matcher<Node*> high_word_load_matcher = \
Is##kLoad(MachineType::Int32(), IsInt32Constant(base), \
IsInt32Add(IsInt32Constant(index), IsInt32Constant(0x4)), \
start(), start()); \
\
EXPECT_THAT( \
graph()->end()->InputAt(1), \
IsReturn2( \
Is##kLoad(MachineType::Int32(), IsInt32Constant(base), \
IsInt32Constant(index), \
AllOf(CaptureEq(&high_word_load), high_word_load_matcher), \
start()), \
AllOf(CaptureEq(&high_word_load), high_word_load_matcher), start(), \
start()));
#elif defined(V8_TARGET_BIG_ENDIAN)
#define LOAD_VERIFY(kLoad) \
Matcher<Node*> high_word_load_matcher = \
Is##kLoad(MachineType::Int32(), IsInt32Constant(base), \
IsInt32Constant(index), start(), start()); \
\
EXPECT_THAT( \
graph()->end()->InputAt(1), \
IsReturn2( \
Is##kLoad(MachineType::Int32(), IsInt32Constant(base), \
IsInt32Add(IsInt32Constant(index), IsInt32Constant(0x4)), \
AllOf(CaptureEq(&high_word_load), high_word_load_matcher), \
start()), \
AllOf(CaptureEq(&high_word_load), high_word_load_matcher), start(), \
start()));
#endif
#define INT64_LOAD_LOWERING(kLoad) \
int32_t base = 0x1234; \
int32_t index = 0x5678; \
\
LowerGraph(graph()->NewNode(machine()->kLoad(MachineType::Int64()), \
Int32Constant(base), Int32Constant(index), \
start(), start()), \
MachineRepresentation::kWord64); \
\
Capture<Node*> high_word_load; \
LOAD_VERIFY(kLoad)
TEST_F(Int64LoweringTest, Int64Load) { INT64_LOAD_LOWERING(Load); }
TEST_F(Int64LoweringTest, UnalignedInt64Load) {
INT64_LOAD_LOWERING(UnalignedLoad);
}
#if defined(V8_TARGET_LITTLE_ENDIAN)
#define STORE_VERIFY(kStore, kRep) \
EXPECT_THAT( \
graph()->end()->InputAt(1), \
IsReturn(IsInt32Constant(return_value), \
Is##kStore( \
kRep, IsInt32Constant(base), IsInt32Constant(index), \
IsInt32Constant(low_word_value(0)), \
Is##kStore( \
kRep, IsInt32Constant(base), \
IsInt32Add(IsInt32Constant(index), IsInt32Constant(4)), \
IsInt32Constant(high_word_value(0)), start(), start()), \
start()), \
start()));
#elif defined(V8_TARGET_BIG_ENDIAN)
#define STORE_VERIFY(kStore, kRep) \
EXPECT_THAT( \
graph()->end()->InputAt(1), \
IsReturn(IsInt32Constant(return_value), \
Is##kStore( \
kRep, IsInt32Constant(base), \
IsInt32Add(IsInt32Constant(index), IsInt32Constant(4)), \
IsInt32Constant(low_word_value(0)), \
Is##kStore( \
kRep, IsInt32Constant(base), IsInt32Constant(index), \
IsInt32Constant(high_word_value(0)), start(), start()), \
start()), \
start()));
#endif
#define INT64_STORE_LOWERING(kStore, kRep32, kRep64) \
int32_t base = 1111; \
int32_t index = 2222; \
int32_t return_value = 0x5555; \
\
Signature<MachineRepresentation>::Builder sig_builder(zone(), 1, 0); \
sig_builder.AddReturn(MachineRepresentation::kWord32); \
\
Node* store = graph()->NewNode(machine()->kStore(kRep64), \
Int32Constant(base), Int32Constant(index), \
Int64Constant(value(0)), start(), start()); \
\
Node* zero = graph()->NewNode(common()->Int32Constant(0)); \
Node* ret = graph()->NewNode(common()->Return(), zero, \
Int32Constant(return_value), store, start()); \
\
NodeProperties::MergeControlToEnd(graph(), common(), ret); \
\
Int64Lowering lowering(graph(), machine(), common(), zone(), \
sig_builder.Build()); \
lowering.LowerGraph(); \
\
STORE_VERIFY(kStore, kRep32)
TEST_F(Int64LoweringTest, Int64Store) {
const StoreRepresentation rep64(MachineRepresentation::kWord64,
WriteBarrierKind::kNoWriteBarrier);
const StoreRepresentation rep32(MachineRepresentation::kWord32,
WriteBarrierKind::kNoWriteBarrier);
INT64_STORE_LOWERING(Store, rep32, rep64);
}
TEST_F(Int64LoweringTest, Int32Store) {
const StoreRepresentation rep32(MachineRepresentation::kWord32,
WriteBarrierKind::kNoWriteBarrier);
int32_t base = 1111;
int32_t index = 2222;
int32_t return_value = 0x5555;
Signature<MachineRepresentation>::Builder sig_builder(zone(), 1, 0);
sig_builder.AddReturn(MachineRepresentation::kWord32);
Node* store = graph()->NewNode(machine()->Store(rep32), Int32Constant(base),
Int32Constant(index), Int64Constant(value(0)),
start(), start());
Node* zero = graph()->NewNode(common()->Int32Constant(0));
Node* ret = graph()->NewNode(common()->Return(), zero,
Int32Constant(return_value), store, start());
NodeProperties::MergeControlToEnd(graph(), common(), ret);
Int64Lowering lowering(graph(), machine(), common(), zone(),
sig_builder.Build());
lowering.LowerGraph();
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn(IsInt32Constant(return_value),
IsStore(rep32, IsInt32Constant(base), IsInt32Constant(index),
IsInt32Constant(low_word_value(0)), start(), start()),
start()));
}
TEST_F(Int64LoweringTest, Int64UnalignedStore) {
const UnalignedStoreRepresentation rep64(MachineRepresentation::kWord64);
const UnalignedStoreRepresentation rep32(MachineRepresentation::kWord32);
INT64_STORE_LOWERING(UnalignedStore, rep32, rep64);
}
TEST_F(Int64LoweringTest, Int64And) {
LowerGraph(graph()->NewNode(machine()->Word64And(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsWord32And(IsInt32Constant(low_word_value(0)),
IsInt32Constant(low_word_value(1))),
IsWord32And(IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1))),
start(), start()));
}
TEST_F(Int64LoweringTest, TruncateInt64ToInt32) {
LowerGraph(graph()->NewNode(machine()->TruncateInt64ToInt32(),
Int64Constant(value(0))),
MachineRepresentation::kWord32);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn(IsInt32Constant(low_word_value(0)), start(), start()));
}
TEST_F(Int64LoweringTest, Parameter) {
LowerGraph(Parameter(1), MachineRepresentation::kWord64,
MachineRepresentation::kWord64, 1);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsParameter(1), IsParameter(2), start(), start()));
}
TEST_F(Int64LoweringTest, Parameter2) {
Signature<MachineRepresentation>::Builder sig_builder(zone(), 1, 5);
sig_builder.AddReturn(MachineRepresentation::kWord32);
sig_builder.AddParam(MachineRepresentation::kWord32);
sig_builder.AddParam(MachineRepresentation::kWord64);
sig_builder.AddParam(MachineRepresentation::kFloat64);
sig_builder.AddParam(MachineRepresentation::kWord64);
sig_builder.AddParam(MachineRepresentation::kWord32);
int start_parameter = start()->op()->ValueOutputCount();
LowerGraph(Parameter(5), sig_builder.Build());
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn(IsParameter(7), start(), start()));
// The parameter of the start node should increase by 2, because we lowered
// two parameter nodes.
EXPECT_THAT(start()->op()->ValueOutputCount(), start_parameter + 2);
}
TEST_F(Int64LoweringTest, ParameterWithJSContextParam) {
Signature<MachineRepresentation>::Builder sig_builder(zone(), 0, 2);
sig_builder.AddParam(MachineRepresentation::kWord64);
sig_builder.AddParam(MachineRepresentation::kWord64);
auto sig = sig_builder.Build();
Node* js_context = graph()->NewNode(
common()->Parameter(Linkage::GetJSCallContextParamIndex(
static_cast<int>(sig->parameter_count()) + 1),
"%context"),
start());
LowerGraph(js_context, sig);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn(js_context, start(), start()));
}
TEST_F(Int64LoweringTest, ParameterWithJSClosureParam) {
Signature<MachineRepresentation>::Builder sig_builder(zone(), 0, 2);
sig_builder.AddParam(MachineRepresentation::kWord64);
sig_builder.AddParam(MachineRepresentation::kWord64);
auto sig = sig_builder.Build();
Node* js_closure = graph()->NewNode(
common()->Parameter(Linkage::kJSCallClosureParamIndex, "%closure"),
start());
LowerGraph(js_closure, sig);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn(js_closure, start(), start()));
}
// The following tests assume that pointers are 32 bit and therefore pointers do
// not get lowered. This assumption does not hold on 64 bit platforms, which
// invalidates these tests.
// TODO(wasm): We can find an alternative to re-activate these tests.
#if V8_TARGET_ARCH_32_BIT
TEST_F(Int64LoweringTest, CallI64Return) {
int32_t function = 0x9999;
Node* context_address = Int32Constant(0);
wasm::FunctionSig::Builder sig_builder(zone(), 1, 0);
sig_builder.AddReturn(wasm::kWasmI64);
auto call_descriptor =
compiler::GetWasmCallDescriptor(zone(), sig_builder.Build());
LowerGraph(
graph()->NewNode(common()->Call(call_descriptor), Int32Constant(function),
context_address, start(), start()),
MachineRepresentation::kWord64);
Capture<Node*> call;
Matcher<Node*> call_matcher =
IsCall(testing::_, IsInt32Constant(function), start(), start());
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&call), call_matcher)),
IsProjection(1, AllOf(CaptureEq(&call), call_matcher)),
start(), start()));
CompareCallDescriptors(
CallDescriptorOf(
graph()->end()->InputAt(1)->InputAt(1)->InputAt(0)->op()),
compiler::GetI32WasmCallDescriptor(zone(), call_descriptor));
}
TEST_F(Int64LoweringTest, CallI64Parameter) {
int32_t function = 0x9999;
Node* context_address = Int32Constant(0);
wasm::FunctionSig::Builder sig_builder(zone(), 1, 3);
sig_builder.AddReturn(wasm::kWasmI32);
sig_builder.AddParam(wasm::kWasmI64);
sig_builder.AddParam(wasm::kWasmI32);
sig_builder.AddParam(wasm::kWasmI64);
auto call_descriptor =
compiler::GetWasmCallDescriptor(zone(), sig_builder.Build());
LowerGraph(
graph()->NewNode(common()->Call(call_descriptor), Int32Constant(function),
context_address, Int64Constant(value(0)),
Int32Constant(low_word_value(1)),
Int64Constant(value(2)), start(), start()),
MachineRepresentation::kWord32);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn(IsCall(testing::_, IsInt32Constant(function), context_address,
IsInt32Constant(low_word_value(0)),
IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(1)),
IsInt32Constant(low_word_value(2)),
IsInt32Constant(high_word_value(2)), start(), start()),
start(), start()));
CompareCallDescriptors(
CallDescriptorOf(graph()->end()->InputAt(1)->InputAt(1)->op()),
compiler::GetI32WasmCallDescriptor(zone(), call_descriptor));
}
TEST_F(Int64LoweringTest, Int64Add) {
LowerGraph(graph()->NewNode(machine()->Int64Add(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
Capture<Node*> add;
Matcher<Node*> add_matcher = IsInt32PairAdd(
IsInt32Constant(low_word_value(0)), IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(1)), IsInt32Constant(high_word_value(1)));
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&add), add_matcher)),
IsProjection(1, AllOf(CaptureEq(&add), add_matcher)),
start(), start()));
}
#endif
TEST_F(Int64LoweringTest, Int64Sub) {
LowerGraph(graph()->NewNode(machine()->Int64Sub(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
Capture<Node*> sub;
Matcher<Node*> sub_matcher = IsInt32PairSub(
IsInt32Constant(low_word_value(0)), IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(1)), IsInt32Constant(high_word_value(1)));
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&sub), sub_matcher)),
IsProjection(1, AllOf(CaptureEq(&sub), sub_matcher)),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64Mul) {
LowerGraph(graph()->NewNode(machine()->Int64Mul(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
Capture<Node*> mul_capture;
Matcher<Node*> mul_matcher = IsInt32PairMul(
IsInt32Constant(low_word_value(0)), IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(1)), IsInt32Constant(high_word_value(1)));
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&mul_capture), mul_matcher)),
IsProjection(1, AllOf(CaptureEq(&mul_capture), mul_matcher)),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64Ior) {
LowerGraph(graph()->NewNode(machine()->Word64Or(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsWord32Or(IsInt32Constant(low_word_value(0)),
IsInt32Constant(low_word_value(1))),
IsWord32Or(IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1))),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64Xor) {
LowerGraph(graph()->NewNode(machine()->Word64Xor(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsWord32Xor(IsInt32Constant(low_word_value(0)),
IsInt32Constant(low_word_value(1))),
IsWord32Xor(IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1))),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64Shl) {
LowerGraph(graph()->NewNode(machine()->Word64Shl(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
Capture<Node*> shl;
Matcher<Node*> shl_matcher = IsWord32PairShl(
IsInt32Constant(low_word_value(0)), IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(1)));
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&shl), shl_matcher)),
IsProjection(1, AllOf(CaptureEq(&shl), shl_matcher)),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64ShrU) {
LowerGraph(graph()->NewNode(machine()->Word64Shr(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
Capture<Node*> shr;
Matcher<Node*> shr_matcher = IsWord32PairShr(
IsInt32Constant(low_word_value(0)), IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(1)));
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&shr), shr_matcher)),
IsProjection(1, AllOf(CaptureEq(&shr), shr_matcher)),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64ShrS) {
LowerGraph(graph()->NewNode(machine()->Word64Sar(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord64);
Capture<Node*> sar;
Matcher<Node*> sar_matcher = IsWord32PairSar(
IsInt32Constant(low_word_value(0)), IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(1)));
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&sar), sar_matcher)),
IsProjection(1, AllOf(CaptureEq(&sar), sar_matcher)),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64Eq) {
LowerGraph(graph()->NewNode(machine()->Word64Equal(), Int64Constant(value(0)),
Int64Constant(value(1))),
MachineRepresentation::kWord32);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn(IsWord32Equal(
IsWord32Or(IsWord32Xor(IsInt32Constant(low_word_value(0)),
IsInt32Constant(low_word_value(1))),
IsWord32Xor(IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1)))),
IsInt32Constant(0)),
start(), start()));
}
TEST_F(Int64LoweringTest, Int64LtS) {
TestComparison(machine()->Int64LessThan(), IsInt32LessThan, IsUint32LessThan);
}
TEST_F(Int64LoweringTest, Int64LeS) {
TestComparison(machine()->Int64LessThanOrEqual(), IsInt32LessThan,
IsUint32LessThanOrEqual);
}
TEST_F(Int64LoweringTest, Int64LtU) {
TestComparison(machine()->Uint64LessThan(), IsUint32LessThan,
IsUint32LessThan);
}
TEST_F(Int64LoweringTest, Int64LeU) {
TestComparison(machine()->Uint64LessThanOrEqual(), IsUint32LessThan,
IsUint32LessThanOrEqual);
}
TEST_F(Int64LoweringTest, I32ConvertI64) {
LowerGraph(graph()->NewNode(machine()->TruncateInt64ToInt32(),
Int64Constant(value(0))),
MachineRepresentation::kWord32);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn(IsInt32Constant(low_word_value(0)), start(), start()));
}
TEST_F(Int64LoweringTest, I64SConvertI32) {
LowerGraph(graph()->NewNode(machine()->ChangeInt32ToInt64(),
Int32Constant(low_word_value(0))),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsInt32Constant(low_word_value(0)),
IsWord32Sar(IsInt32Constant(low_word_value(0)),
IsInt32Constant(31)),
start(), start()));
}
TEST_F(Int64LoweringTest, I64SConvertI32_2) {
LowerGraph(
graph()->NewNode(machine()->ChangeInt32ToInt64(),
graph()->NewNode(machine()->TruncateInt64ToInt32(),
Int64Constant(value(0)))),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsInt32Constant(low_word_value(0)),
IsWord32Sar(IsInt32Constant(low_word_value(0)),
IsInt32Constant(31)),
start(), start()));
}
TEST_F(Int64LoweringTest, I64UConvertI32) {
LowerGraph(graph()->NewNode(machine()->ChangeUint32ToUint64(),
Int32Constant(low_word_value(0))),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsInt32Constant(low_word_value(0)), IsInt32Constant(0),
start(), start()));
}
TEST_F(Int64LoweringTest, I64UConvertI32_2) {
LowerGraph(
graph()->NewNode(machine()->ChangeUint32ToUint64(),
graph()->NewNode(machine()->TruncateInt64ToInt32(),
Int64Constant(value(0)))),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsInt32Constant(low_word_value(0)), IsInt32Constant(0),
start(), start()));
}
TEST_F(Int64LoweringTest, F64ReinterpretI64) {
LowerGraph(graph()->NewNode(machine()->BitcastInt64ToFloat64(),
Int64Constant(value(0))),
MachineRepresentation::kFloat64);
Capture<Node*> stack_slot_capture;
Matcher<Node*> stack_slot_matcher =
IsStackSlot(StackSlotRepresentation(sizeof(int64_t), 0));
Capture<Node*> store_capture;
Matcher<Node*> store_matcher =
IsStore(StoreRepresentation(MachineRepresentation::kWord32,
WriteBarrierKind::kNoWriteBarrier),
AllOf(CaptureEq(&stack_slot_capture), stack_slot_matcher),
IsInt32Constant(kInt64LowerHalfMemoryOffset),
IsInt32Constant(low_word_value(0)),
IsStore(StoreRepresentation(MachineRepresentation::kWord32,
WriteBarrierKind::kNoWriteBarrier),
AllOf(CaptureEq(&stack_slot_capture), stack_slot_matcher),
IsInt32Constant(kInt64UpperHalfMemoryOffset),
IsInt32Constant(high_word_value(0)), start(), start()),
start());
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn(IsLoad(MachineType::Float64(),
AllOf(CaptureEq(&stack_slot_capture), stack_slot_matcher),
IsInt32Constant(0),
AllOf(CaptureEq(&store_capture), store_matcher), start()),
start(), start()));
}
TEST_F(Int64LoweringTest, I64ReinterpretF64) {
LowerGraph(graph()->NewNode(machine()->BitcastFloat64ToInt64(),
Float64Constant(bit_cast<double>(value(0)))),
MachineRepresentation::kWord64);
Capture<Node*> stack_slot;
Matcher<Node*> stack_slot_matcher =
IsStackSlot(StackSlotRepresentation(sizeof(int64_t), 0));
Capture<Node*> store;
Matcher<Node*> store_matcher = IsStore(
StoreRepresentation(MachineRepresentation::kFloat64,
WriteBarrierKind::kNoWriteBarrier),
AllOf(CaptureEq(&stack_slot), stack_slot_matcher), IsInt32Constant(0),
IsFloat64Constant(bit_cast<double>(value(0))), start(), start());
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(IsLoad(MachineType::Int32(),
AllOf(CaptureEq(&stack_slot), stack_slot_matcher),
IsInt32Constant(kInt64LowerHalfMemoryOffset),
AllOf(CaptureEq(&store), store_matcher), start()),
IsLoad(MachineType::Int32(),
AllOf(CaptureEq(&stack_slot), stack_slot_matcher),
IsInt32Constant(kInt64UpperHalfMemoryOffset),
AllOf(CaptureEq(&store), store_matcher), start()),
start(), start()));
}
TEST_F(Int64LoweringTest, I64Clz) {
LowerGraph(graph()->NewNode(machine()->Word64Clz(), Int64Constant(value(0))),
MachineRepresentation::kWord64);
Capture<Node*> branch_capture;
Matcher<Node*> branch_matcher = IsBranch(
IsWord32Equal(IsInt32Constant(high_word_value(0)), IsInt32Constant(0)),
start());
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(
IsPhi(MachineRepresentation::kWord32,
IsInt32Add(IsWord32Clz(IsInt32Constant(low_word_value(0))),
IsInt32Constant(32)),
IsWord32Clz(IsInt32Constant(high_word_value(0))),
IsMerge(
IsIfTrue(AllOf(CaptureEq(&branch_capture), branch_matcher)),
IsIfFalse(
AllOf(CaptureEq(&branch_capture), branch_matcher)))),
IsInt32Constant(0), start(), start()));
}
TEST_F(Int64LoweringTest, I64Ctz) {
LowerGraph(graph()->NewNode(machine()->Word64Ctz().placeholder(),
Int64Constant(value(0))),
MachineRepresentation::kWord64);
Capture<Node*> branch_capture;
Matcher<Node*> branch_matcher = IsBranch(
IsWord32Equal(IsInt32Constant(low_word_value(0)), IsInt32Constant(0)),
start());
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(
IsPhi(MachineRepresentation::kWord32,
IsInt32Add(IsWord32Ctz(IsInt32Constant(high_word_value(0))),
IsInt32Constant(32)),
IsWord32Ctz(IsInt32Constant(low_word_value(0))),
IsMerge(
IsIfTrue(AllOf(CaptureEq(&branch_capture), branch_matcher)),
IsIfFalse(
AllOf(CaptureEq(&branch_capture), branch_matcher)))),
IsInt32Constant(0), start(), start()));
}
TEST_F(Int64LoweringTest, Dfs) {
Node* common = Int64Constant(value(0));
LowerGraph(graph()->NewNode(machine()->Word64And(), common,
graph()->NewNode(machine()->Word64And(), common,
Int64Constant(value(1)))),
MachineRepresentation::kWord64);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(IsWord32And(IsInt32Constant(low_word_value(0)),
IsWord32And(IsInt32Constant(low_word_value(0)),
IsInt32Constant(low_word_value(1)))),
IsWord32And(IsInt32Constant(high_word_value(0)),
IsWord32And(IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1)))),
start(), start()));
}
TEST_F(Int64LoweringTest, I64Popcnt) {
LowerGraph(graph()->NewNode(machine()->Word64Popcnt().placeholder(),
Int64Constant(value(0))),
MachineRepresentation::kWord64);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(IsInt32Add(IsWord32Popcnt(IsInt32Constant(low_word_value(0))),
IsWord32Popcnt(IsInt32Constant(high_word_value(0)))),
IsInt32Constant(0), start(), start()));
}
TEST_F(Int64LoweringTest, I64Ror) {
LowerGraph(graph()->NewNode(machine()->Word64Ror(), Int64Constant(value(0)),
Parameter(0)),
MachineRepresentation::kWord64, MachineRepresentation::kWord64, 1);
Matcher<Node*> branch_lt32_matcher =
IsBranch(IsInt32LessThan(IsParameter(0), IsInt32Constant(32)), start());
Matcher<Node*> low_input_matcher = IsPhi(
MachineRepresentation::kWord32, IsInt32Constant(low_word_value(0)),
IsInt32Constant(high_word_value(0)),
IsMerge(IsIfTrue(branch_lt32_matcher), IsIfFalse(branch_lt32_matcher)));
Matcher<Node*> high_input_matcher = IsPhi(
MachineRepresentation::kWord32, IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(0)),
IsMerge(IsIfTrue(branch_lt32_matcher), IsIfFalse(branch_lt32_matcher)));
Matcher<Node*> shift_matcher =
IsWord32And(IsParameter(0), IsInt32Constant(0x1F));
Matcher<Node*> bit_mask_matcher = IsWord32Xor(
IsWord32Shr(IsInt32Constant(-1), shift_matcher), IsInt32Constant(-1));
Matcher<Node*> inv_mask_matcher =
IsWord32Xor(bit_mask_matcher, IsInt32Constant(-1));
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(
IsWord32Or(IsWord32And(IsWord32Ror(low_input_matcher, shift_matcher),
inv_mask_matcher),
IsWord32And(IsWord32Ror(high_input_matcher, shift_matcher),
bit_mask_matcher)),
IsWord32Or(IsWord32And(IsWord32Ror(high_input_matcher, shift_matcher),
inv_mask_matcher),
IsWord32And(IsWord32Ror(low_input_matcher, shift_matcher),
bit_mask_matcher)),
start(), start()));
}
TEST_F(Int64LoweringTest, I64Ror_0) {
LowerGraph(graph()->NewNode(machine()->Word64Ror(), Int64Constant(value(0)),
Int32Constant(0)),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsInt32Constant(low_word_value(0)),
IsInt32Constant(high_word_value(0)), start(), start()));
}
TEST_F(Int64LoweringTest, I64Ror_32) {
LowerGraph(graph()->NewNode(machine()->Word64Ror(), Int64Constant(value(0)),
Int32Constant(32)),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsInt32Constant(high_word_value(0)),
IsInt32Constant(low_word_value(0)), start(), start()));
}
TEST_F(Int64LoweringTest, I64Ror_11) {
LowerGraph(graph()->NewNode(machine()->Word64Ror(), Int64Constant(value(0)),
Int32Constant(11)),
MachineRepresentation::kWord64);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(IsWord32Or(IsWord32Shr(IsInt32Constant(low_word_value(0)),
IsInt32Constant(11)),
IsWord32Shl(IsInt32Constant(high_word_value(0)),
IsInt32Constant(21))),
IsWord32Or(IsWord32Shr(IsInt32Constant(high_word_value(0)),
IsInt32Constant(11)),
IsWord32Shl(IsInt32Constant(low_word_value(0)),
IsInt32Constant(21))),
start(), start()));
}
TEST_F(Int64LoweringTest, I64Ror_43) {
LowerGraph(graph()->NewNode(machine()->Word64Ror(), Int64Constant(value(0)),
Int32Constant(43)),
MachineRepresentation::kWord64);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(IsWord32Or(IsWord32Shr(IsInt32Constant(high_word_value(0)),
IsInt32Constant(11)),
IsWord32Shl(IsInt32Constant(low_word_value(0)),
IsInt32Constant(21))),
IsWord32Or(IsWord32Shr(IsInt32Constant(low_word_value(0)),
IsInt32Constant(11)),
IsWord32Shl(IsInt32Constant(high_word_value(0)),
IsInt32Constant(21))),
start(), start()));
}
TEST_F(Int64LoweringTest, I64PhiWord64) {
LowerGraph(graph()->NewNode(common()->Phi(MachineRepresentation::kWord64, 2),
Int64Constant(value(0)), Int64Constant(value(1)),
start()),
MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsPhi(MachineRepresentation::kWord32,
IsInt32Constant(low_word_value(0)),
IsInt32Constant(low_word_value(1)), start()),
IsPhi(MachineRepresentation::kWord32,
IsInt32Constant(high_word_value(0)),
IsInt32Constant(high_word_value(1)), start()),
start(), start()));
}
void TestPhi(Int64LoweringTest* test, MachineRepresentation rep, Node* v1,
Node* v2) {
test->LowerGraph(test->graph()->NewNode(test->common()->Phi(rep, 2), v1, v2,
test->start()),
rep);
EXPECT_THAT(test->graph()->end()->InputAt(1),
IsReturn(IsPhi(rep, v1, v2, test->start()), test->start(),
test->start()));
}
TEST_F(Int64LoweringTest, I64PhiFloat32) {
TestPhi(this, MachineRepresentation::kFloat32, Float32Constant(1.5),
Float32Constant(2.5));
}
TEST_F(Int64LoweringTest, I64PhiFloat64) {
TestPhi(this, MachineRepresentation::kFloat64, Float32Constant(1.5),
Float32Constant(2.5));
}
TEST_F(Int64LoweringTest, I64PhiWord32) {
TestPhi(this, MachineRepresentation::kWord32, Float32Constant(1),
Float32Constant(2));
}
TEST_F(Int64LoweringTest, I64ReverseBytes) {
LowerGraph(graph()->NewNode(machine()->Word64ReverseBytes(),
Int64Constant(value(0))),
MachineRepresentation::kWord64);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn2(IsWord32ReverseBytes(IsInt32Constant(high_word_value(0))),
IsWord32ReverseBytes(IsInt32Constant(low_word_value(0))),
start(), start()));
}
TEST_F(Int64LoweringTest, EffectPhiLoop) {
// Construct a cycle consisting of an EffectPhi, a Store, and a Load.
Node* eff_phi = graph()->NewNode(common()->EffectPhi(1), graph()->start(),
graph()->start());
StoreRepresentation store_rep(MachineRepresentation::kWord64,
WriteBarrierKind::kNoWriteBarrier);
LoadRepresentation load_rep(MachineType::Int64());
Node* load =
graph()->NewNode(machine()->Load(load_rep), Int64Constant(value(0)),
Int64Constant(value(1)), eff_phi, graph()->start());
Node* store =
graph()->NewNode(machine()->Store(store_rep), Int64Constant(value(0)),
Int64Constant(value(1)), load, load, graph()->start());
eff_phi->InsertInput(zone(), 1, store);
NodeProperties::ChangeOp(eff_phi,
common()->ResizeMergeOrPhi(eff_phi->op(), 2));
LowerGraph(load, MachineRepresentation::kWord64);
}
TEST_F(Int64LoweringTest, LoopCycle) {
// New node with two placeholders.
Node* compare = graph()->NewNode(machine()->Word64Equal(), Int64Constant(0),
Int64Constant(value(0)));
Node* load = graph()->NewNode(
machine()->Load(MachineType::Int64()), Int64Constant(value(1)),
Int64Constant(value(2)), graph()->start(),
graph()->NewNode(
common()->Loop(2), graph()->start(),
graph()->NewNode(common()->IfFalse(),
graph()->NewNode(common()->Branch(), compare,
graph()->start()))));
NodeProperties::ReplaceValueInput(compare, load, 0);
LowerGraph(load, MachineRepresentation::kWord64);
}
TEST_F(Int64LoweringTest, LoopExitValue) {
Node* loop_header = graph()->NewNode(common()->Loop(1), graph()->start());
Node* loop_exit =
graph()->NewNode(common()->LoopExit(), loop_header, loop_header);
Node* exit =
graph()->NewNode(common()->LoopExitValue(MachineRepresentation::kWord64),
Int64Constant(value(2)), loop_exit);
LowerGraph(exit, MachineRepresentation::kWord64);
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsLoopExitValue(MachineRepresentation::kWord32,
IsInt32Constant(low_word_value(2))),
IsLoopExitValue(MachineRepresentation::kWord32,
IsInt32Constant(high_word_value(2))),
start(), start()));
}
TEST_F(Int64LoweringTest, WasmBigIntSpecialCaseBigIntToI64) {
Node* target = Int32Constant(1);
Node* context = Int32Constant(2);
Node* bigint = Int32Constant(4);
CallDescriptor* bigint_to_i64_call_descriptor =
Linkage::GetStubCallDescriptor(
zone(), // zone
BigIntToI64Descriptor(), // descriptor
BigIntToI64Descriptor()
.GetStackParameterCount(), // stack parameter count
CallDescriptor::kNoFlags, // flags
Operator::kNoProperties, // properties
StubCallMode::kCallCodeObject); // stub call mode
CallDescriptor* bigint_to_i32_pair_call_descriptor =
Linkage::GetStubCallDescriptor(
zone(), // zone
BigIntToI32PairDescriptor(), // descriptor
BigIntToI32PairDescriptor()
.GetStackParameterCount(), // stack parameter count
CallDescriptor::kNoFlags, // flags
Operator::kNoProperties, // properties
StubCallMode::kCallCodeObject); // stub call mode
auto lowering_special_case = std::make_unique<Int64LoweringSpecialCase>();
lowering_special_case->replacements.insert(
{bigint_to_i64_call_descriptor, bigint_to_i32_pair_call_descriptor});
Node* call_node =
graph()->NewNode(common()->Call(bigint_to_i64_call_descriptor), target,
bigint, context, start(), start());
LowerGraphWithSpecialCase(call_node, std::move(lowering_special_case),
MachineRepresentation::kWord64);
Capture<Node*> call;
Matcher<Node*> call_matcher =
IsCall(bigint_to_i32_pair_call_descriptor, target, bigint, context,
start(), start());
EXPECT_THAT(graph()->end()->InputAt(1),
IsReturn2(IsProjection(0, AllOf(CaptureEq(&call), call_matcher)),
IsProjection(1, AllOf(CaptureEq(&call), call_matcher)),
start(), start()));
}
TEST_F(Int64LoweringTest, WasmBigIntSpecialCaseI64ToBigInt) {
Node* target = Int32Constant(1);
Node* i64 = Int64Constant(value(0));
CallDescriptor* i64_to_bigint_call_descriptor =
Linkage::GetStubCallDescriptor(
zone(), // zone
I64ToBigIntDescriptor(), // descriptor
I64ToBigIntDescriptor()
.GetStackParameterCount(), // stack parameter count
CallDescriptor::kNoFlags, // flags
Operator::kNoProperties, // properties
StubCallMode::kCallCodeObject); // stub call mode
CallDescriptor* i32_pair_to_bigint_call_descriptor =
Linkage::GetStubCallDescriptor(
zone(), // zone
I32PairToBigIntDescriptor(), // descriptor
I32PairToBigIntDescriptor()
.GetStackParameterCount(), // stack parameter count
CallDescriptor::kNoFlags, // flags
Operator::kNoProperties, // properties
StubCallMode::kCallCodeObject); // stub call mode
auto lowering_special_case = std::make_unique<Int64LoweringSpecialCase>();
lowering_special_case->replacements.insert(
{i64_to_bigint_call_descriptor, i32_pair_to_bigint_call_descriptor});
Node* call = graph()->NewNode(common()->Call(i64_to_bigint_call_descriptor),
target, i64, start(), start());
LowerGraphWithSpecialCase(call, std::move(lowering_special_case),
MachineRepresentation::kTaggedPointer);
EXPECT_THAT(
graph()->end()->InputAt(1),
IsReturn(IsCall(i32_pair_to_bigint_call_descriptor, target,
IsInt32Constant(low_word_value(0)),
IsInt32Constant(high_word_value(0)), start(), start()),
start(), start()));
}
} // namespace compiler
} // namespace internal
} // namespace v8
| 43.972702 | 80 | 0.574618 | devcode1981 |
0483c71a08c462efdff09b7e55ba0614e1cdfc5d | 19,361 | cpp | C++ | DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/tinyclr/test/ssl_test_bf.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 529 | 2015-03-10T00:17:45.000Z | 2022-03-17T02:21:19.000Z | DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/tinyclr/test/ssl_test_bf.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 495 | 2015-03-10T22:02:46.000Z | 2019-05-16T13:05:00.000Z | DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/tinyclr/test/ssl_test_bf.cpp | PervasiveDigital/netmf-interpreter | 03d84fe76e0b666ebec62d17d69c55c45940bc40 | [
"Apache-2.0"
] | 332 | 2015-03-10T08:04:36.000Z | 2022-03-29T04:18:36.000Z | /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* This has been a quickly hacked 'ideatest.c'. When I add tests for other
* RC2 modes, more of the code will be uncommented. */
#include "ssl_tests.h"
#include <openssl/opensslconf.h> /* To see if OPENSSL_NO_BF is defined */
#ifdef OPENSSL_SYS_WINDOWS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#endif
#include "../e_os.h"
#ifdef OPENSSL_NO_BF
int ssl_test_bf(int argc, char *argv[])
{
TINYCLR_SSL_PRINTF("No BF support\n");
return(0);
}
#else
#include <openssl/blowfish.h>
#ifdef CHARSET_EBCDIC
#include <openssl/ebcdic.h>
#endif
static char *bf_key[2]={
"abcdefghijklmnopqrstuvwxyz",
"Who is John Galt?"
};
/* big endian */
static BF_LONG bf_plain[2][2]={
{0x424c4f57L,0x46495348L},
{0xfedcba98L,0x76543210L}
};
static BF_LONG bf_cipher[2][2]={
{0x324ed0feL,0xf413a203L},
{0xcc91732bL,0x8022f684L}
};
/************/
/* Lets use the DES test vectors :-) */
#define NUM_TESTS 34
static unsigned char ecb_data[NUM_TESTS][8]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10},
{0x7C,0xA1,0x10,0x45,0x4A,0x1A,0x6E,0x57},
{0x01,0x31,0xD9,0x61,0x9D,0xC1,0x37,0x6E},
{0x07,0xA1,0x13,0x3E,0x4A,0x0B,0x26,0x86},
{0x38,0x49,0x67,0x4C,0x26,0x02,0x31,0x9E},
{0x04,0xB9,0x15,0xBA,0x43,0xFE,0xB5,0xB6},
{0x01,0x13,0xB9,0x70,0xFD,0x34,0xF2,0xCE},
{0x01,0x70,0xF1,0x75,0x46,0x8F,0xB5,0xE6},
{0x43,0x29,0x7F,0xAD,0x38,0xE3,0x73,0xFE},
{0x07,0xA7,0x13,0x70,0x45,0xDA,0x2A,0x16},
{0x04,0x68,0x91,0x04,0xC2,0xFD,0x3B,0x2F},
{0x37,0xD0,0x6B,0xB5,0x16,0xCB,0x75,0x46},
{0x1F,0x08,0x26,0x0D,0x1A,0xC2,0x46,0x5E},
{0x58,0x40,0x23,0x64,0x1A,0xBA,0x61,0x76},
{0x02,0x58,0x16,0x16,0x46,0x29,0xB0,0x07},
{0x49,0x79,0x3E,0xBC,0x79,0xB3,0x25,0x8F},
{0x4F,0xB0,0x5E,0x15,0x15,0xAB,0x73,0xA7},
{0x49,0xE9,0x5D,0x6D,0x4C,0xA2,0x29,0xBF},
{0x01,0x83,0x10,0xDC,0x40,0x9B,0x26,0xD6},
{0x1C,0x58,0x7F,0x1C,0x13,0x92,0x4F,0xEF},
{0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01},
{0x1F,0x1F,0x1F,0x1F,0x0E,0x0E,0x0E,0x0E},
{0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1,0xFE},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10}};
static unsigned char plain_data[NUM_TESTS][8]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x01},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x01,0xA1,0xD6,0xD0,0x39,0x77,0x67,0x42},
{0x5C,0xD5,0x4C,0xA8,0x3D,0xEF,0x57,0xDA},
{0x02,0x48,0xD4,0x38,0x06,0xF6,0x71,0x72},
{0x51,0x45,0x4B,0x58,0x2D,0xDF,0x44,0x0A},
{0x42,0xFD,0x44,0x30,0x59,0x57,0x7F,0xA2},
{0x05,0x9B,0x5E,0x08,0x51,0xCF,0x14,0x3A},
{0x07,0x56,0xD8,0xE0,0x77,0x47,0x61,0xD2},
{0x76,0x25,0x14,0xB8,0x29,0xBF,0x48,0x6A},
{0x3B,0xDD,0x11,0x90,0x49,0x37,0x28,0x02},
{0x26,0x95,0x5F,0x68,0x35,0xAF,0x60,0x9A},
{0x16,0x4D,0x5E,0x40,0x4F,0x27,0x52,0x32},
{0x6B,0x05,0x6E,0x18,0x75,0x9F,0x5C,0xCA},
{0x00,0x4B,0xD6,0xEF,0x09,0x17,0x60,0x62},
{0x48,0x0D,0x39,0x00,0x6E,0xE7,0x62,0xF2},
{0x43,0x75,0x40,0xC8,0x69,0x8F,0x3C,0xFA},
{0x07,0x2D,0x43,0xA0,0x77,0x07,0x52,0x92},
{0x02,0xFE,0x55,0x77,0x81,0x17,0xF1,0x2A},
{0x1D,0x9D,0x5C,0x50,0x18,0xF7,0x28,0xC2},
{0x30,0x55,0x32,0x28,0x6D,0x6F,0x29,0x5A},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}};
static unsigned char cipher_data[NUM_TESTS][8]={
{0x4E,0xF9,0x97,0x45,0x61,0x98,0xDD,0x78},
{0x51,0x86,0x6F,0xD5,0xB8,0x5E,0xCB,0x8A},
{0x7D,0x85,0x6F,0x9A,0x61,0x30,0x63,0xF2},
{0x24,0x66,0xDD,0x87,0x8B,0x96,0x3C,0x9D},
{0x61,0xF9,0xC3,0x80,0x22,0x81,0xB0,0x96},
{0x7D,0x0C,0xC6,0x30,0xAF,0xDA,0x1E,0xC7},
{0x4E,0xF9,0x97,0x45,0x61,0x98,0xDD,0x78},
{0x0A,0xCE,0xAB,0x0F,0xC6,0xA0,0xA2,0x8D},
{0x59,0xC6,0x82,0x45,0xEB,0x05,0x28,0x2B},
{0xB1,0xB8,0xCC,0x0B,0x25,0x0F,0x09,0xA0},
{0x17,0x30,0xE5,0x77,0x8B,0xEA,0x1D,0xA4},
{0xA2,0x5E,0x78,0x56,0xCF,0x26,0x51,0xEB},
{0x35,0x38,0x82,0xB1,0x09,0xCE,0x8F,0x1A},
{0x48,0xF4,0xD0,0x88,0x4C,0x37,0x99,0x18},
{0x43,0x21,0x93,0xB7,0x89,0x51,0xFC,0x98},
{0x13,0xF0,0x41,0x54,0xD6,0x9D,0x1A,0xE5},
{0x2E,0xED,0xDA,0x93,0xFF,0xD3,0x9C,0x79},
{0xD8,0x87,0xE0,0x39,0x3C,0x2D,0xA6,0xE3},
{0x5F,0x99,0xD0,0x4F,0x5B,0x16,0x39,0x69},
{0x4A,0x05,0x7A,0x3B,0x24,0xD3,0x97,0x7B},
{0x45,0x20,0x31,0xC1,0xE4,0xFA,0xDA,0x8E},
{0x75,0x55,0xAE,0x39,0xF5,0x9B,0x87,0xBD},
{0x53,0xC5,0x5F,0x9C,0xB4,0x9F,0xC0,0x19},
{0x7A,0x8E,0x7B,0xFA,0x93,0x7E,0x89,0xA3},
{0xCF,0x9C,0x5D,0x7A,0x49,0x86,0xAD,0xB5},
{0xD1,0xAB,0xB2,0x90,0x65,0x8B,0xC7,0x78},
{0x55,0xCB,0x37,0x74,0xD1,0x3E,0xF2,0x01},
{0xFA,0x34,0xEC,0x48,0x47,0xB2,0x68,0xB2},
{0xA7,0x90,0x79,0x51,0x08,0xEA,0x3C,0xAE},
{0xC3,0x9E,0x07,0x2D,0x9F,0xAC,0x63,0x1D},
{0x01,0x49,0x33,0xE0,0xCD,0xAF,0xF6,0xE4},
{0xF2,0x1E,0x9A,0x77,0xB7,0x1C,0x49,0xBC},
{0x24,0x59,0x46,0x88,0x57,0x54,0x36,0x9A},
{0x6B,0x5C,0x5A,0x9C,0x5D,0x9E,0x0A,0x5A},
};
static unsigned char cbc_key [16]={
0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87};
static unsigned char cbc_iv [8]={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
static char cbc_data[40]="7654321 Now is the time for ";
static unsigned char cbc_ok[32]={
0x6B,0x77,0xB4,0xD6,0x30,0x06,0xDE,0xE6,
0x05,0xB1,0x56,0xE2,0x74,0x03,0x97,0x93,
0x58,0xDE,0xB9,0xE7,0x15,0x46,0x16,0xD9,
0x59,0xF1,0x65,0x2B,0xD5,0xFF,0x92,0xCC};
static unsigned char cfb64_ok[]={
0xE7,0x32,0x14,0xA2,0x82,0x21,0x39,0xCA,
0xF2,0x6E,0xCF,0x6D,0x2E,0xB9,0xE7,0x6E,
0x3D,0xA3,0xDE,0x04,0xD1,0x51,0x72,0x00,
0x51,0x9D,0x57,0xA6,0xC3};
static unsigned char ofb64_ok[]={
0xE7,0x32,0x14,0xA2,0x82,0x21,0x39,0xCA,
0x62,0xB3,0x43,0xCC,0x5B,0x65,0x58,0x73,
0x10,0xDD,0x90,0x8D,0x0C,0x24,0x1B,0x22,
0x63,0xC2,0xCF,0x80,0xDA};
#define KEY_TEST_NUM 25
static unsigned char key_test[KEY_TEST_NUM]={
0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,
0x78,0x69,0x5a,0x4b,0x3c,0x2d,0x1e,0x0f,
0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,
0x88};
static unsigned char key_data[8]=
{0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10};
static unsigned char key_out[KEY_TEST_NUM][8]={
{0xF9,0xAD,0x59,0x7C,0x49,0xDB,0x00,0x5E},
{0xE9,0x1D,0x21,0xC1,0xD9,0x61,0xA6,0xD6},
{0xE9,0xC2,0xB7,0x0A,0x1B,0xC6,0x5C,0xF3},
{0xBE,0x1E,0x63,0x94,0x08,0x64,0x0F,0x05},
{0xB3,0x9E,0x44,0x48,0x1B,0xDB,0x1E,0x6E},
{0x94,0x57,0xAA,0x83,0xB1,0x92,0x8C,0x0D},
{0x8B,0xB7,0x70,0x32,0xF9,0x60,0x62,0x9D},
{0xE8,0x7A,0x24,0x4E,0x2C,0xC8,0x5E,0x82},
{0x15,0x75,0x0E,0x7A,0x4F,0x4E,0xC5,0x77},
{0x12,0x2B,0xA7,0x0B,0x3A,0xB6,0x4A,0xE0},
{0x3A,0x83,0x3C,0x9A,0xFF,0xC5,0x37,0xF6},
{0x94,0x09,0xDA,0x87,0xA9,0x0F,0x6B,0xF2},
{0x88,0x4F,0x80,0x62,0x50,0x60,0xB8,0xB4},
{0x1F,0x85,0x03,0x1C,0x19,0xE1,0x19,0x68},
{0x79,0xD9,0x37,0x3A,0x71,0x4C,0xA3,0x4F},
{0x93,0x14,0x28,0x87,0xEE,0x3B,0xE1,0x5C},
{0x03,0x42,0x9E,0x83,0x8C,0xE2,0xD1,0x4B},
{0xA4,0x29,0x9E,0x27,0x46,0x9F,0xF6,0x7B},
{0xAF,0xD5,0xAE,0xD1,0xC1,0xBC,0x96,0xA8},
{0x10,0x85,0x1C,0x0E,0x38,0x58,0xDA,0x9F},
{0xE6,0xF5,0x1E,0xD7,0x9B,0x9D,0xB2,0x1F},
{0x64,0xA6,0xE1,0x4A,0xFD,0x36,0xB4,0x6F},
{0x80,0xC7,0xD7,0xD4,0x5A,0x54,0x79,0xAD},
{0x05,0x04,0x4B,0x62,0xFA,0x52,0xD0,0x80},
};
static int test(void );
static int print_test_data(void );
int ssl_test_bf(int argc, char *argv[])
{
int ret;
if (argc > 1)
ret=print_test_data();
else
ret=test();
#ifdef OPENSSL_SYS_NETWARE
if (ret) TINYCLR_SSL_PRINTF("ERROR: %d\n", ret);
#endif
return(ret);
}
static int print_test_data(void)
{
unsigned int i,j;
TINYCLR_SSL_PRINTF("ecb test data\n");
TINYCLR_SSL_PRINTF("key bytes\t\tclear bytes\t\tcipher bytes\n");
for (i=0; i<NUM_TESTS; i++)
{
for (j=0; j<8; j++)
TINYCLR_SSL_PRINTF("%02X",ecb_data[i][j]);
TINYCLR_SSL_PRINTF("\t");
for (j=0; j<8; j++)
TINYCLR_SSL_PRINTF("%02X",plain_data[i][j]);
TINYCLR_SSL_PRINTF("\t");
for (j=0; j<8; j++)
TINYCLR_SSL_PRINTF("%02X",cipher_data[i][j]);
TINYCLR_SSL_PRINTF("\n");
}
TINYCLR_SSL_PRINTF("set_key test data\n");
TINYCLR_SSL_PRINTF("data[8]= ");
for (j=0; j<8; j++)
TINYCLR_SSL_PRINTF("%02X",key_data[j]);
TINYCLR_SSL_PRINTF("\n");
for (i=0; i<KEY_TEST_NUM-1; i++)
{
TINYCLR_SSL_PRINTF("c=");
for (j=0; j<8; j++)
TINYCLR_SSL_PRINTF("%02X",key_out[i][j]);
TINYCLR_SSL_PRINTF(" k[%2u]=",i+1);
for (j=0; j<i+1; j++)
TINYCLR_SSL_PRINTF("%02X",key_test[j]);
TINYCLR_SSL_PRINTF("\n");
}
TINYCLR_SSL_PRINTF("\nchaining mode test data\n");
TINYCLR_SSL_PRINTF("key[16] = ");
for (j=0; j<16; j++)
TINYCLR_SSL_PRINTF("%02X",cbc_key[j]);
TINYCLR_SSL_PRINTF("\niv[8] = ");
for (j=0; j<8; j++)
TINYCLR_SSL_PRINTF("%02X",cbc_iv[j]);
TINYCLR_SSL_PRINTF("\ndata[%d] = '%s'",(int)TINYCLR_SSL_STRLEN(cbc_data)+1,cbc_data);
TINYCLR_SSL_PRINTF("\ndata[%d] = ",(int)TINYCLR_SSL_STRLEN(cbc_data)+1);
for (j=0; j<TINYCLR_SSL_STRLEN(cbc_data)+1; j++)
TINYCLR_SSL_PRINTF("%02X",cbc_data[j]);
TINYCLR_SSL_PRINTF("\n");
TINYCLR_SSL_PRINTF("cbc cipher text\n");
TINYCLR_SSL_PRINTF("cipher[%d]= ",32);
for (j=0; j<32; j++)
TINYCLR_SSL_PRINTF("%02X",cbc_ok[j]);
TINYCLR_SSL_PRINTF("\n");
TINYCLR_SSL_PRINTF("cfb64 cipher text\n");
TINYCLR_SSL_PRINTF("cipher[%d]= ",(int)TINYCLR_SSL_STRLEN(cbc_data)+1);
for (j=0; j<TINYCLR_SSL_STRLEN(cbc_data)+1; j++)
TINYCLR_SSL_PRINTF("%02X",cfb64_ok[j]);
TINYCLR_SSL_PRINTF("\n");
TINYCLR_SSL_PRINTF("ofb64 cipher text\n");
TINYCLR_SSL_PRINTF("cipher[%d]= ",(int)TINYCLR_SSL_STRLEN(cbc_data)+1);
for (j=0; j<TINYCLR_SSL_STRLEN(cbc_data)+1; j++)
TINYCLR_SSL_PRINTF("%02X",ofb64_ok[j]);
TINYCLR_SSL_PRINTF("\n");
return(0);
}
static int test(void)
{
unsigned char cbc_in[40],cbc_out[40],iv[8];
int i,n,err=0;
BF_KEY key;
BF_LONG data[2];
unsigned char out[8];
BF_LONG len;
#ifdef CHARSET_EBCDIC
ebcdic2ascii(cbc_data, cbc_data, TINYCLR_SSL_STRLEN(cbc_data));
#endif
TINYCLR_SSL_PRINTF("testing blowfish in raw ecb mode\n");
for (n=0; n<2; n++)
{
#ifdef CHARSET_EBCDIC
ebcdic2ascii(bf_key[n], bf_key[n], TINYCLR_SSL_STRLEN(bf_key[n]));
#endif
BF_set_key(&key,TINYCLR_SSL_STRLEN(bf_key[n]),(unsigned char *)bf_key[n]);
data[0]=bf_plain[n][0];
data[1]=bf_plain[n][1];
BF_encrypt(data,&key);
if (TINYCLR_SSL_MEMCMP(&(bf_cipher[n][0]),&(data[0]),8) != 0)
{
TINYCLR_SSL_PRINTF("BF_encrypt error encrypting\n");
TINYCLR_SSL_PRINTF("got :");
for (i=0; i<2; i++)
TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)data[i]);
TINYCLR_SSL_PRINTF("\n");
TINYCLR_SSL_PRINTF("expected:");
for (i=0; i<2; i++)
TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)bf_cipher[n][i]);
err=1;
TINYCLR_SSL_PRINTF("\n");
}
BF_decrypt(&(data[0]),&key);
if (TINYCLR_SSL_MEMCMP(&(bf_plain[n][0]),&(data[0]),8) != 0)
{
TINYCLR_SSL_PRINTF("BF_encrypt error decrypting\n");
TINYCLR_SSL_PRINTF("got :");
for (i=0; i<2; i++)
TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)data[i]);
TINYCLR_SSL_PRINTF("\n");
TINYCLR_SSL_PRINTF("expected:");
for (i=0; i<2; i++)
TINYCLR_SSL_PRINTF("%08lX ",(unsigned long)bf_plain[n][i]);
TINYCLR_SSL_PRINTF("\n");
err=1;
}
}
TINYCLR_SSL_PRINTF("testing blowfish in ecb mode\n");
for (n=0; n<NUM_TESTS; n++)
{
BF_set_key(&key,8,ecb_data[n]);
BF_ecb_encrypt(&(plain_data[n][0]),out,&key,BF_ENCRYPT);
if (TINYCLR_SSL_MEMCMP(&(cipher_data[n][0]),out,8) != 0)
{
TINYCLR_SSL_PRINTF("BF_ecb_encrypt blowfish error encrypting\n");
TINYCLR_SSL_PRINTF("got :");
for (i=0; i<8; i++)
TINYCLR_SSL_PRINTF("%02X ",out[i]);
TINYCLR_SSL_PRINTF("\n");
TINYCLR_SSL_PRINTF("expected:");
for (i=0; i<8; i++)
TINYCLR_SSL_PRINTF("%02X ",cipher_data[n][i]);
err=1;
TINYCLR_SSL_PRINTF("\n");
}
BF_ecb_encrypt(out,out,&key,BF_DECRYPT);
if (TINYCLR_SSL_MEMCMP(&(plain_data[n][0]),out,8) != 0)
{
TINYCLR_SSL_PRINTF("BF_ecb_encrypt error decrypting\n");
TINYCLR_SSL_PRINTF("got :");
for (i=0; i<8; i++)
TINYCLR_SSL_PRINTF("%02X ",out[i]);
TINYCLR_SSL_PRINTF("\n");
TINYCLR_SSL_PRINTF("expected:");
for (i=0; i<8; i++)
TINYCLR_SSL_PRINTF("%02X ",plain_data[n][i]);
TINYCLR_SSL_PRINTF("\n");
err=1;
}
}
TINYCLR_SSL_PRINTF("testing blowfish set_key\n");
for (n=1; n<KEY_TEST_NUM; n++)
{
BF_set_key(&key,n,key_test);
BF_ecb_encrypt(key_data,out,&key,BF_ENCRYPT);
/* mips-sgi-irix6.5-gcc vv -mabi=64 bug workaround */
if (TINYCLR_SSL_MEMCMP(out,&(key_out[i=n-1][0]),8) != 0)
{
TINYCLR_SSL_PRINTF("blowfish setkey error\n");
err=1;
}
}
TINYCLR_SSL_PRINTF("testing blowfish in cbc mode\n");
len=TINYCLR_SSL_STRLEN(cbc_data)+1;
BF_set_key(&key,16,cbc_key);
TINYCLR_SSL_MEMSET(cbc_in,0,sizeof cbc_in);
TINYCLR_SSL_MEMSET(cbc_out,0,sizeof cbc_out);
TINYCLR_SSL_MEMCPY(iv,cbc_iv,sizeof iv);
BF_cbc_encrypt((unsigned char *)cbc_data,cbc_out,len,
&key,iv,BF_ENCRYPT);
if (TINYCLR_SSL_MEMCMP(cbc_out,cbc_ok,32) != 0)
{
err=1;
TINYCLR_SSL_PRINTF("BF_cbc_encrypt encrypt error\n");
for (i=0; i<32; i++) TINYCLR_SSL_PRINTF("0x%02X,",cbc_out[i]);
}
TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
BF_cbc_encrypt(cbc_out,cbc_in,len,
&key,iv,BF_DECRYPT);
if (TINYCLR_SSL_MEMCMP(cbc_in,cbc_data,TINYCLR_SSL_STRLEN(cbc_data)+1) != 0)
{
TINYCLR_SSL_PRINTF("BF_cbc_encrypt decrypt error\n");
err=1;
}
TINYCLR_SSL_PRINTF("testing blowfish in cfb64 mode\n");
BF_set_key(&key,16,cbc_key);
TINYCLR_SSL_MEMSET(cbc_in,0,40);
TINYCLR_SSL_MEMSET(cbc_out,0,40);
TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
n=0;
BF_cfb64_encrypt((unsigned char *)cbc_data,cbc_out,(long)13,
&key,iv,&n,BF_ENCRYPT);
BF_cfb64_encrypt((unsigned char *)&(cbc_data[13]),&(cbc_out[13]),len-13,
&key,iv,&n,BF_ENCRYPT);
if (TINYCLR_SSL_MEMCMP(cbc_out,cfb64_ok,(int)len) != 0)
{
err=1;
TINYCLR_SSL_PRINTF("BF_cfb64_encrypt encrypt error\n");
for (i=0; i<(int)len; i++) TINYCLR_SSL_PRINTF("0x%02X,",cbc_out[i]);
}
n=0;
TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
BF_cfb64_encrypt(cbc_out,cbc_in,17,
&key,iv,&n,BF_DECRYPT);
BF_cfb64_encrypt(&(cbc_out[17]),&(cbc_in[17]),len-17,
&key,iv,&n,BF_DECRYPT);
if (TINYCLR_SSL_MEMCMP(cbc_in,cbc_data,(int)len) != 0)
{
TINYCLR_SSL_PRINTF("BF_cfb64_encrypt decrypt error\n");
err=1;
}
TINYCLR_SSL_PRINTF("testing blowfish in ofb64\n");
BF_set_key(&key,16,cbc_key);
TINYCLR_SSL_MEMSET(cbc_in,0,40);
TINYCLR_SSL_MEMSET(cbc_out,0,40);
TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
n=0;
BF_ofb64_encrypt((unsigned char *)cbc_data,cbc_out,(long)13,&key,iv,&n);
BF_ofb64_encrypt((unsigned char *)&(cbc_data[13]),
&(cbc_out[13]),len-13,&key,iv,&n);
if (TINYCLR_SSL_MEMCMP(cbc_out,ofb64_ok,(int)len) != 0)
{
err=1;
TINYCLR_SSL_PRINTF("BF_ofb64_encrypt encrypt error\n");
for (i=0; i<(int)len; i++) TINYCLR_SSL_PRINTF("0x%02X,",cbc_out[i]);
}
n=0;
TINYCLR_SSL_MEMCPY(iv,cbc_iv,8);
BF_ofb64_encrypt(cbc_out,cbc_in,17,&key,iv,&n);
BF_ofb64_encrypt(&(cbc_out[17]),&(cbc_in[17]),len-17,&key,iv,&n);
if (TINYCLR_SSL_MEMCMP(cbc_in,cbc_data,(int)len) != 0)
{
TINYCLR_SSL_PRINTF("BF_ofb64_encrypt decrypt error\n");
err=1;
}
return(err);
}
#endif
| 35.655617 | 88 | 0.690564 | PervasiveDigital |
0487efeed9420e29e974d27a03d09e85207a9f99 | 1,833 | cc | C++ | inet/src/inet/common/packet/serializer/ByteCountChunkSerializer.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | null | null | null | inet/src/inet/common/packet/serializer/ByteCountChunkSerializer.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | null | null | null | inet/src/inet/common/packet/serializer/ByteCountChunkSerializer.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | 1 | 2021-07-02T13:32:40.000Z | 2021-07-02T13:32:40.000Z | //
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "inet/common/packet/chunk/ByteCountChunk.h"
#include "inet/common/packet/serializer/ByteCountChunkSerializer.h"
#include "inet/common/packet/serializer/ChunkSerializerRegistry.h"
namespace inet {
Register_Serializer(ByteCountChunk, ByteCountChunkSerializer);
void ByteCountChunkSerializer::serialize(MemoryOutputStream& stream, const Ptr<const Chunk>& chunk, b offset, b length) const
{
const auto& byteCountChunk = staticPtrCast<const ByteCountChunk>(chunk);
b serializedLength = length == b(-1) ? byteCountChunk->getChunkLength() - offset : length;
stream.writeByteRepeatedly(byteCountChunk->getData(), B(serializedLength).get());
ChunkSerializer::totalSerializedLength += serializedLength;
}
const Ptr<Chunk> ByteCountChunkSerializer::deserialize(MemoryInputStream& stream, const std::type_info& typeInfo) const
{
auto byteCountChunk = makeShared<ByteCountChunk>();
B length = stream.getRemainingLength();
stream.readByteRepeatedly(byteCountChunk->getData(), B(length).get());
byteCountChunk->setLength(length);
ChunkSerializer::totalDeserializedLength += length;
return byteCountChunk;
}
} // namespace
| 42.627907 | 125 | 0.768685 | ntanetani |
048b6443cb65226507f2eb3a756a64ed299e984d | 2,973 | cpp | C++ | test/glfw/glfw.cpp | 10110111/GLFFT | 78176d4480bc3675327bf2bcfd80d5dae1820081 | [
"MIT"
] | 176 | 2015-08-17T20:47:10.000Z | 2022-03-30T09:14:33.000Z | test/glfw/glfw.cpp | 10110111/GLFFT | 78176d4480bc3675327bf2bcfd80d5dae1820081 | [
"MIT"
] | 6 | 2017-09-21T15:55:44.000Z | 2020-11-07T03:15:44.000Z | test/glfw/glfw.cpp | 10110111/GLFFT | 78176d4480bc3675327bf2bcfd80d5dae1820081 | [
"MIT"
] | 28 | 2016-02-28T04:37:50.000Z | 2022-02-27T12:35:55.000Z | /* Copyright (C) 2015 Hans-Kristian Arntzen <maister@archlinux.us>
*
* 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 "glfft_gl_interface.hpp"
#include "glfft_context.hpp"
using namespace GLFFT;
using namespace std;
#ifdef GLFFT_GL_DEBUG
static void APIENTRY gl_debug_cb(GLenum, GLenum, GLuint, GLenum, GLsizei,
const GLchar *message, void*)
{
glfft_log("GLDEBUG: %s.\n", message);
}
#endif
struct GLFWContext : GLContext
{
~GLFWContext()
{
if (window)
{
teardown();
glfwDestroyWindow(window);
glfwTerminate();
}
}
GLFWwindow *window = nullptr;
bool supports_texture_readback() override { return true; }
void read_texture(void *buffer, Texture *texture, Format format) override
{
glBindTexture(GL_TEXTURE_2D, static_cast<GLTexture*>(texture)->get());
glGetTexImage(GL_TEXTURE_2D, 0, convert_format(format), convert_type(format), buffer);
glBindTexture(GL_TEXTURE_2D, 0);
}
};
unique_ptr<Context> GLFFT::create_cli_context()
{
if (!glfwInit())
{
return nullptr;
}
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
unique_ptr<GLFWContext> context(new GLFWContext);
context->window = glfwCreateWindow(128, 128, "GLFFT Test", nullptr, nullptr);
if (!context->window)
{
glfwTerminate();
return nullptr;
}
glfwMakeContextCurrent(context->window);
rglgen_resolve_symbols(glfwGetProcAddress);
#ifdef GLFFT_GL_DEBUG
glDebugMessageCallback(gl_debug_cb, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
#endif
return unique_ptr<Context>(move(context));
}
| 33.404494 | 129 | 0.722503 | 10110111 |
048d7411d88c4df2342b348703c0f7329f6360f7 | 7,964 | hpp | C++ | OptFrame/MultiEvaluator.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 2 | 2018-05-24T11:04:12.000Z | 2020-03-03T13:37:07.000Z | OptFrame/MultiEvaluator.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | null | null | null | OptFrame/MultiEvaluator.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 1 | 2019-06-06T16:57:49.000Z | 2019-06-06T16:57:49.000Z | // OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_MULTI_EVALUATOR_HPP_
#define OPTFRAME_MULTI_EVALUATOR_HPP_
#include <iostream>
#include "Solution.hpp"
#include "Evaluator.hpp"
#include "MultiEvaluation.hpp"
#include "MultiDirection.hpp"
#include "Action.hpp"
using namespace std;
using namespace scannerpp;
namespace optframe
{
template<class R, class ADS = OPTFRAME_DEFAULT_ADS>
class MultiEvaluator: public MultiDirection
{
protected:
vector<Evaluator<R, ADS>*> sngEvaluators; // single evaluators
bool allowCosts; // move.cost() is enabled or disabled for this Evaluator
public:
MultiEvaluator(vector<Evaluator<R, ADS>*> _veval) :
sngEvaluators(_veval), allowCosts(false)
{
for (unsigned i = 0; i < _veval.size(); i++)
if (_veval[i])
vDir.push_back(_veval[i]);
nObjectives = vDir.size();
}
MultiEvaluator(bool _allowCosts = false) :
allowCosts(_allowCosts)
{
}
virtual void addEvaluator(Evaluator<R, ADS>& ev)
{
sngEvaluators.push_back(&ev);
}
// MultiEvaluator(MultiDirection& mDir, bool _allowCosts = false) :
// MultiDirection(mDir), allowCosts(_allowCosts)
// {
// }
//
// MultiEvaluator(vector<Direction*>& vDir, bool _allowCosts = false) :
// MultiDirection(vDir), allowCosts(_allowCosts)
// {
// }
// MultiEvaluator(MultiEvaluator<R, ADS>& _mev) :
// sngEvaluators(*_mev.getEvaluators2()), allowCosts(false)
// {
// cout<<"sngEvaluators.size():"<<sngEvaluators.size()<<endl;
// for (unsigned i = 0; i < sngEvaluators.size(); i++)
// if (sngEvaluators[i])
// vDir.push_back(sngEvaluators[i]);
// nObjectives = vDir.size();
// }
virtual ~MultiEvaluator()
{
}
unsigned size()
{
return sngEvaluators.size();
}
unsigned size() const
{
return sngEvaluators.size();
}
virtual bool betterThan(const Evaluation& ev1, const Evaluation& ev2, int index)
{
return sngEvaluators[index]->betterThan(ev1, ev2);
}
virtual bool equals(const Evaluation& ev1, const Evaluation& ev2, int index)
{
return sngEvaluators[index]->equals(ev1, ev2);
}
MultiEvaluation evaluateSolution(const Solution<R, ADS>& s)
{
return evaluate(s.getR(), s.getADSptr());
}
//changed to Meval without point TODO
virtual MultiEvaluation evaluate(const R& r, const ADS* ads)
{
cout << "inside mother class" << endl;
getchar();
MultiEvaluation nev;
for (unsigned i = 0; i < sngEvaluators.size(); i++)
{
Evaluation ev = sngEvaluators[i]->evaluate(r, ads);
nev.addEvaluation(ev);
}
return nev;
}
void clear()
{
for (int e = 0; e < int(sngEvaluators.size()); e++)
delete sngEvaluators[e];
}
void reevaluateSolutionMEV(MultiEvaluation& mev, const Solution<R, ADS>& s)
{
reevaluateMEV(mev, s.getR(),s.getADSptr());
}
virtual void reevaluateMEV(MultiEvaluation& mev, const R& r, const ADS* ads)
{
for (unsigned i = 0; i < sngEvaluators.size(); i++)
{
Evaluation e = std::move(mev[i]);
sngEvaluators[i]->reevaluate(e, r, ads);
mev[i] = std::move(e);
}
}
// bool getAllowCosts()
// {
// return allowCosts;
// }
// vector<Evaluator<R, ADS>*> getEvaluators2()
// {
// return sngEvaluators;
// }
// // TODO: check
// const vector<const Evaluator<R, ADS>*>* getEvaluatorsConstTest() const
// {
// if (sngEvaluators.size() > 0)
// return new vector<const Evaluator<R, ADS>*>(sngEvaluators);
// else
// return nullptr;
// }
// Evaluator<R, ADS>& at(unsigned index)
// {
// return *sngEvaluators.at(index);
// }
//
// const Evaluator<R, ADS>& at(unsigned index) const
// {
// return *sngEvaluators.at(index);
// }
//
// Evaluator<R, ADS>& operator[](unsigned index)
// {
// return *sngEvaluators[index];
// }
//
// const Evaluator<R, ADS>& operator[](unsigned index) const
// {
// return *sngEvaluators[index];
// }
// void addEvaluator(const Evaluator<R, ADS>& ev)
// {
// sngEvaluators.push_back(&ev.clone());
// }
protected:
// ============= Component ===============
virtual bool compatible(string s)
{
return (s == idComponent()) || (MultiDirection::compatible(s));
}
static string idComponent()
{
stringstream ss;
ss << MultiDirection::idComponent() << ":MultiEvaluator";
return ss.str();
}
virtual string id() const
{
return idComponent();
}
};
template<class R, class ADS = OPTFRAME_DEFAULT_ADS>
class MultiEvaluatorAction: public Action<R, ADS>
{
public:
virtual ~MultiEvaluatorAction()
{
}
virtual string usage()
{
return ":MultiEvaluator idx evaluate :Solution idx [output_variable] => OptFrame:Evaluation";
}
virtual bool handleComponent(string type)
{
return Component::compareBase(MultiEvaluator<R, ADS>::idComponent(), type);
}
virtual bool handleComponent(Component& component)
{
return component.compatible(MultiEvaluator<R, ADS>::idComponent());
}
virtual bool handleAction(string action)
{
return (action == "evaluate"); //|| (action == "betterThan") || (action == "betterOrEquals");
}
virtual bool doCast(string component, int id, string type, string variable, HeuristicFactory<R, ADS>& hf, map<string, string>& d)
{
cout << "MultiEvaluator::doCast: NOT IMPLEMENTED!" << endl;
return false;
if (!handleComponent(type))
{
cout << "EvaluatorAction::doCast error: can't handle component type '" << type << " " << id << "'" << endl;
return false;
}
Component* comp = hf.components[component].at(id);
if (!comp)
{
cout << "EvaluatorAction::doCast error: nullptr component '" << component << " " << id << "'" << endl;
return false;
}
if (!Component::compareBase(comp->id(), type))
{
cout << "EvaluatorAction::doCast error: component '" << comp->id() << " is not base of " << type << "'" << endl;
return false;
}
// remove old component from factory
hf.components[component].at(id) = nullptr;
// cast object to lower type
Component* final = nullptr;
if (type == Evaluator<R, ADS>::idComponent())
{
final = (Evaluator<R, ADS>*) comp;
}
else
{
cout << "EvaluatorAction::doCast error: no cast for type '" << type << "'" << endl;
return false;
}
// add new component
Scanner scanner(variable);
return ComponentAction<R, ADS>::addAndRegister(scanner, *final, hf, d);
}
virtual bool doAction(string content, HeuristicFactory<R, ADS>& hf, map<string, string>& dictionary, map<string, vector<string> >& ldictionary)
{
cout << "MultiEvaluator::doAction: NOT IMPLEMENTED!" << endl;
return false;
//cout << "Evaluator::doAction '" << content << "'" << endl;
Scanner scanner(content);
if (!scanner.hasNext())
return false;
Evaluator<R, ADS>* ev;
hf.assign(ev, scanner.nextInt(), scanner.next());
if (!ev)
return false;
if (!scanner.hasNext())
return false;
string action = scanner.next();
if (!handleAction(action))
return false;
if (action == "evaluate")
{
if (!scanner.hasNext())
return false;
Solution<R, ADS>* s;
hf.assign(s, scanner.nextInt(), scanner.next());
if (!s)
return false;
Evaluation& e = ev->evaluate(*s);
return Action<R, ADS>::addAndRegister(scanner, e, hf, dictionary);
}
// no action found!
return false;
}
};
}
#endif /*OPTFRAME_MULTI_EVALUATOR_HPP_*/
| 22.951009 | 144 | 0.668634 | 216k155 |
0491938f8790fc8811dbe25b09a6aa1741dc3636 | 723 | cpp | C++ | src/BinaryTreeLevelOrderTraversal.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | src/BinaryTreeLevelOrderTraversal.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | src/BinaryTreeLevelOrderTraversal.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "BinaryTreeLevelOrderTraversal.hpp"
#include <queue>
using namespace std;
vector<vector<int>> BinaryTreeLevelOrderTraversal::levelOrder(TreeNode *root) {
vector<vector<int>> ret;
queue<TreeNode *> q;
if (root != nullptr) q.push(root);
while (!q.empty()) {
int n = q.size();
vector<int> newlevel(n);
for (int i = 0; i < n; i++) {
TreeNode *current = q.front();
q.pop();
newlevel[i] = current->val;
if (current->left != nullptr)
q.push(current->left);
if (current->right != nullptr)
q.push(current->right);
}
ret.push_back(newlevel);
}
return ret;
}
| 21.264706 | 79 | 0.53112 | yanzhe-chen |
049576575aa6e0efe7a7a429772f51232c01c574 | 2,826 | cpp | C++ | src/UbGraphicsScene.cpp | cadet/UberCode | 19d70134774dfae607b18b5185ad93e5b2cf7cfe | [
"Apache-2.0"
] | 1 | 2016-10-31T13:05:30.000Z | 2016-10-31T13:05:30.000Z | src/UbGraphicsScene.cpp | cadet/UberCode | 19d70134774dfae607b18b5185ad93e5b2cf7cfe | [
"Apache-2.0"
] | null | null | null | src/UbGraphicsScene.cpp | cadet/UberCode | 19d70134774dfae607b18b5185ad93e5b2cf7cfe | [
"Apache-2.0"
] | null | null | null | /*
CADET - Center for Advances in Digital Entertainment Technologies
Copyright 2011 Fachhochschule Salzburg GmbH
http://www.cadet.at
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 "UbGraphicsScene.h"
#include "BlockNavigationTreeWidget.h"
#include "DataflowEngineManager.h"
namespace Uber {
UbGraphicsScene::UbGraphicsScene()
{
initialize();
}
UbGraphicsScene::~UbGraphicsScene()
{
}
void UbGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
{
//std::cout << " drag enter scene" << std::endl;
BlockNavigationTreeWidget* source = qobject_cast<BlockNavigationTreeWidget *>(event->source());
event->setAccepted(true);
if(source)
{
event->setAccepted(true);
}
else
{
event->setAccepted(false);
}
}
void UbGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent* event)
{
//std::cout << " drag move scene" << std::endl;
BlockNavigationTreeWidget* source = qobject_cast<BlockNavigationTreeWidget *>(event->source());
event->setAccepted(true);
if(source)
{
event->setAccepted(true);
}
else
{
event->setAccepted(false);
}
}
void UbGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent* event)
{
//std::cout << " drag drop scene" << std::endl;
QString blockName = event->mimeData()->text();
DataflowEngineManager::getInstance()->getComposition()->addBlock(blockName, event->scenePos());
event->acceptProposedAction();
}
void UbGraphicsScene::initialize()
{
//setSceneRect(0,0,640, 480);
}
void UbGraphicsScene::addItem( UbObject * item )
{
m_Items.push_back(item);
QGraphicsScene::addItem(item);
}
void UbGraphicsScene::removeUbObject( UbObject * item )
{
int tt = item->type();
QGraphicsScene::removeItem(item);
QList<UbObject*>::iterator iter = m_Items.begin();
for ( ;iter!=m_Items.end(); )
{
if ( *iter==item )
{
iter = m_Items.erase(iter);
if ( item->type()==BundleBlockType )
{
UbBundleBlock *obj = static_cast<UbBundleBlock*>(item);
obj->getHandle().kill();
}
delete item;
break;
}
else {
++iter;
}
}
}
UbObject* UbGraphicsScene::getNamedItem( QString name )
{
QList<UbObject*>::iterator iter = m_Items.begin();
for ( ;iter!=m_Items.end(); ++iter )
{
if ( (*iter)->getName() == name )
{
return *iter;
}
}
return NULL;
}
} | 23.747899 | 97 | 0.691083 | cadet |
049967f9b38881ce18df1aae86d3ea9d849fed35 | 1,722 | cpp | C++ | src/OpenLoco/Drawing/FPSCounter.cpp | ser-pounce/OpenLoco | f280941bc535c1a681e65420c312c1815a17c1fe | [
"MIT"
] | 1 | 2020-05-23T20:17:13.000Z | 2020-05-23T20:17:13.000Z | src/OpenLoco/Drawing/FPSCounter.cpp | ser-pounce/OpenLoco | f280941bc535c1a681e65420c312c1815a17c1fe | [
"MIT"
] | null | null | null | src/OpenLoco/Drawing/FPSCounter.cpp | ser-pounce/OpenLoco | f280941bc535c1a681e65420c312c1815a17c1fe | [
"MIT"
] | null | null | null | #include "FPSCounter.h"
#include "../Graphics/Colour.h"
#include "../Graphics/Gfx.h"
#include "../Localisation/StringManager.h"
#include "../Ui.h"
#include <chrono>
#include <stdio.h>
namespace OpenLoco::Drawing
{
using Clock_t = std::chrono::high_resolution_clock;
using TimePoint_t = Clock_t::time_point;
static TimePoint_t _referenceTime;
static uint32_t _currentFrameCount;
static float _currentFPS;
static float measureFPS()
{
_currentFrameCount++;
auto currentTime = Clock_t::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - _referenceTime).count() / 1000.0;
if (elapsed > 1.0)
{
_currentFPS = _currentFrameCount / elapsed;
_currentFrameCount = 0;
_referenceTime = currentTime;
}
return _currentFPS;
}
void drawFPS()
{
// Measure FPS
const float fps = measureFPS();
// Format string
char buffer[64];
buffer[0] = ControlCodes::font_bold;
buffer[1] = ControlCodes::outline;
buffer[2] = ControlCodes::colour_white;
const char* formatString = (_currentFPS >= 10.0f ? "%.0f" : "%.1f");
snprintf(&buffer[3], std::size(buffer) - 3, formatString, fps);
auto& context = Gfx::screenContext();
// Draw text
const int stringWidth = Gfx::getStringWidth(buffer);
const auto x = Ui::width() / 2 - (stringWidth / 2);
const auto y = 2;
Gfx::drawString(&context, x, y, Colour::black, buffer);
// Make area dirty so the text doesn't get drawn over the last
Gfx::setDirtyBlocks(x - 16, y - 4, x + 16, 16);
}
}
| 27.774194 | 124 | 0.60453 | ser-pounce |
049c74bf08b1b4060c78a7203fb84df6d1b33c85 | 854 | hpp | C++ | src/components/MenuBase.hpp | ryanreno/spacewar | 3b154b3dfbf2cc8b657f89fc7c328d3713ca3be7 | [
"MIT"
] | 1 | 2021-06-24T13:31:37.000Z | 2021-06-24T13:31:37.000Z | src/components/MenuBase.hpp | ryanreno/spacewar | 3b154b3dfbf2cc8b657f89fc7c328d3713ca3be7 | [
"MIT"
] | 1 | 2021-07-02T19:26:36.000Z | 2021-07-02T19:26:36.000Z | src/components/MenuBase.hpp | ryanreno/spacewar | 3b154b3dfbf2cc8b657f89fc7c328d3713ca3be7 | [
"MIT"
] | 1 | 2021-07-02T17:07:41.000Z | 2021-07-02T17:07:41.000Z | /**
* @file
*
* $Id: MenuBase.hpp $
* @author Bill Eggert
*/
#pragma once
#include <entityx/Event.h>
#include <SFML/Graphics.hpp>
/*
* Base class for menus. These are the actual things that do the work.
* The "Menu" class is the component.
*/
class MenuBase
{
public:
virtual ~MenuBase() = default;
virtual void update(entityx::EventManager &events, float dt) = 0;
virtual void draw(sf::RenderWindow &window, const sf::Vector2f &pos) = 0;
virtual void select(entityx::EventManager &eventManager) = 0;
virtual void cancel(entityx::EventManager &eventManager) = 0;
virtual void up(entityx::EventManager &eventManager) = 0;
virtual void down(entityx::EventManager &eventManager) = 0;
virtual void left(entityx::EventManager &eventManager) = 0;
virtual void right(entityx::EventManager &eventManager) = 0;
};
| 26.6875 | 77 | 0.69555 | ryanreno |
049d5ffc794faa0407674e18cb0b89b97dbc2c21 | 240 | cpp | C++ | docs/atl-mfc-shared/codesnippet/CPP/ctime-class_10.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/atl-mfc-shared/codesnippet/CPP/ctime-class_10.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 3,272 | 2017-06-24T00:26:34.000Z | 2022-03-31T22:14:07.000Z | docs/atl-mfc-shared/codesnippet/CPP/ctime-class_10.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | // Example for CTime::GetHour, CTime::GetMinute, and CTime::GetSecond
CTime t(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999
ATLASSERT(t.GetSecond() == 0);
ATLASSERT(t.GetMinute() == 15);
ATLASSERT(t.GetHour() == 22); | 48 | 72 | 0.616667 | bobbrow |
049f5638256314a9b2650d3bb8727687ca7ad5b3 | 1,797 | cpp | C++ | codechef/SWAPPALI/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codechef/SWAPPALI/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codechef/SWAPPALI/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 29-02-2020 22:17:56
* solution_verdict: Accepted language: C++14
* run_time: 0.00 sec memory_used: 15.2M
* problem: https://www.codechef.com/LTIME81A/problems/SWAPPALI
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int t;cin>>t;
while(t--)
{
int n;string s;cin>>n>>s;
int i=0,j=n-1;
int ans=0,l=-1,r=n+1;
while(true)
{
if(i==j)break;
if(j-i==1)
{
if(s[i]==s[j])break;
else {ans=-1;break;}
}
if(j-i==2)
{
if(s[i]==s[i+2])break;
if((s[i]!=s[i+1])&&(s[i]!=s[i+2])&&(s[i+1]!=s[i+2])){ans=-1;break;}
//cout<<l<<" "<<r<<" "<<i<<" "<<j<<endl;
if(s[j]==s[j-1]&&l>=i){ans=-1;break;}
if(s[i]==s[i+1]&&r<=j){ans=-1;break;}
ans++;break;
}
if(s[i]==s[j])
{
i++,j--;continue;
}
if(s[i+1]==s[j]&&l<i)
{
ans++;swap(s[i],s[i+1]);l=i+1;
}
else if(s[j-1]==s[i]&&r>j)
{
ans++;swap(s[j],s[j-1]);r=j-1;
}
else {ans=-1;break;}
i++;j--;
//cout<<s<<endl;
//cout<<i<<" "<<j<<endl;
}
if(ans==-1)cout<<"NO\n";
else cout<<"YES\n"<<ans<<"\n";
//cout<<ans<<"\n";
}
return 0;
} | 30.457627 | 111 | 0.333333 | kzvd4729 |
04a431d5306d6f19238fd8fa9611830be3dde60b | 451 | cpp | C++ | UnrealPakViewer/UnrealPakViewer/Private/ViewModels/WidgetDelegates.cpp | kakacoding/pkg-doctor | 4d6f860763d1499a15ed6b762d938713bc67a841 | [
"MIT"
] | 128 | 2021-06-25T10:20:19.000Z | 2022-03-30T09:49:14.000Z | UnrealPakViewer/UnrealPakViewer/Private/ViewModels/WidgetDelegates.cpp | kakacoding/pkg-doctor | 4d6f860763d1499a15ed6b762d938713bc67a841 | [
"MIT"
] | 5 | 2021-06-29T09:04:13.000Z | 2022-03-07T03:13:23.000Z | UnrealPakViewer/UnrealPakViewer/Private/ViewModels/WidgetDelegates.cpp | kakacoding/pkg-doctor | 4d6f860763d1499a15ed6b762d938713bc67a841 | [
"MIT"
] | 16 | 2021-06-29T01:28:57.000Z | 2022-03-09T09:53:20.000Z | #include "WidgetDelegates.h"
FOnSwitchToTreeView& FWidgetDelegates::GetOnSwitchToTreeViewDelegate()
{
static FOnSwitchToTreeView Delegate;
return Delegate;
}
FOnSwitchToFileView& FWidgetDelegates::GetOnSwitchToFileViewDelegate()
{
static FOnSwitchToFileView Delegate;
return Delegate;
}
FOnLoadAssetRegistryFinished& FWidgetDelegates::GetOnLoadAssetRegistryFinishedDelegate()
{
static FOnLoadAssetRegistryFinished Delegate;
return Delegate;
} | 23.736842 | 88 | 0.849224 | kakacoding |
04a49b4df8bc5e01416e2904824e65e0de3a1772 | 5,200 | cpp | C++ | libs/common/x86/src/sync/ticket.lock.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 32 | 2015-09-02T22:56:22.000Z | 2021-02-24T17:15:50.000Z | libs/common/x86/src/sync/ticket.lock.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 30 | 2015-04-26T18:35:07.000Z | 2021-06-06T09:57:02.000Z | libs/common/x86/src/sync/ticket.lock.cpp | vercas/Beelzebub | 9d0e4790060b313c6681ca7e478d08d3910332b0 | [
"NCSA"
] | 11 | 2015-09-03T20:47:41.000Z | 2021-06-25T17:00:01.000Z | /*
Copyright (c) 2015 Alexandru-Mihai Maftei. All rights reserved.
Developed by: Alexandru-Mihai Maftei
aka Vercas
http://vercas.com | https://github.com/vercas/Beelzebub
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal with 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:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of Alexandru-Mihai Maftei, Vercas, nor the names of
its contributors may be used to endorse or promote products derived from
this Software without specific prior written permission.
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
CONTRIBUTORS 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
WITH THE SOFTWARE.
---
You may also find the text of this license in "LICENSE.md", along with a more
thorough explanation regarding other files.
*/
#include <beel/sync/ticket.lock.hpp>
#include <debug.hpp>
using namespace Beelzebub::Synchronization;
/************************
TicketLock struct
************************/
#ifdef __BEELZEBUB__CONF_DEBUG
/* Destructor */
#if defined(__BEELZEBUB_SETTINGS_NO_SMP)
TicketLock<false>::~TicketLock()
#else
template<bool SMP>
TicketLock<SMP>::~TicketLock()
#endif
{
assert(this->Check(), "TicketLock @ %Xp was destructed while busy!", this);
//this->Release();
}//*/
#endif
#ifdef __BEELZEBUB_SETTINGS_NO_INLINE_SPINLOCKS
/* Operations */
#if defined(__BEELZEBUB_SETTINGS_NO_SMP)
bool TicketLock<false>::TryAcquire() volatile
#else
template<bool SMP>
bool TicketLock<SMP>::TryAcquire() volatile
#endif
{
uint16_t const oldTail = this->Value.Tail;
ticketlock_t cmp {oldTail, oldTail};
ticketlock_t const newVal {oldTail, (uint16_t)(oldTail + 1)};
ticketlock_t const cmpCpy = cmp;
asm volatile( "lock cmpxchgl %[newVal], %[curVal] \n\t"
: [curVal]"+m"(this->Value), "+a"(cmp)
: [newVal]"r"(newVal)
: "cc" );
return cmp.Overall == cmpCpy.Overall;
}
#if defined(__BEELZEBUB_SETTINGS_NO_SMP)
void TicketLock<false>::Spin() const volatile
#else
template<bool SMP>
void TicketLock<SMP>::Spin() const volatile
#endif
{
ticketlock_t copy;
do
{
copy = {this->Value.Overall};
DO_NOTHING();
} while (copy.Tail != copy.Head);
}
#if defined(__BEELZEBUB_SETTINGS_NO_SMP)
void TicketLock<false>::Await() const volatile
#else
template<bool SMP>
void TicketLock<SMP>::Await() const volatile
#endif
{
ticketlock_t copy = {this->Value.Overall};
while (copy.Tail != copy.Head)
{
DO_NOTHING();
copy = {this->Value.Overall};
}
}
#if defined(__BEELZEBUB_SETTINGS_NO_SMP)
void TicketLock<false>::Acquire() volatile
#else
template<bool SMP>
void TicketLock<SMP>::Acquire() volatile
#endif
{
uint16_t myTicket = 1;
asm volatile( "lock xaddw %[ticket], %[tail] \n\t"
: [tail]"+m"(this->Value.Tail)
, [ticket]"+r"(myTicket)
: : "cc" );
// It's possible to address the upper word directly.
while (this->Value.Head != myTicket)
DO_NOTHING();
}
#if defined(__BEELZEBUB_SETTINGS_NO_SMP)
void TicketLock<false>::Release() volatile
#else
template<bool SMP>
void TicketLock<SMP>::Release() volatile
#endif
{
asm volatile( "lock addw $1, %[head] \n\t"
: [head]"+m"(this->Value.Head)
: : "cc" );
}
#if defined(__BEELZEBUB_SETTINGS_NO_SMP)
bool TicketLock<false>::Check() const volatile
#else
template<bool SMP>
bool TicketLock<SMP>::Check() const volatile
#endif
{
ticketlock_t copy = {this->Value.Overall};
return copy.Head == copy.Tail;
}
#endif
namespace Beelzebub { namespace Synchronization
{
template struct TicketLock<true>;
template struct TicketLock<false>;
}}
| 30.409357 | 83 | 0.634615 | vercas |
04a82edb110ca9b912fadcd588a21f50d1d8d2ab | 9,952 | cpp | C++ | src/editor/generate_menu_for_float.cpp | Apodus/gamejam-rynx-tech | 4d67f1fe394dc151c290f86110038907461de6f5 | [
"MIT"
] | null | null | null | src/editor/generate_menu_for_float.cpp | Apodus/gamejam-rynx-tech | 4d67f1fe394dc151c290f86110038907461de6f5 | [
"MIT"
] | null | null | null | src/editor/generate_menu_for_float.cpp | Apodus/gamejam-rynx-tech | 4d67f1fe394dc151c290f86110038907461de6f5 | [
"MIT"
] | null | null | null |
#include <editor/editor.hpp>
#include <sstream>
std::string humanize(std::string s) {
auto replace_all = [&s](std::string what, std::string with) {
while (s.find(what) != s.npos) {
s.replace(s.find(what), what.length(), with);
}
};
replace_all("class", "");
replace_all("struct", "");
replace_all(" ", "");
replace_all("rynx::math", "r::m");
replace_all("rynx::", "r::");
replace_all("vec3<float>", "vec3f");
replace_all("vec4<float>", "vec4f");
return s;
}
void rynx::editor::field_float(
const rynx::reflection::field& member,
struct rynx_common_info info,
rynx::menu::Component* component_sheet,
std::vector<std::pair<rynx::reflection::type, rynx::reflection::field>> reflection_stack)
{
int32_t mem_offset = info.cumulative_offset + member.m_memory_offset;
float value = ecs_value_editor().access<float>(*info.ecs, info.entity_id, info.component_type_id, mem_offset);
auto field_container = std::make_shared<rynx::menu::Div>(rynx::vec3f(0.6f, 0.03f, 0.0f));
auto variable_name_label = std::make_shared<rynx::menu::Text>(rynx::vec3f(0.4f, 1.0f, 0.0f));
variable_name_label->text(std::string(info.indent, '-') + member.m_field_name);
variable_name_label->text_align_left();
auto variable_value_field = std::make_shared<rynx::menu::Button>(*info.textures, "Frame", rynx::vec3f(0.4f, 1.0f, 0.0f));
struct field_config {
float min_value = std::numeric_limits<float>::lowest();
float max_value = std::numeric_limits<float>::max();
bool slider_dynamic = true;
float constrain(float v) const {
if (v < min_value) return min_value;
if (v > max_value) return max_value;
return v;
}
};
field_config config;
auto handle_annotations = [&variable_name_label, &info, &member, &config](
// const rynx::reflection::type& type,
const rynx::reflection::field& field)
{
bool skip_next = false;
for (auto&& annotation : field.m_annotations) {
if (annotation.starts_with("applies_to")) {
std::stringstream ss(annotation);
std::string v;
ss >> v;
bool self_found = false;
while (ss >> v) {
self_found |= (v == member.m_field_name);
}
skip_next = !self_found;
}
if (annotation == "applies_to_all") {
skip_next = false;
}
if (skip_next) {
continue;
}
if (annotation.starts_with("rename")) {
std::stringstream ss(annotation);
std::string v;
ss >> v >> v;
std::string source_name = v;
ss >> v;
if (source_name == member.m_field_name) {
variable_name_label->text(std::string(info.indent, '-') + v);
}
}
else if (annotation == ">=0") {
config.min_value = 0;
}
else if (annotation.starts_with("except")) {
std::stringstream ss(annotation);
std::string v;
ss >> v;
while (ss >> v) {
if (v == member.m_field_name) {
skip_next = true;
}
}
}
else if (annotation.starts_with("range")) {
std::stringstream ss(annotation);
std::string v;
ss >> v;
ss >> v;
config.min_value = std::stof(v);
ss >> v;
config.max_value = std::stof(v);
config.slider_dynamic = false;
}
}
};
for (auto it = reflection_stack.rbegin(); it != reflection_stack.rend(); ++it)
handle_annotations(it->second);
handle_annotations(member);
variable_value_field->text()
.text(std::to_string(value))
.text_align_right()
.input_enable();
std::shared_ptr<rynx::menu::SlideBarVertical> value_slider;
if (config.slider_dynamic) {
value_slider = std::make_shared<rynx::menu::SlideBarVertical>(*info.textures, "Editor_Frame", "Editor_Frame", rynx::vec3f(0.2f, 1.0f, 0.0f), -1.0f, +1.0f);
value_slider->setValue(0);
value_slider->on_active_tick([info, mem_offset, config, self = value_slider.get(), text_element = variable_value_field.get()](float /* input_v */, float dt) {
float& v = ecs_value_editor().access<float>(*info.ecs, info.entity_id, info.component_type_id, mem_offset);
float input_v = self->getValueCubic_AroundCenter();
float tmp = v + dt * input_v;
constexpr float value_modify_velocity = 3.0f;
if (input_v * v > 0) {
tmp *= (1.0f + std::fabs(input_v) * value_modify_velocity * dt);
}
else {
tmp *= 1.0f / (1.0f + std::fabs(input_v) * value_modify_velocity * dt);
}
v = config.constrain(tmp);
text_element->text().text(std::to_string(v));
});
value_slider->on_drag_end([self = value_slider.get()](float v) {
self->setValue(0);
});
}
else {
value_slider = std::make_shared<rynx::menu::SlideBarVertical>(
*info.textures,
"Editor_Frame",
"Editor_SliderMarker",
rynx::vec3f(0.2f, 1.0f, 0.0f),
config.min_value,
config.max_value);
value_slider->setValue(ecs_value_editor().access<float>(*info.ecs, info.entity_id, info.component_type_id, mem_offset));
value_slider->on_value_changed([info, mem_offset, text_element = variable_value_field.get()](float v) {
float& field_value = ecs_value_editor().access<float>(*info.ecs, info.entity_id, info.component_type_id, mem_offset);
field_value = v;
text_element->text().text(std::to_string(v));
});
}
variable_value_field->text().on_value_changed([info, mem_offset, config, slider_ptr = value_slider.get()](const std::string& s) {
float new_value = 0.0f;
try { new_value = config.constrain(std::stof(s)); }
catch (...) { return; }
ecs_value_editor().access<float>(*info.ecs, info.entity_id, info.component_type_id, mem_offset) = new_value;
if (!config.slider_dynamic) {
slider_ptr->setValue(new_value);
}
});
value_slider->align().right_inside().top_inside().offset_x(-0.15f);
variable_value_field->align().target(value_slider.get()).left_outside().top_inside();
variable_name_label->align().left_inside().top_inside();
field_container->addChild(variable_name_label);
field_container->addChild(value_slider);
field_container->addChild(variable_value_field);
field_container->align()
.target(component_sheet->last_child())
.bottom_outside()
.left_inside();
variable_name_label->velocity_position(2000.0f);
variable_value_field->velocity_position(1000.0f);
value_slider->velocity_position(1000.0f);
component_sheet->addChild(field_container);
}
void rynx::editor::field_bool(
const rynx::reflection::field& member,
struct rynx_common_info info,
rynx::menu::Component* component_sheet,
std::vector<std::pair<rynx::reflection::type, rynx::reflection::field>> reflection_stack)
{
int32_t mem_offset = info.cumulative_offset + member.m_memory_offset;
bool value = ecs_value_editor().access<bool>(*info.ecs, info.entity_id, info.component_type_id, mem_offset);
auto field_container = std::make_shared<rynx::menu::Div>(rynx::vec3f(0.6f, 0.03f, 0.0f));
auto variable_name_label = std::make_shared<rynx::menu::Text>(rynx::vec3f(0.4f, 1.0f, 0.0f));
variable_name_label->text(std::string(info.indent, '-') + member.m_field_name);
variable_name_label->text_align_left();
auto variable_value_field = std::make_shared<rynx::menu::Button>(*info.textures, "Frame", rynx::vec3f(0.4f, 1.0f, 0.0f));
variable_value_field->text()
.text(value ? "^gYes" : "^rNo")
.text_align_center()
.input_disable();
variable_value_field->on_click([info, mem_offset, self = variable_value_field.get()]() {
bool& value = ecs_value_editor().access<bool>(*info.ecs, info.entity_id, info.component_type_id, mem_offset);
value = !value;
self->text().text(value ? "^gYes" : "^rNo");
});
variable_value_field->align().right_inside().top_inside();
variable_name_label->align().left_inside().top_inside();
field_container->addChild(variable_name_label);
field_container->addChild(variable_value_field);
field_container->align()
.target(component_sheet->last_child())
.bottom_outside()
.left_inside();
variable_name_label->velocity_position(2000.0f);
variable_value_field->velocity_position(1000.0f);
component_sheet->addChild(field_container);
}
void rynx::editor::generate_menu_for_reflection(
rynx::reflection::reflections& reflections_,
const rynx::reflection::type& type_reflection,
struct rynx_common_info info,
rynx::menu::Component* component_sheet_,
std::vector<std::pair<rynx::reflection::type, rynx::reflection::field>> reflection_stack)
{
for (auto&& member : type_reflection.m_members) {
if (member.m_type_name == "float") {
rynx_common_info field_info = info;
++field_info.indent;
field_float(member, field_info, component_sheet_, reflection_stack);
}
else if (member.m_type_name == "bool") {
rynx_common_info field_info = info;
++field_info.indent;
field_bool(member, field_info, component_sheet_, reflection_stack);
}
else if (reflections_.has(member.m_type_name)) {
auto label = std::make_shared<rynx::menu::Button>(*info.textures, "Frame", rynx::vec3f(0.6f, 0.03f, 0.0f));
label->text()
.text(std::string(info.indent + 1, '-') + member.m_field_name + " (" + humanize(member.m_type_name) + ")")
.text_align_left();
label->align()
.target(component_sheet_->last_child())
.bottom_outside()
.left_inside();
label->velocity_position(100.0f);
component_sheet_->addChild(label);
rynx_common_info field_info;
field_info = info;
field_info.cumulative_offset += member.m_memory_offset;
++field_info.indent;
reflection_stack.emplace_back(type_reflection, member);
const auto& member_type_reflection = reflections_.get(member);
generate_menu_for_reflection(reflections_, member_type_reflection, field_info, component_sheet_, reflection_stack);
reflection_stack.pop_back();
}
else {
auto label = std::make_shared<rynx::menu::Button>(*info.textures, "Frame", rynx::vec3f(0.6f, 0.03f, 0.0f));
label->text()
.text(std::string(info.indent + 1, '-') + member.m_field_name + " (" + humanize(member.m_type_name) + ")")
.text_align_left();
label->align()
.target(component_sheet_->last_child())
.bottom_outside()
.left_inside();
label->velocity_position(100.0f);
component_sheet_->addChild(label);
}
}
} | 33.173333 | 160 | 0.697247 | Apodus |
04a86597a7088ff20d02b8177381ef4358b85aac | 107,837 | cpp | C++ | src/lock/lock.cpp | stbergmann/firebird | bfabbd020f00fc40a3155799ccb3caac2642504f | [
"Condor-1.1"
] | 1 | 2021-05-25T09:15:39.000Z | 2021-05-25T09:15:39.000Z | src/lock/lock.cpp | stbergmann/firebird | bfabbd020f00fc40a3155799ccb3caac2642504f | [
"Condor-1.1"
] | null | null | null | src/lock/lock.cpp | stbergmann/firebird | bfabbd020f00fc40a3155799ccb3caac2642504f | [
"Condor-1.1"
] | null | null | null | /*
* PROGRAM: JRD Lock Manager
* MODULE: lock.cpp
* DESCRIPTION: Generic ISC Lock Manager
*
* The contents of this file are subject to the Interbase Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy
* of the License at http://www.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
* 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "IMP" port
*
* 2002.10.27 Sean Leyne - Completed removal of obsolete "DELTA" port
* 2002.10.27 Sean Leyne - Completed removal of obsolete "IMP" port
*
* 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
* 2003.03.24 Nickolay Samofatov
* - cleanup #define's,
* - shutdown blocking thread cleanly on Windows CS
* - fix Windows CS lock-ups (make wakeup event manual-reset)
* - detect deadlocks instantly in most cases (if blocking owner
* dies during AST processing deadlock scan timeout still applies)
* 2003.04.29 Nickolay Samofatov - fix broken lock table resizing code in CS builds
* 2003.08.11 Nickolay Samofatov - finally and correctly fix Windows CS lock-ups.
* Roll back earlier workarounds on this subject.
*
*/
#include "firebird.h"
#include "../lock/lock_proto.h"
#include "../common/ThreadStart.h"
#include "../jrd/jrd.h"
#include "../jrd/Attachment.h"
#include "gen/iberror.h"
#include "../yvalve/gds_proto.h"
#include "../common/gdsassert.h"
#include "../common/isc_proto.h"
#include "../common/os/isc_i_proto.h"
#include "../common/isc_s_proto.h"
#include "../common/config/config.h"
#include "../common/classes/array.h"
#include "../common/classes/Hash.h"
#include "../common/classes/semaphore.h"
#include "../common/classes/init.h"
#include "../common/classes/timestamp.h"
#include "../common/os/os_utils.h"
#include <stdio.h>
#include <errno.h>
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#ifdef TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_VFORK_H
#include <vfork.h>
#endif
#ifdef WIN_NT
#include <process.h>
#define MUTEX &m_shmemMutex
#else
#define MUTEX m_lhb_mutex
#endif
#ifdef DEV_BUILD
//#define VALIDATE_LOCK_TABLE
#endif
#ifdef DEV_BUILD
#define ASSERT_ACQUIRED fb_assert(m_sharedMemory->getHeader()->lhb_active_owner)
#ifdef HAVE_OBJECT_MAP
#define LOCK_DEBUG_REMAP
#define DEBUG_REMAP_INTERVAL 5000
static ULONG debug_remap_count = 0;
#endif
#define CHECK(x) do { if (!(x)) bug_assert ("consistency check", __LINE__); } while (false)
#else // DEV_BUILD
#define ASSERT_ACQUIRED
#define CHECK(x) do { } while (false)
#endif // DEV_BUILD
#ifdef DEBUG_LM
SSHORT LOCK_debug_level = 0;
#define LOCK_TRACE(x) { time_t t; time(&t); printf("%s", ctime(&t) ); printf x; fflush (stdout); gds__log x;}
#define DEBUG_MSG(l, x) if ((l) <= LOCK_debug_level) { time_t t; time(&t); printf("%s", ctime(&t) ); printf x; fflush (stdout); gds__log x; }
// Debug delay is used to create nice big windows for signals or other
// events to occur in - eg: slow down the code to try and make
// timing race conditions show up
#define DEBUG_DELAY debug_delay (__LINE__)
#else
#define LOCK_TRACE(x)
#define DEBUG_MSG(l, x)
#define DEBUG_DELAY
#endif
using namespace Firebird;
// hvlad: enable to log deadlocked owners and its PIDs in firebird.log
//#define DEBUG_TRACE_DEADLOCKS
// CVC: Unlike other definitions, SRQ_PTR is not a pointer to something in lowercase.
// It's LONG.
const SRQ_PTR DUMMY_OWNER = -1;
const SLONG HASH_MIN_SLOTS = 101;
const SLONG HASH_MAX_SLOTS = 65521;
const USHORT HISTORY_BLOCKS = 256;
// SRQ_ABS_PTR uses this macro.
#define SRQ_BASE ((UCHAR*) m_sharedMemory->getHeader())
static const bool compatibility[LCK_max][LCK_max] =
{
/* Shared Prot Shared Prot
none null Read Read Write Write Exclusive */
/* none */ {true, true, true, true, true, true, true},
/* null */ {true, true, true, true, true, true, true},
/* SR */ {true, true, true, true, true, true, false},
/* PR */ {true, true, true, true, false, false, false},
/* SW */ {true, true, true, false, true, false, false},
/* PW */ {true, true, true, false, false, false, false},
/* EX */ {true, true, false, false, false, false, false}
};
namespace Jrd {
LockManager::LockManager(const string& id, const Config* conf)
: PID(getpid()),
m_bugcheck(false),
m_process(NULL),
m_processOffset(0),
m_cleanupSync(getPool(), blocking_action_thread, THREAD_high),
m_sharedMemory(NULL),
m_blockage(false),
m_dbId(id),
m_config(conf),
m_acquireSpins(m_config->getLockAcquireSpins()),
m_memorySize(m_config->getLockMemSize()),
m_useBlockingThread(m_config->getServerMode() != MODE_SUPER)
#ifdef USE_SHMEM_EXT
, m_extents(getPool())
#endif
{
LocalStatus ls;
CheckStatusWrapper localStatus(&ls);
if (!init_shared_file(&localStatus))
{
iscLogStatus("LockManager::LockManager()", &localStatus);
status_exception::raise(&localStatus);
}
}
LockManager::~LockManager()
{
const SRQ_PTR process_offset = m_processOffset;
{ // guardian's scope
LockTableGuard guard(this, FB_FUNCTION);
m_processOffset = 0;
}
LocalStatus ls;
CheckStatusWrapper localStatus(&ls);
if (m_process)
{
if (m_useBlockingThread)
{
// Wait for AST thread to start (or 5 secs)
m_startupSemaphore.tryEnter(5);
// Wakeup the AST thread - it might be blocking
(void) // Ignore errors in dtor()
m_sharedMemory->eventPost(&m_process->prc_blocking);
// Wait for the AST thread to finish cleanup or for 5 seconds
m_cleanupSync.waitForCompletion();
}
#ifdef HAVE_OBJECT_MAP
m_sharedMemory->unmapObject(&localStatus, &m_process);
#else
m_process = NULL;
#endif
}
{ // guardian's scope
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
if (process_offset)
{
prc* const process = (prc*) SRQ_ABS_PTR(process_offset);
purge_process(process);
}
if (m_sharedMemory->getHeader() && SRQ_EMPTY(m_sharedMemory->getHeader()->lhb_processes))
{
PathName name;
get_shared_file_name(name);
m_sharedMemory->removeMapFile();
#ifdef USE_SHMEM_EXT
for (ULONG i = 1; i < m_extents.getCount(); ++i)
{
m_extents[i].removeMapFile();
}
#endif //USE_SHMEM_EXT
}
}
#ifdef USE_SHMEM_EXT
for (ULONG i = 1; i < m_extents.getCount(); ++i)
{
m_extents[i].unmapFile(&localStatus);
}
#endif //USE_SHMEM_EXT
}
#ifdef USE_SHMEM_EXT
SRQ_PTR LockManager::REL_PTR(const void* par_item)
{
const UCHAR* const item = static_cast<const UCHAR*>(par_item);
for (ULONG i = 0; i < m_extents.getCount(); ++i)
{
Extent& l = m_extents[i];
UCHAR* adr = reinterpret_cast<UCHAR*>(l.sh_mem_header);
if (item >= adr && item < adr + getExtentSize())
{
return getStartOffset(i) + (item - adr);
}
}
errno = 0;
bug(NULL, "Extent not found in REL_PTR()");
return 0; // compiler silencer
}
void* LockManager::ABS_PTR(SRQ_PTR item)
{
const ULONG extent = item / getExtentSize();
if (extent >= m_extents.getCount())
{
errno = 0;
bug(NULL, "Extent not found in ABS_PTR()");
}
return reinterpret_cast<UCHAR*>(m_extents[extent].sh_mem_header) + (item % getExtentSize());
}
#endif //USE_SHMEM_EXT
bool LockManager::init_shared_file(CheckStatusWrapper* statusVector)
{
PathName name;
get_shared_file_name(name);
try
{
SharedMemory<lhb>* tmp = FB_NEW_POOL(getPool()) SharedMemory<lhb>(name.c_str(), m_memorySize, this);
// initialize will reset m_sharedMemory
fb_assert(m_sharedMemory == tmp);
}
catch (const Exception& ex)
{
ex.stuffException(statusVector);
return false;
}
fb_assert(m_sharedMemory->getHeader()->mhb_type == SharedMemoryBase::SRAM_LOCK_MANAGER);
fb_assert(m_sharedMemory->getHeader()->mhb_header_version == MemoryHeader::HEADER_VERSION);
fb_assert(m_sharedMemory->getHeader()->mhb_version == LHB_VERSION);
#ifdef USE_SHMEM_EXT
m_extents[0] = *this;
#endif
return true;
}
void LockManager::get_shared_file_name(PathName& name, ULONG extent) const
{
name.printf(LOCK_FILE, m_dbId.c_str());
if (extent)
{
PathName ename;
ename.printf("%s.ext%d", name.c_str(), extent);
name = ename;
}
}
bool LockManager::initializeOwner(CheckStatusWrapper* statusVector,
LOCK_OWNER_T owner_id,
UCHAR owner_type,
SRQ_PTR* owner_handle)
{
/**************************************
*
* i n i t i a l i z e O w n e r
*
**************************************
*
* Functional description
* Initialize lock manager for the given owner, if not already done.
*
* Initialize an owner block in the lock manager, if not already
* initialized.
*
* Return the offset of the owner block through owner_handle.
*
* Return success or failure.
*
**************************************/
LOCK_TRACE(("LM::init (ownerid=%ld)\n", owner_id));
SRQ_PTR owner_offset = *owner_handle;
if (owner_offset)
{
LockTableGuard guard(this, FB_FUNCTION, owner_offset);
// If everything is already initialized, just bump the use count
own* const owner = (own*) SRQ_ABS_PTR(owner_offset);
owner->own_count++;
return true;
}
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
owner_offset = create_owner(statusVector, owner_id, owner_type);
if (owner_offset)
*owner_handle = owner_offset;
LOCK_TRACE(("LM::init done (%ld)\n", owner_offset));
return (owner_offset != 0);
}
void LockManager::shutdownOwner(thread_db* tdbb, SRQ_PTR* owner_handle)
{
/**************************************
*
* s h u t d o w n O w n e r
*
**************************************
*
* Functional description
* Release the owner block and any outstanding locks.
* The exit handler will unmap the shared memory.
*
**************************************/
LOCK_TRACE(("LM::fini (%ld)\n", *owner_handle));
const SRQ_PTR owner_offset = *owner_handle;
if (!owner_offset)
return;
LockTableGuard guard(this, FB_FUNCTION, owner_offset);
own* owner = (own*) SRQ_ABS_PTR(owner_offset);
if (!owner->own_count)
return;
if (--owner->own_count > 0)
return;
while (owner->own_ast_count)
{
{ // checkout scope
LockTableCheckout checkout(this, FB_FUNCTION);
EngineCheckout cout(tdbb, FB_FUNCTION, true);
Thread::sleep(10);
}
owner = (own*) SRQ_ABS_PTR(owner_offset);
}
// This assert expects that all the granted locks have been explicitly
// released before destroying the lock owner. This is not strictly required,
// but it enforces the proper object lifetime discipline through the codebase.
fb_assert(SRQ_EMPTY(owner->own_requests));
purge_owner(owner_offset, owner);
*owner_handle = 0;
}
SRQ_PTR LockManager::enqueue(thread_db* tdbb,
CheckStatusWrapper* statusVector,
SRQ_PTR prior_request,
const USHORT series,
const UCHAR* value,
const USHORT length,
UCHAR type,
lock_ast_t ast_routine,
void* ast_argument,
LOCK_DATA_T data,
SSHORT lck_wait,
SRQ_PTR owner_offset)
{
/**************************************
*
* e n q u e u e
*
**************************************
*
* Functional description
* Enque on a lock. If the lock can't be granted immediately,
* return an event count on which to wait. If the lock can't
* be granted because of deadlock, return NULL.
*
**************************************/
LOCK_TRACE(("LM::enqueue (%ld)\n", owner_offset));
if (!owner_offset)
return 0;
LockTableGuard guard(this, FB_FUNCTION, owner_offset);
own* owner = (own*) SRQ_ABS_PTR(owner_offset);
if (!owner->own_count)
return 0;
ASSERT_ACQUIRED;
++(m_sharedMemory->getHeader()->lhb_enqs);
#ifdef VALIDATE_LOCK_TABLE
if ((m_sharedMemory->getHeader()->lhb_enqs % 50) == 0)
validate_lhb(m_sharedMemory->getHeader());
#endif
if (prior_request)
internal_dequeue(prior_request);
// Allocate or reuse a lock request block
lrq* request;
ASSERT_ACQUIRED;
if (SRQ_EMPTY(m_sharedMemory->getHeader()->lhb_free_requests))
{
if (!(request = (lrq*) alloc(sizeof(lrq), statusVector)))
return 0;
owner = (own*) SRQ_ABS_PTR(owner_offset);
}
else
{
ASSERT_ACQUIRED;
request = (lrq*) ((UCHAR*) SRQ_NEXT(m_sharedMemory->getHeader()->lhb_free_requests) -
offsetof(lrq, lrq_lbl_requests));
remove_que(&request->lrq_lbl_requests);
}
post_history(his_enq, owner_offset, (SRQ_PTR)0, SRQ_REL_PTR(request), true);
request->lrq_type = type_lrq;
request->lrq_flags = 0;
request->lrq_requested = type;
request->lrq_state = LCK_none;
request->lrq_data = 0;
request->lrq_owner = owner_offset;
request->lrq_ast_routine = ast_routine;
request->lrq_ast_argument = ast_argument;
insert_tail(&owner->own_requests, &request->lrq_own_requests);
SRQ_INIT(request->lrq_own_blocks);
SRQ_INIT(request->lrq_own_pending);
const SRQ_PTR request_offset = SRQ_REL_PTR(request);
// See if the lock already exists
USHORT hash_slot;
lbl* lock = find_lock(series, value, length, &hash_slot);
if (lock)
{
if (series < LCK_MAX_SERIES)
++(m_sharedMemory->getHeader()->lhb_operations[series]);
else
++(m_sharedMemory->getHeader()->lhb_operations[0]);
insert_tail(&lock->lbl_requests, &request->lrq_lbl_requests);
request->lrq_data = data;
if (grant_or_que(tdbb, request, lock, lck_wait))
return request_offset;
Arg::Gds(lck_wait > 0 ? isc_deadlock : lck_wait < 0 ? isc_lock_timeout :
isc_lock_conflict).copyTo(statusVector);
return 0;
}
// Lock doesn't exist. Allocate lock block and set it up.
if (!(lock = alloc_lock(length, statusVector)))
{
// lock table is exhausted: release request gracefully
remove_que(&request->lrq_own_requests);
request->lrq_type = type_null;
insert_tail(&m_sharedMemory->getHeader()->lhb_free_requests, &request->lrq_lbl_requests);
return 0;
}
lock->lbl_state = type;
fb_assert(series <= MAX_UCHAR);
lock->lbl_series = (UCHAR)series;
// Maintain lock series data queue
SRQ_INIT(lock->lbl_lhb_data);
if ( (lock->lbl_data = data) )
insert_data_que(lock);
if (series < LCK_MAX_SERIES)
++(m_sharedMemory->getHeader()->lhb_operations[series]);
else
++(m_sharedMemory->getHeader()->lhb_operations[0]);
lock->lbl_flags = 0;
lock->lbl_pending_lrq_count = 0;
memset(lock->lbl_counts, 0, sizeof(lock->lbl_counts));
lock->lbl_length = length;
memcpy(lock->lbl_key, value, length);
request = (lrq*) SRQ_ABS_PTR(request_offset);
SRQ_INIT(lock->lbl_requests);
ASSERT_ACQUIRED;
insert_tail(&m_sharedMemory->getHeader()->lhb_hash[hash_slot], &lock->lbl_lhb_hash);
insert_tail(&lock->lbl_requests, &request->lrq_lbl_requests);
request->lrq_lock = SRQ_REL_PTR(lock);
grant(request, lock);
return request_offset;
}
bool LockManager::convert(thread_db* tdbb,
CheckStatusWrapper* statusVector,
SRQ_PTR request_offset,
UCHAR type,
SSHORT lck_wait,
lock_ast_t ast_routine,
void* ast_argument)
{
/**************************************
*
* c o n v e r t
*
**************************************
*
* Functional description
* Perform a lock conversion, if possible.
*
**************************************/
LOCK_TRACE(("LM::convert (%d, %d)\n", type, lck_wait));
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
lrq* const request = get_request(request_offset);
const SRQ_PTR owner_offset = request->lrq_owner;
guard.setOwner(owner_offset);
own* const owner = (own*) SRQ_ABS_PTR(owner_offset);
if (!owner->own_count)
return false;
++(m_sharedMemory->getHeader()->lhb_converts);
const lbl* lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
if (lock->lbl_series < LCK_MAX_SERIES)
++(m_sharedMemory->getHeader()->lhb_operations[lock->lbl_series]);
else
++(m_sharedMemory->getHeader()->lhb_operations[0]);
const bool result =
internal_convert(tdbb, statusVector, request_offset, type, lck_wait,
ast_routine, ast_argument);
return result;
}
UCHAR LockManager::downgrade(thread_db* tdbb,
CheckStatusWrapper* statusVector,
const SRQ_PTR request_offset)
{
/**************************************
*
* d o w n g r a d e
*
**************************************
*
* Functional description
* Downgrade an existing lock returning
* its new state.
*
**************************************/
LOCK_TRACE(("LM::downgrade (%ld)\n", request_offset));
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
lrq* const request = get_request(request_offset);
const SRQ_PTR owner_offset = request->lrq_owner;
guard.setOwner(owner_offset);
own* const owner = (own*) SRQ_ABS_PTR(owner_offset);
if (!owner->own_count)
return LCK_none;
++(m_sharedMemory->getHeader()->lhb_downgrades);
const lbl* lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
UCHAR pending_state = LCK_none;
// Loop thru requests looking for pending conversions
// and find the highest requested state
srq* lock_srq;
SRQ_LOOP(lock->lbl_requests, lock_srq)
{
const lrq* const pending = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_lbl_requests));
if ((pending->lrq_flags & LRQ_pending) && pending != request)
{
pending_state = MAX(pending->lrq_requested, pending_state);
if (pending_state == LCK_EX)
break;
}
}
UCHAR state = request->lrq_state;
while (state > LCK_none && !compatibility[pending_state][state])
--state;
if (state == LCK_none || state == LCK_null)
{
internal_dequeue(request_offset);
state = LCK_none;
}
else
{
internal_convert(tdbb, statusVector, request_offset, state, LCK_NO_WAIT,
request->lrq_ast_routine, request->lrq_ast_argument);
}
return state;
}
bool LockManager::dequeue(const SRQ_PTR request_offset)
{
/**************************************
*
* d e q u e u e
*
**************************************
*
* Functional description
* Release an outstanding lock.
*
**************************************/
LOCK_TRACE(("LM::dequeue (%ld)\n", request_offset));
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
lrq* const request = get_request(request_offset);
const SRQ_PTR owner_offset = request->lrq_owner;
guard.setOwner(owner_offset);
own* const owner = (own*) SRQ_ABS_PTR(owner_offset);
if (!owner->own_count)
return false;
++(m_sharedMemory->getHeader()->lhb_deqs);
const lbl* lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
if (lock->lbl_series < LCK_MAX_SERIES)
++(m_sharedMemory->getHeader()->lhb_operations[lock->lbl_series]);
else
++(m_sharedMemory->getHeader()->lhb_operations[0]);
internal_dequeue(request_offset);
return true;
}
void LockManager::repost(thread_db* tdbb, lock_ast_t ast, void* arg, SRQ_PTR owner_offset)
{
/**************************************
*
* r e p o s t
*
**************************************
*
* Functional description
* Re-post an AST that was previously blocked.
* It is assumed that the routines that look
* at the re-post list only test the ast element.
*
**************************************/
LOCK_TRACE(("LM::repost (%ld)\n", owner_offset));
if (!owner_offset)
return;
LockTableGuard guard(this, FB_FUNCTION, owner_offset);
// Allocate or reuse a lock request block
lrq* request;
ASSERT_ACQUIRED;
if (SRQ_EMPTY(m_sharedMemory->getHeader()->lhb_free_requests))
{
if (!(request = (lrq*) alloc(sizeof(lrq), NULL)))
{
return;
}
}
else
{
ASSERT_ACQUIRED;
request = (lrq*) ((UCHAR*) SRQ_NEXT(m_sharedMemory->getHeader()->lhb_free_requests) -
offsetof(lrq, lrq_lbl_requests));
remove_que(&request->lrq_lbl_requests);
}
request->lrq_type = type_lrq;
request->lrq_flags = LRQ_repost;
request->lrq_ast_routine = ast;
request->lrq_ast_argument = arg;
request->lrq_requested = LCK_none;
request->lrq_state = LCK_none;
request->lrq_owner = owner_offset;
request->lrq_lock = 0;
own* const owner = (own*) SRQ_ABS_PTR(owner_offset);
insert_tail(&owner->own_blocks, &request->lrq_own_blocks);
SRQ_INIT(request->lrq_own_pending);
DEBUG_DELAY;
if (!(owner->own_flags & OWN_signaled))
signal_owner(tdbb, owner);
}
bool LockManager::cancelWait(SRQ_PTR owner_offset)
{
/**************************************
*
* c a n c e l W a i t
*
**************************************
*
* Functional description
* Wakeup waiting owner to make it check if wait should be cancelled.
* As this routine could be called asyncronous, take extra care and
* don't trust the input params blindly.
*
**************************************/
LOCK_TRACE(("LM::cancelWait (%ld)\n", owner_offset));
if (!owner_offset)
return false;
LockTableGuard guard(this, FB_FUNCTION, owner_offset);
own* const owner = (own*) SRQ_ABS_PTR(owner_offset);
if (!owner->own_count)
return false;
post_wakeup(owner);
return true;
}
LOCK_DATA_T LockManager::queryData(const USHORT series, const USHORT aggregate)
{
/**************************************
*
* q u e r y D a t a
*
**************************************
*
* Functional description
* Query lock series data with respect to a rooted
* lock hierarchy calculating aggregates as we go.
*
**************************************/
if (series >= LCK_MAX_SERIES)
{
CHECK(false);
return 0;
}
LOCK_TRACE(("LM::queryData (%ld)\n", owner_offset));
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
++(m_sharedMemory->getHeader()->lhb_query_data);
const srq& data_header = m_sharedMemory->getHeader()->lhb_data[series];
LOCK_DATA_T data = 0, count = 0;
// Simply walk the lock series data queue forward for the minimum
// and backward for the maximum -- it's maintained in sorted order.
switch (aggregate)
{
case LCK_CNT:
case LCK_AVG:
case LCK_SUM:
for (const srq* lock_srq = (SRQ) SRQ_ABS_PTR(data_header.srq_forward);
lock_srq != &data_header; lock_srq = (SRQ) SRQ_ABS_PTR(lock_srq->srq_forward))
{
const lbl* const lock = (lbl*) ((UCHAR*) lock_srq - offsetof(lbl, lbl_lhb_data));
CHECK(lock->lbl_series == series);
switch (aggregate)
{
case LCK_CNT:
++count;
break;
case LCK_AVG:
++count;
case LCK_SUM:
data += lock->lbl_data;
break;
}
}
if (aggregate == LCK_CNT)
data = count;
else if (aggregate == LCK_AVG)
data = count ? data / count : 0;
break;
case LCK_ANY:
if (!SRQ_EMPTY(data_header))
data = 1;
break;
case LCK_MIN:
if (!SRQ_EMPTY(data_header))
{
const srq* lock_srq = (SRQ) SRQ_ABS_PTR(data_header.srq_forward);
const lbl* const lock = (lbl*) ((UCHAR*) lock_srq - offsetof(lbl, lbl_lhb_data));
CHECK(lock->lbl_series == series);
data = lock->lbl_data;
}
break;
case LCK_MAX:
if (!SRQ_EMPTY(data_header))
{
const srq* lock_srq = (SRQ) SRQ_ABS_PTR(data_header.srq_backward);
const lbl* const lock = (lbl*) ((UCHAR*) lock_srq - offsetof(lbl, lbl_lhb_data));
CHECK(lock->lbl_series == series);
data = lock->lbl_data;
}
break;
default:
CHECK(false);
}
return data;
}
LOCK_DATA_T LockManager::readData(SRQ_PTR request_offset)
{
/**************************************
*
* r e a d D a t a
*
**************************************
*
* Functional description
* Read data associated with a lock.
*
**************************************/
LOCK_TRACE(("LM::readData (%ld)\n", request_offset));
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
const lrq* const request = get_request(request_offset);
guard.setOwner(request->lrq_owner);
++(m_sharedMemory->getHeader()->lhb_read_data);
const lbl* const lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
const LOCK_DATA_T data = lock->lbl_data;
if (lock->lbl_series < LCK_MAX_SERIES)
++(m_sharedMemory->getHeader()->lhb_operations[lock->lbl_series]);
else
++(m_sharedMemory->getHeader()->lhb_operations[0]);
return data;
}
LOCK_DATA_T LockManager::readData2(USHORT series,
const UCHAR* value,
USHORT length,
SRQ_PTR owner_offset)
{
/**************************************
*
* r e a d D a t a 2
*
**************************************
*
* Functional description
* Read data associated with transient locks.
*
**************************************/
LOCK_TRACE(("LM::readData2 (%ld)\n", owner_offset));
if (!owner_offset)
return 0;
LockTableGuard guard(this, FB_FUNCTION, owner_offset);
++(m_sharedMemory->getHeader()->lhb_read_data);
if (series < LCK_MAX_SERIES)
++(m_sharedMemory->getHeader()->lhb_operations[series]);
else
++(m_sharedMemory->getHeader()->lhb_operations[0]);
USHORT junk;
const lbl* const lock = find_lock(series, value, length, &junk);
return lock ? lock->lbl_data : 0;
}
LOCK_DATA_T LockManager::writeData(SRQ_PTR request_offset, LOCK_DATA_T data)
{
/**************************************
*
* w r i t e D a t a
*
**************************************
*
* Functional description
* Write a longword into the lock block.
*
**************************************/
LOCK_TRACE(("LM::writeData (%ld)\n", request_offset));
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
const lrq* const request = get_request(request_offset);
guard.setOwner(request->lrq_owner);
++(m_sharedMemory->getHeader()->lhb_write_data);
lbl* const lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
remove_que(&lock->lbl_lhb_data);
if ( (lock->lbl_data = data) )
insert_data_que(lock);
if (lock->lbl_series < LCK_MAX_SERIES)
++(m_sharedMemory->getHeader()->lhb_operations[lock->lbl_series]);
else
++(m_sharedMemory->getHeader()->lhb_operations[0]);
return data;
}
void LockManager::acquire_shmem(SRQ_PTR owner_offset)
{
/**************************************
*
* a c q u i r e
*
**************************************
*
* Functional description
* Acquire the lock file. If it's busy, wait for it.
*
**************************************/
LocalStatus ls;
CheckStatusWrapper localStatus(&ls);
// Perform a spin wait on the lock table mutex. This should only
// be used on SMP machines; it doesn't make much sense otherwise.
const ULONG spins_to_try = m_acquireSpins ? m_acquireSpins : 1;
bool locked = false;
ULONG spins = 0;
while (spins++ < spins_to_try)
{
if (m_sharedMemory->mutexLockCond())
{
locked = true;
break;
}
m_blockage = true;
}
// If the spin wait didn't succeed then wait forever
if (!locked)
m_sharedMemory->mutexLock();
// Reattach if someone has just deleted the shared file
while (m_sharedMemory->getHeader()->isDeleted())
{
fb_assert(!m_process);
if (m_process)
bug(NULL, "Process disappeared in LockManager::acquire_shmem");
// Shared memory must be empty at this point
fb_assert(SRQ_EMPTY(m_sharedMemory->getHeader()->lhb_processes));
// no sense thinking about statistics now
m_blockage = false;
m_sharedMemory->mutexUnlock();
m_sharedMemory.reset();
Thread::yield();
if (!init_shared_file(&localStatus))
bug(NULL, "ISC_map_file failed (reattach shared file)");
m_sharedMemory->mutexLock();
}
++(m_sharedMemory->getHeader()->lhb_acquires);
if (m_blockage)
{
++(m_sharedMemory->getHeader()->lhb_acquire_blocks);
m_blockage = false;
}
if (spins > 1)
{
++(m_sharedMemory->getHeader()->lhb_acquire_retries);
if (spins < spins_to_try) {
++(m_sharedMemory->getHeader()->lhb_retry_success);
}
}
const SRQ_PTR prior_active = m_sharedMemory->getHeader()->lhb_active_owner;
m_sharedMemory->getHeader()->lhb_active_owner = owner_offset;
if (owner_offset > 0)
{
own* const owner = (own*) SRQ_ABS_PTR(owner_offset);
owner->own_thread_id = getThreadId();
}
#ifdef USE_SHMEM_EXT
while (m_sharedMemory->getHeader()->lhb_length > getTotalMapped())
{
if (!createExtent(&localStatus))
{
bug(NULL, "map of lock file extent failed");
}
}
#else //USE_SHMEM_EXT
if (m_sharedMemory->getHeader()->lhb_length > m_sharedMemory->sh_mem_length_mapped
#ifdef LOCK_DEBUG_REMAP
// If we're debugging remaps, force a remap every-so-often.
|| ((debug_remap_count++ % DEBUG_REMAP_INTERVAL) == 0 && m_processOffset)
#endif
)
{
#ifdef HAVE_OBJECT_MAP
const ULONG new_length = m_sharedMemory->getHeader()->lhb_length;
WriteLockGuard guard(m_remapSync, FB_FUNCTION);
// Post remapping notifications
remap_local_owners();
// Remap the shared memory region
if (!m_sharedMemory->remapFile(&localStatus, new_length, false))
#endif
{
bug(NULL, "remap failed");
return;
}
}
#endif //USE_SHMEM_EXT
// If we were able to acquire the MUTEX, but there is an prior owner marked
// in the the lock table, it means that someone died while owning
// the lock mutex. In that event, lets see if there is any unfinished work
// left around that we need to finish up.
if (prior_active > 0)
{
post_history(his_active, owner_offset, prior_active, (SRQ_PTR) 0, false);
shb* const recover = (shb*) SRQ_ABS_PTR(m_sharedMemory->getHeader()->lhb_secondary);
if (recover->shb_remove_node)
{
// There was a remove_que operation in progress when the prior_owner died
DEBUG_MSG(0, ("Got to the funky shb_remove_node code\n"));
remove_que((SRQ) SRQ_ABS_PTR(recover->shb_remove_node));
}
else if (recover->shb_insert_que && recover->shb_insert_prior)
{
// There was a insert_que operation in progress when the prior_owner died
DEBUG_MSG(0, ("Got to the funky shb_insert_que code\n"));
SRQ lock_srq = (SRQ) SRQ_ABS_PTR(recover->shb_insert_que);
lock_srq->srq_backward = recover->shb_insert_prior;
lock_srq = (SRQ) SRQ_ABS_PTR(recover->shb_insert_prior);
lock_srq->srq_forward = recover->shb_insert_que;
recover->shb_insert_que = 0;
recover->shb_insert_prior = 0;
}
}
}
#ifdef USE_SHMEM_EXT
bool LockManager::Extent::initialize(bool)
{
return false;
}
void LockManager::Extent::mutexBug(int, const char*)
{ }
bool LockManager::createExtent(CheckStatusWrapper* statusVector)
{
PathName name;
get_shared_file_name(name, (ULONG) m_extents.getCount());
Extent& extent = m_extents.add();
if (!extent.mapFile(statusVector, name.c_str(), m_memorySize))
{
m_extents.pop();
logError("LockManager::createExtent() mapFile", local_status);
return false;
}
return true;
}
#endif
UCHAR* LockManager::alloc(USHORT size, CheckStatusWrapper* statusVector)
{
/**************************************
*
* a l l o c
*
**************************************
*
* Functional description
* Allocate a block of given size.
*
**************************************/
LocalStatus ls;
CheckStatusWrapper localStatus(&ls);
if (!statusVector)
statusVector = &localStatus;
size = FB_ALIGN(size, FB_ALIGNMENT);
ASSERT_ACQUIRED;
ULONG block = m_sharedMemory->getHeader()->lhb_used;
// Make sure we haven't overflowed the lock table. If so, bump the size of the table.
if (m_sharedMemory->getHeader()->lhb_used + size > m_sharedMemory->getHeader()->lhb_length)
{
#ifdef USE_SHMEM_EXT
// round up so next object starts at beginning of next extent
block = m_sharedMemory->getHeader()->lhb_used = m_sharedMemory->getHeader()->lhb_length;
if (createExtent(*statusVector))
{
m_sharedMemory->getHeader()->lhb_length += m_memorySize;
}
else
#elif (defined HAVE_OBJECT_MAP)
WriteLockGuard guard(m_remapSync, FB_FUNCTION);
// Post remapping notifications
remap_local_owners();
// Remap the shared memory region
const ULONG new_length = m_sharedMemory->sh_mem_length_mapped + m_memorySize;
if (m_sharedMemory->remapFile(statusVector, new_length, true))
{
ASSERT_ACQUIRED;
m_sharedMemory->getHeader()->lhb_length = m_sharedMemory->sh_mem_length_mapped;
}
else
#endif
{
// Do not do abort in case if there is not enough room -- just
// return an error
(Arg::Gds(isc_lockmanerr) <<
Arg::Gds(isc_random) << Arg::Str("lock manager out of room") <<
Arg::StatusVector(statusVector)).copyTo(statusVector);
return NULL;
}
}
m_sharedMemory->getHeader()->lhb_used += size;
#ifdef DEV_BUILD
// This version of alloc() doesn't initialize memory. To shake out
// any bugs, in DEV_BUILD we initialize it to a "funny" pattern.
memset((void*)SRQ_ABS_PTR(block), 0xFD, size);
#endif
return (UCHAR*) SRQ_ABS_PTR(block);
}
lbl* LockManager::alloc_lock(USHORT length, CheckStatusWrapper* statusVector)
{
/**************************************
*
* a l l o c _ l o c k
*
**************************************
*
* Functional description
* Allocate a lock for a key of a given length. Look first to see
* if a spare of the right size is sitting around. If not, allocate
* one.
*
**************************************/
length = FB_ALIGN(length, 8);
ASSERT_ACQUIRED;
srq* lock_srq;
SRQ_LOOP(m_sharedMemory->getHeader()->lhb_free_locks, lock_srq)
{
lbl* lock = (lbl*) ((UCHAR*) lock_srq - offsetof(lbl, lbl_lhb_hash));
// Here we use the "first fit" approach which costs us some memory,
// but works fast. The "best fit" one is proven to be unacceptably slow.
// Maybe there could be some compromise, e.g. limiting the number of "best fit"
// iterations before defaulting to a "first fit" match. Another idea could be
// to introduce yet another hash table for the free locks queue.
if (lock->lbl_size >= length)
{
remove_que(&lock->lbl_lhb_hash);
lock->lbl_type = type_lbl;
return lock;
}
}
lbl* lock = (lbl*) alloc(sizeof(lbl) + length, statusVector);
if (lock)
{
lock->lbl_size = length;
lock->lbl_type = type_lbl;
}
// NOTE: if the above alloc() fails do not release mutex here but rather
// release it in LOCK_enq() (as of now it is the only function that
// calls alloc_lock()). We need to hold mutex to be able
// to release a lock request block.
return lock;
}
void LockManager::blocking_action(thread_db* tdbb, SRQ_PTR blocking_owner_offset)
{
/**************************************
*
* b l o c k i n g _ a c t i o n
*
**************************************
*
* Functional description
* Fault handler for a blocking signal. A blocking signal
* is an indication (albeit a strong one) that a blocking
* AST is pending for the owner. Check in with the data
* structure for details.
* The re-post code in this routine assumes that no more
* than one thread of execution can be running in this
* routine at any time.
*
* IMPORTANT: Before calling this routine, acquire_shmem() should
* have already been done.
*
* Note that both a blocking owner offset and blocked owner
* offset are passed to this function. This is for those
* cases where the owners are not the same. If they are
* the same, then the blocked owner offset will be NULL.
*
**************************************/
ASSERT_ACQUIRED;
own* owner = (own*) SRQ_ABS_PTR(blocking_owner_offset);
while (owner->own_count && !SRQ_EMPTY(owner->own_blocks))
{
srq* const lock_srq = SRQ_NEXT(owner->own_blocks);
lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_own_blocks));
lock_ast_t routine = request->lrq_ast_routine;
void* arg = request->lrq_ast_argument;
remove_que(&request->lrq_own_blocks);
if (request->lrq_flags & LRQ_blocking)
{
request->lrq_flags &= ~LRQ_blocking;
request->lrq_flags |= LRQ_blocking_seen;
++(m_sharedMemory->getHeader()->lhb_blocks);
post_history(his_post_ast, blocking_owner_offset,
request->lrq_lock, SRQ_REL_PTR(request), true);
}
else if (request->lrq_flags & LRQ_repost)
{
request->lrq_type = type_null;
insert_tail(&m_sharedMemory->getHeader()->lhb_free_requests, &request->lrq_lbl_requests);
}
if (routine)
{
owner->own_ast_count++;
{ // checkout scope
LockTableCheckout checkout(this, FB_FUNCTION);
EngineCheckout cout(tdbb, FB_FUNCTION, true);
(*routine)(arg);
}
owner = (own*) SRQ_ABS_PTR(blocking_owner_offset);
owner->own_ast_count--;
}
}
owner->own_flags &= ~OWN_signaled;
}
void LockManager::blocking_action_thread()
{
/**************************************
*
* b l o c k i n g _ a c t i o n _ t h r e a d
*
**************************************
*
* Functional description
* Thread to handle blocking signals.
*
**************************************/
/*
* Main thread may be gone releasing our LockManager instance
* when AST can't lock appropriate attachment mutex and therefore does not return.
*
* This causes multiple errors when entering/releasing mutexes/semaphores.
* Catch this errors and log them.
*
* AP 2008
*/
bool atStartup = true;
try
{
while (true)
{
SLONG value;
{ // guardian's scope
LockTableGuard guard(this, FB_FUNCTION, DUMMY_OWNER);
// See if the main thread has requested us to go away
if (!m_processOffset || m_process->prc_process_id != PID)
{
if (atStartup)
{
m_startupSemaphore.release();
}
break;
}
value = m_sharedMemory->eventClear(&m_process->prc_blocking);
DEBUG_DELAY;
while (m_processOffset)
{
const prc* const process = (prc*) SRQ_ABS_PTR(m_processOffset);
bool completed = true;
srq* lock_srq;
SRQ_LOOP(process->prc_owners, lock_srq)
{
const own* const owner = (own*) ((UCHAR*) lock_srq - offsetof(own, own_prc_owners));
if (owner->own_flags & OWN_signaled)
{
const SRQ_PTR owner_offset = SRQ_REL_PTR(owner);
guard.setOwner(owner_offset);
blocking_action(NULL, owner_offset);
completed = false;
break;
}
}
if (completed)
break;
}
if (atStartup)
{
atStartup = false;
m_startupSemaphore.release();
}
}
m_sharedMemory->eventWait(&m_process->prc_blocking, value, 0);
}
}
catch (const Exception& x)
{
iscLogException("Error in blocking action thread\n", x);
}
}
void LockManager::exceptionHandler(const Exception& ex,
ThreadFinishSync<LockManager*>::ThreadRoutine* /*routine*/)
{
/**************************************
*
* e x c e p t i o n H a n d l e r
*
**************************************
*
* Functional description
* Handler for blocking thread close bugs.
*
**************************************/
iscLogException("Error closing blocking action thread\n", ex);
}
void LockManager::bug_assert(const TEXT* string, ULONG line)
{
/**************************************
*
* b u g _ a s s e r t
*
**************************************
*
* Functional description
* Disastrous lock manager bug. Issue message and abort process.
*
**************************************/
TEXT buffer[MAXPATHLEN + 100];
lhb LOCK_header_copy;
sprintf((char*) buffer, "%s %" ULONGFORMAT": lock assertion failure: %.60s\n",
__FILE__, line, string);
// Copy the shared memory so we can examine its state when we crashed
LOCK_header_copy = *m_sharedMemory->getHeader();
bug(NULL, buffer); // Never returns
}
void LockManager::bug(CheckStatusWrapper* statusVector, const TEXT* string)
{
/**************************************
*
* b u g
*
**************************************
*
* Functional description
* Disastrous lock manager bug. Issue message and abort process.
*
**************************************/
TEXT s[2 * MAXPATHLEN];
#ifdef WIN_NT
sprintf(s, "Fatal lock manager error: %s, errno: %ld", string, ERRNO);
#else
sprintf(s, "Fatal lock manager error: %s, errno: %d", string, ERRNO);
#endif
#if !(defined WIN_NT)
// The strerror() function returns the appropriate description string,
// or an unknown error message if the error code is unknown.
if (errno)
{
strcat(s, "\n--");
strcat(s, strerror(errno));
}
#endif
if (!m_bugcheck)
{
m_bugcheck = true;
const lhb* const header = m_sharedMemory ? m_sharedMemory->getHeader() : nullptr;
if (header)
{
// The lock table has some problem - copy it for later analysis
TEXT buffer[MAXPATHLEN];
gds__prefix_lock(buffer, "fb_lock_table.dump");
const TEXT* const lock_file = buffer;
FILE* const fd = os_utils::fopen(lock_file, "wb");
if (fd)
{
FB_UNUSED(fwrite(header, 1, header->lhb_used, fd));
fclose(fd);
}
// If the current mutex acquirer is in the same process, release the mutex
if (header->lhb_active_owner > 0)
{
const own* const owner = (own*) SRQ_ABS_PTR(header->lhb_active_owner);
const prc* const process = (prc*) SRQ_ABS_PTR(owner->own_process);
if (process->prc_process_id == PID)
release_shmem(header->lhb_active_owner);
}
}
if (statusVector)
{
(Arg::Gds(isc_lockmanerr) <<
Arg::Gds(isc_random) << Arg::Str(string) <<
Arg::StatusVector(statusVector)).copyTo(statusVector);
return;
}
}
#ifdef DEV_BUILD
/* In the worst case this code makes it possible to attach live process
* and see shared memory data.
if (isatty(2))
fprintf(stderr, "Attach to pid=%d\n", getpid());
else
gds__log("Attach to pid=%d\n", getpid());
sleep(120);
*/
#endif
fb_utils::logAndDie(s);
}
SRQ_PTR LockManager::create_owner(CheckStatusWrapper* statusVector,
LOCK_OWNER_T owner_id,
UCHAR owner_type)
{
/**************************************
*
* c r e a t e _ o w n e r
*
**************************************
*
* Functional description
* Create an owner block.
*
**************************************/
if (m_sharedMemory->getHeader()->mhb_type != SharedMemoryBase::SRAM_LOCK_MANAGER ||
m_sharedMemory->getHeader()->mhb_header_version != MemoryHeader::HEADER_VERSION ||
m_sharedMemory->getHeader()->mhb_version != LHB_VERSION)
{
TEXT bug_buffer[BUFFER_TINY];
sprintf(bug_buffer, "inconsistent lock table type/version; found %d/%d:%d, expected %d/%d:%d",
m_sharedMemory->getHeader()->mhb_type,
m_sharedMemory->getHeader()->mhb_header_version,
m_sharedMemory->getHeader()->mhb_version,
SharedMemoryBase::SRAM_LOCK_MANAGER, MemoryHeader::HEADER_VERSION, LHB_VERSION);
bug(statusVector, bug_buffer);
return 0;
}
// Allocate a process block, if required
if (!m_processOffset)
{
if (!create_process(statusVector))
return 0;
}
// Look for a previous instance of owner. If we find one, get rid of it.
srq* lock_srq;
SRQ_LOOP(m_sharedMemory->getHeader()->lhb_owners, lock_srq)
{
own* owner = (own*) ((UCHAR*) lock_srq - offsetof(own, own_lhb_owners));
if (owner->own_owner_id == owner_id && (UCHAR) owner->own_owner_type == owner_type)
{
purge_owner(DUMMY_OWNER, owner); // purging owner_offset has not been set yet
break;
}
}
// Allocate an owner block
own* owner = 0;
if (SRQ_EMPTY(m_sharedMemory->getHeader()->lhb_free_owners))
{
if (!(owner = (own*) alloc(sizeof(own), statusVector)))
return 0;
}
else
{
owner = (own*) ((UCHAR*) SRQ_NEXT(m_sharedMemory->getHeader()->lhb_free_owners) -
offsetof(own, own_lhb_owners));
remove_que(&owner->own_lhb_owners);
}
if (!init_owner_block(statusVector, owner, owner_type, owner_id))
return 0;
insert_tail(&m_sharedMemory->getHeader()->lhb_owners, &owner->own_lhb_owners);
prc* const process = (prc*) SRQ_ABS_PTR(owner->own_process);
insert_tail(&process->prc_owners, &owner->own_prc_owners);
probe_processes();
return SRQ_REL_PTR(owner);
}
bool LockManager::create_process(CheckStatusWrapper* statusVector)
{
/**************************************
*
* c r e a t e _ p r o c e s s
*
**************************************
*
* Functional description
* Create a process block.
*
**************************************/
srq* lock_srq;
SRQ_LOOP(m_sharedMemory->getHeader()->lhb_processes, lock_srq)
{
prc* process = (prc*) ((UCHAR*) lock_srq - offsetof(prc, prc_lhb_processes));
if (process->prc_process_id == PID)
{
purge_process(process);
break;
}
}
prc* process = NULL;
if (SRQ_EMPTY(m_sharedMemory->getHeader()->lhb_free_processes))
{
if (!(process = (prc*) alloc(sizeof(prc), statusVector)))
return false;
}
else
{
process = (prc*) ((UCHAR*) SRQ_NEXT(m_sharedMemory->getHeader()->lhb_free_processes) -
offsetof(prc, prc_lhb_processes));
remove_que(&process->prc_lhb_processes);
}
process->prc_type = type_lpr;
process->prc_process_id = PID;
SRQ_INIT(process->prc_owners);
SRQ_INIT(process->prc_lhb_processes);
process->prc_flags = 0;
insert_tail(&m_sharedMemory->getHeader()->lhb_processes, &process->prc_lhb_processes);
if (m_sharedMemory->eventInit(&process->prc_blocking) != FB_SUCCESS)
{
(Arg::StatusVector(statusVector) << Arg::Gds(isc_lockmanerr) <<
Arg::Gds(isc_random) << Arg::Str("process blocking event failed to initialize properly")).copyTo(statusVector);
return false;
}
m_processOffset = SRQ_REL_PTR(process);
#if defined HAVE_OBJECT_MAP
m_process = m_sharedMemory->mapObject<prc>(statusVector, m_processOffset);
#else
m_process = process;
#endif
if (!m_process)
return false;
if (m_useBlockingThread)
{
try
{
m_cleanupSync.run(this);
}
catch (const Exception& ex)
{
(Arg::Gds(isc_lockmanerr) << Arg::StatusVector(ex) <<
Arg::Gds(isc_random) << Arg::Str("blocking thread failed to start")).copyTo(statusVector);
return false;
}
}
return true;
}
void LockManager::deadlock_clear()
{
/**************************************
*
* d e a d l o c k _ c l e a r
*
**************************************
*
* Functional description
* Clear deadlock and scanned bits for pending requests
* in preparation for a deadlock scan.
*
**************************************/
ASSERT_ACQUIRED;
srq* lock_srq;
SRQ_LOOP(m_sharedMemory->getHeader()->lhb_owners, lock_srq)
{
own* const owner = (own*) ((UCHAR*) lock_srq - offsetof(own, own_lhb_owners));
srq* lock_srq2;
SRQ_LOOP(owner->own_pending, lock_srq2)
{
lrq* const request = (lrq*) ((UCHAR*) lock_srq2 - offsetof(lrq, lrq_own_pending));
fb_assert(request->lrq_flags & LRQ_pending);
request->lrq_flags &= ~(LRQ_deadlock | LRQ_scanned);
}
}
}
lrq* LockManager::deadlock_scan(own* owner, lrq* request)
{
/**************************************
*
* d e a d l o c k _ s c a n
*
**************************************
*
* Functional description
* Given an owner block that has been stalled for some time, find
* a deadlock cycle if there is one. If a deadlock is found, return
* the address of a pending lock request in the deadlock request.
* If no deadlock is found, return null.
*
**************************************/
LOCK_TRACE(("deadlock_scan: owner %ld request %ld\n", SRQ_REL_PTR(owner),
SRQ_REL_PTR(request)));
ASSERT_ACQUIRED;
++(m_sharedMemory->getHeader()->lhb_scans);
post_history(his_scan, request->lrq_owner, request->lrq_lock, SRQ_REL_PTR(request), true);
deadlock_clear();
#ifdef VALIDATE_LOCK_TABLE
validate_lhb(m_sharedMemory->getHeader());
#endif
bool maybe_deadlock = false;
lrq* victim = deadlock_walk(request, &maybe_deadlock);
// Only when it is certain that this request is not part of a deadlock do we
// mark this request as 'scanned' so that we will not check this request again.
// Note that this request might be part of multiple deadlocks.
if (!victim && !maybe_deadlock)
owner->own_flags |= OWN_scanned;
#ifdef DEBUG_LM
else if (!victim && maybe_deadlock)
DEBUG_MSG(0, ("deadlock_scan: not marking due to maybe_deadlock\n"));
#endif
return victim;
}
lrq* LockManager::deadlock_walk(lrq* request, bool* maybe_deadlock)
{
/**************************************
*
* d e a d l o c k _ w a l k
*
**************************************
*
* Functional description
* Given a request that is waiting, determine whether a deadlock has
* occurred.
*
**************************************/
// If this request was scanned for deadlock earlier than don't visit it again
if (request->lrq_flags & LRQ_scanned)
return NULL;
// If this request has been seen already during this deadlock-walk, then we
// detected a circle in the wait-for graph. Return "deadlock".
if (request->lrq_flags & LRQ_deadlock)
{
#ifdef DEBUG_TRACE_DEADLOCKS
const own* owner = (own*) SRQ_ABS_PTR(request->lrq_owner);
const prc* proc = (prc*) SRQ_ABS_PTR(owner->own_process);
gds__log("deadlock chain: OWNER BLOCK %6" SLONGFORMAT"\tProcess id: %6d\tFlags: 0x%02X ",
request->lrq_owner, proc->prc_process_id, owner->own_flags);
#endif
return request;
}
// Remember that this request is part of the wait-for graph
request->lrq_flags |= LRQ_deadlock;
// Check if this is a conversion request
const bool conversion = (request->lrq_state > LCK_null);
// Find the parent lock of the request
lbl* lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
// Loop thru the requests granted against the lock. If any granted request is
// blocking the request we're handling, recurse to find what's blocking him.
srq* lock_srq;
SRQ_LOOP(lock->lbl_requests, lock_srq)
{
lrq* block = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_lbl_requests));
if (conversion)
{
// Don't pursue our own lock-request again
if (request == block)
continue;
// Since lock conversions can't follow the fairness rules (to avoid
// deadlocks), only granted lock requests need to be examined.
// If lock-ordering is turned off (opening the door for starvation),
// only granted requests can block our request.
if (compatibility[request->lrq_requested][block->lrq_state])
continue;
}
else
{
// Don't pursue our own lock-request again. In addition, don't look
// at requests that arrived after our request because lock-ordering
// is in effect.
if (request == block)
break;
// Since lock ordering is in effect, granted locks and waiting
// requests that arrived before our request could block us
const UCHAR max_state = MAX(block->lrq_state, block->lrq_requested);
if (compatibility[request->lrq_requested][max_state])
{
continue;
}
}
// Don't pursue lock owners that still have to finish processing their AST.
// If the blocking queue is not empty, then the owner still has some
// AST's to process (or lock reposts).
// hvlad: also lock maybe just granted to owner and blocked owners have no
// time to send blocking AST
// Remember this fact because they still might be part of a deadlock.
own* const owner = (own*) SRQ_ABS_PTR(block->lrq_owner);
if ((owner->own_flags & (OWN_signaled | OWN_wakeup)) || !SRQ_EMPTY((owner->own_blocks)) ||
(block->lrq_flags & LRQ_just_granted))
{
*maybe_deadlock = true;
continue;
}
// YYY: Note: can the below code be moved to the
// start of this block? Before the OWN_signaled check?
srq* lock_srq2;
SRQ_LOOP(owner->own_pending, lock_srq2)
{
lrq* target = (lrq*) ((UCHAR*) lock_srq2 - offsetof(lrq, lrq_own_pending));
fb_assert(target->lrq_flags & LRQ_pending);
// hvlad: don't pursue requests that are waiting with a timeout
// as such a circle in the wait-for graph will be broken automatically
// when the permitted timeout expires
if (target->lrq_flags & LRQ_wait_timeout) {
continue;
}
// Check who is blocking the request whose owner is blocking the input request
if (target = deadlock_walk(target, maybe_deadlock))
{
#ifdef DEBUG_TRACE_DEADLOCKS
const own* const owner2 = (own*) SRQ_ABS_PTR(request->lrq_owner);
const prc* const proc = (prc*) SRQ_ABS_PTR(owner2->own_process);
gds__log("deadlock chain: OWNER BLOCK %6" SLONGFORMAT"\tProcess id: %6d\tFlags: 0x%02X ",
request->lrq_owner, proc->prc_process_id, owner2->own_flags);
#endif
return target;
}
}
}
// This branch of the wait-for graph is exhausted, the current waiting
// request is not part of a deadlock
request->lrq_flags &= ~LRQ_deadlock;
request->lrq_flags |= LRQ_scanned;
return NULL;
}
#ifdef DEBUG_LM
static ULONG delay_count = 0;
static ULONG last_signal_line = 0;
static ULONG last_delay_line = 0;
void LockManager::debug_delay(ULONG lineno)
{
/**************************************
*
* d e b u g _ d e l a y
*
**************************************
*
* Functional description
* This is a debugging routine, the purpose of which is to slow
* down operations in order to expose windows of critical
* sections.
*
**************************************/
ULONG i;
// Delay for a while
last_delay_line = lineno;
for (i = 0; i < 10000; i++)
; // Nothing
// Occasionally crash for robustness testing
/*
if ((delay_count % 500) == 0)
exit (-1);
*/
for (i = 0; i < 10000; i++)
; // Nothing
}
#endif
lbl* LockManager::find_lock(USHORT series,
const UCHAR* value,
USHORT length,
USHORT* slot)
{
/**************************************
*
* f i n d _ l o c k
*
**************************************
*
* Functional description
* Find a lock block given a resource
* name. If it doesn't exist, the hash
* slot will be useful for enqueing a
* lock.
*
**************************************/
// See if the lock already exists
const USHORT hash_slot = *slot =
(USHORT) InternalHash::hash(length, value, m_sharedMemory->getHeader()->lhb_hash_slots);
ASSERT_ACQUIRED;
srq* const hash_header = &m_sharedMemory->getHeader()->lhb_hash[hash_slot];
for (srq* lock_srq = (SRQ) SRQ_ABS_PTR(hash_header->srq_forward);
lock_srq != hash_header; lock_srq = (SRQ) SRQ_ABS_PTR(lock_srq->srq_forward))
{
lbl* lock = (lbl*) ((UCHAR*) lock_srq - offsetof(lbl, lbl_lhb_hash));
if (lock->lbl_series != series || lock->lbl_length != length)
{
continue;
}
if (!length || !memcmp(value, lock->lbl_key, length))
return lock;
}
return NULL;
}
lrq* LockManager::get_request(SRQ_PTR offset)
{
/**************************************
*
* g e t _ r e q u e s t
*
**************************************
*
* Functional description
* Locate and validate user supplied request offset.
*
**************************************/
TEXT s[BUFFER_TINY];
lrq* request = (lrq*) SRQ_ABS_PTR(offset);
if (offset == -1 || request->lrq_type != type_lrq)
{
sprintf(s, "invalid lock id (%" SLONGFORMAT")", offset);
bug(NULL, s);
}
const lbl* lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
if (lock->lbl_type != type_lbl)
{
sprintf(s, "invalid lock (%" SLONGFORMAT")", offset);
bug(NULL, s);
}
return request;
}
void LockManager::grant(lrq* request, lbl* lock)
{
/**************************************
*
* g r a n t
*
**************************************
*
* Functional description
* Grant a lock request. If the lock is a conversion, assume the caller
* has already decremented the former lock type count in the lock block.
*
**************************************/
// Request must be for THIS lock
CHECK(SRQ_REL_PTR(lock) == request->lrq_lock);
post_history(his_grant, request->lrq_owner, request->lrq_lock, SRQ_REL_PTR(request), true);
++lock->lbl_counts[request->lrq_requested];
request->lrq_state = request->lrq_requested;
if (request->lrq_data)
{
remove_que(&lock->lbl_lhb_data);
if ( (lock->lbl_data = request->lrq_data) )
insert_data_que(lock);
request->lrq_data = 0;
}
lock->lbl_state = lock_state(lock);
if (request->lrq_flags & LRQ_pending)
{
remove_que(&request->lrq_own_pending);
request->lrq_flags &= ~LRQ_pending;
lock->lbl_pending_lrq_count--;
}
post_wakeup((own*) SRQ_ABS_PTR(request->lrq_owner));
}
bool LockManager::grant_or_que(thread_db* tdbb, lrq* request, lbl* lock, SSHORT lck_wait)
{
/**************************************
*
* g r a n t _ o r _ q u e
*
**************************************
*
* Functional description
* There is a request against an existing lock. If the request
* is compatible with the lock, grant it. Otherwise lock_srq it.
* If the lock is lock_srq-ed, set up the machinery to do a deadlock
* scan in awhile.
*
**************************************/
request->lrq_lock = SRQ_REL_PTR(lock);
// Compatible requests are easy to satify. Just post the request to the lock,
// update the lock state, release the data structure, and we're done.
if (compatibility[request->lrq_requested][lock->lbl_state])
{
if (request->lrq_requested == LCK_null || lock->lbl_pending_lrq_count == 0)
{
grant(request, lock);
post_pending(lock);
return true;
}
}
// The request isn't compatible with the current state of the lock.
// If we haven't be asked to wait for the lock, return now.
if (lck_wait)
{
const SRQ_PTR request_offset = SRQ_REL_PTR(request);
wait_for_request(tdbb, request, lck_wait);
request = (lrq*) SRQ_ABS_PTR(request_offset);
if (!(request->lrq_flags & LRQ_rejected))
return true;
}
post_history(his_deny, request->lrq_owner, request->lrq_lock, SRQ_REL_PTR(request), true);
ASSERT_ACQUIRED;
++(m_sharedMemory->getHeader()->lhb_denies);
if (lck_wait < 0)
++(m_sharedMemory->getHeader()->lhb_timeouts);
release_request(request);
return false;
}
bool LockManager::init_owner_block(CheckStatusWrapper* statusVector, own* owner, UCHAR owner_type,
LOCK_OWNER_T owner_id)
{
/**************************************
*
* i n i t _ o w n e r _ b l o c k
*
**************************************
*
* Functional description
* Initialize the passed owner block nice and new.
*
**************************************/
owner->own_type = type_own;
owner->own_owner_type = owner_type;
owner->own_flags = 0;
owner->own_count = 1;
owner->own_owner_id = owner_id;
owner->own_process = m_processOffset;
owner->own_thread_id = 0;
SRQ_INIT(owner->own_lhb_owners);
SRQ_INIT(owner->own_prc_owners);
SRQ_INIT(owner->own_requests);
SRQ_INIT(owner->own_blocks);
SRQ_INIT(owner->own_pending);
owner->own_acquire_time = 0;
owner->own_waits = 0;
owner->own_ast_count = 0;
if (m_sharedMemory->eventInit(&owner->own_wakeup) != FB_SUCCESS)
{
(Arg::StatusVector(statusVector) << Arg::Gds(isc_lockmanerr) <<
Arg::Gds(isc_random) << Arg::Str("owner wakeup event failed initialization")).copyTo(statusVector);
return false;
}
return true;
}
bool LockManager::initialize(SharedMemoryBase* sm, bool initializeMemory)
{
/**************************************
*
* i n i t i a l i z e
*
**************************************
*
* Functional description
* Initialize the lock header block. The caller is assumed
* to have an exclusive lock on the lock file.
*
**************************************/
// reset m_sharedMemory in advance to be able to use SRQ_BASE macro
m_sharedMemory.reset(reinterpret_cast<SharedMemory<lhb>*>(sm));
#ifdef USE_SHMEM_EXT
if (m_extents.getCount() == 0)
{
Extent zero;
zero = *this;
m_extents.push(zero);
}
#endif
if (!initializeMemory)
return true;
lhb* hdr = m_sharedMemory->getHeader();
memset(hdr, 0, sizeof(lhb));
hdr->init(SharedMemoryBase::SRAM_LOCK_MANAGER, LHB_VERSION);
hdr->lhb_type = type_lhb;
// Mark ourselves as active owner to prevent fb_assert() checks
hdr->lhb_active_owner = DUMMY_OWNER; // In init of lock system
SRQ_INIT(hdr->lhb_processes);
SRQ_INIT(hdr->lhb_owners);
SRQ_INIT(hdr->lhb_free_processes);
SRQ_INIT(hdr->lhb_free_owners);
SRQ_INIT(hdr->lhb_free_locks);
SRQ_INIT(hdr->lhb_free_requests);
int hash_slots = m_config->getLockHashSlots();
if (hash_slots < HASH_MIN_SLOTS)
hash_slots = HASH_MIN_SLOTS;
if (hash_slots > HASH_MAX_SLOTS)
hash_slots = HASH_MAX_SLOTS;
hdr->lhb_hash_slots = (USHORT) hash_slots;
hdr->lhb_scan_interval = m_config->getDeadlockTimeout();
hdr->lhb_acquire_spins = m_acquireSpins;
// Initialize lock series data queues and lock hash chains
USHORT i;
SRQ lock_srq;
for (i = 0, lock_srq = hdr->lhb_data; i < LCK_MAX_SERIES; i++, lock_srq++)
{
SRQ_INIT((*lock_srq));
}
for (i = 0, lock_srq = hdr->lhb_hash; i < hdr->lhb_hash_slots; i++, lock_srq++)
{
SRQ_INIT((*lock_srq));
}
// Set lock_ordering flag for the first time
const ULONG length = sizeof(lhb) + (hdr->lhb_hash_slots * sizeof(hdr->lhb_hash[0]));
hdr->lhb_length = m_sharedMemory->sh_mem_length_mapped;
hdr->lhb_used = FB_ALIGN(length, FB_ALIGNMENT);
shb* secondary_header = (shb*) alloc(sizeof(shb), NULL);
if (!secondary_header)
{
fb_utils::logAndDie("Fatal lock manager error: lock manager out of room");
}
hdr->lhb_secondary = SRQ_REL_PTR(secondary_header);
secondary_header->shb_type = type_shb;
secondary_header->shb_remove_node = 0;
secondary_header->shb_insert_que = 0;
secondary_header->shb_insert_prior = 0;
// Allocate a sufficiency of history blocks
his* history = NULL;
for (USHORT j = 0; j < 2; j++)
{
SRQ_PTR* prior = (j == 0) ? &hdr->lhb_history : &secondary_header->shb_history;
for (i = 0; i < HISTORY_BLOCKS; i++)
{
if (!(history = (his*) alloc(sizeof(his), NULL)))
{
fb_utils::logAndDie("Fatal lock manager error: lock manager out of room");
}
*prior = SRQ_REL_PTR(history);
history->his_type = type_his;
history->his_operation = 0;
prior = &history->his_next;
}
history->his_next = (j == 0) ? hdr->lhb_history : secondary_header->shb_history;
}
// Done initializing, unmark owner information
hdr->lhb_active_owner = 0;
return true;
}
void LockManager::insert_data_que(lbl* lock)
{
/**************************************
*
* i n s e r t _ d a t a _ q u e
*
**************************************
*
* Functional description
* Insert a node in the lock series data queue
* in sorted (ascending) order by lock data.
*
**************************************/
if (lock->lbl_series < LCK_MAX_SERIES && lock->lbl_data)
{
SRQ data_header = &m_sharedMemory->getHeader()->lhb_data[lock->lbl_series];
SRQ lock_srq;
for (lock_srq = (SRQ) SRQ_ABS_PTR(data_header->srq_forward);
lock_srq != data_header; lock_srq = (SRQ) SRQ_ABS_PTR(lock_srq->srq_forward))
{
const lbl* lock2 = (lbl*) ((UCHAR*) lock_srq - offsetof(lbl, lbl_lhb_data));
CHECK(lock2->lbl_series == lock->lbl_series);
if (lock->lbl_data <= lock2->lbl_data)
break;
}
insert_tail(lock_srq, &lock->lbl_lhb_data);
}
}
void LockManager::insert_tail(SRQ lock_srq, SRQ node)
{
/**************************************
*
* i n s e r t _ t a i l
*
**************************************
*
* Functional description
* Insert a node at the tail of a lock_srq.
*
* To handle the event of the process terminating during
* the insertion of the node, we set values in the shb to
* indicate the node being inserted.
* Then, should we be unable to complete
* the node insert, the next process into the lock table
* will notice the uncompleted work and undo it,
* eg: it will put the queue back to the state
* prior to the insertion being started.
*
**************************************/
ASSERT_ACQUIRED;
shb* const recover = (shb*) SRQ_ABS_PTR(m_sharedMemory->getHeader()->lhb_secondary);
DEBUG_DELAY;
recover->shb_insert_que = SRQ_REL_PTR(lock_srq);
DEBUG_DELAY;
recover->shb_insert_prior = lock_srq->srq_backward;
DEBUG_DELAY;
node->srq_forward = SRQ_REL_PTR(lock_srq);
DEBUG_DELAY;
node->srq_backward = lock_srq->srq_backward;
DEBUG_DELAY;
SRQ prior = (SRQ) SRQ_ABS_PTR(lock_srq->srq_backward);
DEBUG_DELAY;
prior->srq_forward = SRQ_REL_PTR(node);
DEBUG_DELAY;
lock_srq->srq_backward = SRQ_REL_PTR(node);
DEBUG_DELAY;
recover->shb_insert_que = 0;
DEBUG_DELAY;
recover->shb_insert_prior = 0;
DEBUG_DELAY;
}
bool LockManager::internal_convert(thread_db* tdbb,
CheckStatusWrapper* statusVector,
SRQ_PTR request_offset,
UCHAR type,
SSHORT lck_wait,
lock_ast_t ast_routine,
void* ast_argument)
{
/**************************************
*
* i n t e r n a l _ c o n v e r t
*
**************************************
*
* Functional description
* Perform a lock conversion, if possible. If the lock cannot be
* granted immediately, either return immediately or wait depending
* on a wait flag. If the lock is granted return true, otherwise
* return false. Note: if the conversion would cause a deadlock,
* false is returned even if wait was requested.
*
**************************************/
ASSERT_ACQUIRED;
lrq* request = get_request(request_offset);
lbl* lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
const SRQ_PTR owner_offset = request->lrq_owner;
post_history(his_convert, owner_offset, request->lrq_lock, request_offset, true);
request->lrq_requested = type;
request->lrq_flags &= ~LRQ_blocking_seen;
// Compute the state of the lock without the request
--lock->lbl_counts[request->lrq_state];
const UCHAR temp = lock_state(lock);
// If the requested lock level is compatible with the current state
// of the lock, just grant the request. Easy enough.
if (compatibility[type][temp])
{
request->lrq_ast_routine = ast_routine;
request->lrq_ast_argument = ast_argument;
grant(request, lock);
post_pending(lock);
return true;
}
++lock->lbl_counts[request->lrq_state];
// If we weren't requested to wait, just forget about the whole thing.
// Otherwise wait for the request to be granted or rejected.
if (lck_wait)
{
bool new_ast;
if (request->lrq_ast_routine != ast_routine || request->lrq_ast_argument != ast_argument)
{
new_ast = true;
}
else
new_ast = false;
wait_for_request(tdbb, request, lck_wait);
request = (lrq*) SRQ_ABS_PTR(request_offset);
lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
if (!(request->lrq_flags & LRQ_rejected))
{
if (new_ast)
{
request = (lrq*) SRQ_ABS_PTR(request_offset);
request->lrq_ast_routine = ast_routine;
request->lrq_ast_argument = ast_argument;
}
return true;
}
post_pending(lock);
}
request->lrq_requested = request->lrq_state;
ASSERT_ACQUIRED;
++(m_sharedMemory->getHeader()->lhb_denies);
if (lck_wait < 0)
++(m_sharedMemory->getHeader()->lhb_timeouts);
(Arg::Gds(lck_wait > 0 ? isc_deadlock : lck_wait < 0 ? isc_lock_timeout :
isc_lock_conflict)).copyTo(statusVector);
return false;
}
void LockManager::internal_dequeue(SRQ_PTR request_offset)
{
/**************************************
*
* i n t e r n a l _ d e q u e u e
*
**************************************
*
* Functional description
* Release an outstanding lock.
*
**************************************/
// Acquire the data structure, and compute addresses of both lock
// request and lock
lrq* request = get_request(request_offset);
post_history(his_deq, request->lrq_owner, request->lrq_lock, request_offset, true);
request->lrq_ast_routine = NULL;
release_request(request);
}
USHORT LockManager::lock_state(const lbl* lock)
{
/**************************************
*
* l o c k _ s t a t e
*
**************************************
*
* Functional description
* Compute the current state of a lock.
*
**************************************/
if (lock->lbl_counts[LCK_EX])
return LCK_EX;
if (lock->lbl_counts[LCK_PW])
return LCK_PW;
if (lock->lbl_counts[LCK_SW])
return LCK_SW;
if (lock->lbl_counts[LCK_PR])
return LCK_PR;
if (lock->lbl_counts[LCK_SR])
return LCK_SR;
if (lock->lbl_counts[LCK_null])
return LCK_null;
return LCK_none;
}
void LockManager::post_blockage(thread_db* tdbb, lrq* request, lbl* lock)
{
/**************************************
*
* p o s t _ b l o c k a g e
*
**************************************
*
* Functional description
* The current request is blocked. Post blocking notices to
* any process blocking the request.
*
**************************************/
const SRQ_PTR owner_offset = request->lrq_owner;
const own* owner = (own*) SRQ_ABS_PTR(owner_offset);
const SRQ_PTR request_offset = SRQ_REL_PTR(request);
const SRQ_PTR lock_offset = SRQ_REL_PTR(lock);
ASSERT_ACQUIRED;
CHECK(request->lrq_flags & LRQ_pending);
HalfStaticArray<SRQ_PTR, 16> blocking_owners;
SRQ lock_srq;
SRQ_LOOP(lock->lbl_requests, lock_srq)
{
lrq* const block = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_lbl_requests));
own* const blocking_owner = (own*) SRQ_ABS_PTR(block->lrq_owner);
// Figure out if this lock request is blocking our own lock request.
// Of course, our own request cannot block ourselves. Compatible
// requests don't block us, and if there is no AST routine for the
// request the block doesn't matter as we can't notify anyone.
// If the owner has marked the request with LRQ_blocking_seen
// then the blocking AST has been delivered and the owner promises
// to release the lock as soon as possible (so don't bug the owner).
if (block == request ||
blocking_owner == owner ||
compatibility[request->lrq_requested][block->lrq_state] ||
!block->lrq_ast_routine ||
(block->lrq_flags & LRQ_blocking_seen))
{
continue;
}
// Add the blocking request to the list of blocks if it's not
// there already (LRQ_blocking)
if (!(block->lrq_flags & LRQ_blocking))
{
insert_tail(&blocking_owner->own_blocks, &block->lrq_own_blocks);
block->lrq_flags |= LRQ_blocking;
block->lrq_flags &= ~(LRQ_blocking_seen | LRQ_just_granted);
}
blocking_owners.add(block->lrq_owner);
if (block->lrq_state == LCK_EX)
break;
}
HalfStaticArray<SRQ_PTR, 16> dead_processes;
for (SRQ_PTR* iter = blocking_owners.begin(); iter != blocking_owners.end(); ++iter)
{
own* const blocking_owner = (own*) SRQ_ABS_PTR(*iter);
if (blocking_owner->own_count &&
!(blocking_owner->own_flags & OWN_signaled) &&
!signal_owner(tdbb, blocking_owner))
{
dead_processes.add(blocking_owner->own_process);
}
}
for (SRQ_PTR* iter = dead_processes.begin(); iter != dead_processes.end(); ++iter)
{
prc* const process = (prc*) SRQ_ABS_PTR(*iter);
if (process->prc_process_id)
purge_process(process);
}
}
void LockManager::post_history(USHORT operation,
SRQ_PTR process,
SRQ_PTR lock,
SRQ_PTR request,
bool old_version)
{
/**************************************
*
* p o s t _ h i s t o r y
*
**************************************
*
* Functional description
* Post a history item.
*
**************************************/
his* history;
if (old_version)
{
history = (his*) SRQ_ABS_PTR(m_sharedMemory->getHeader()->lhb_history);
ASSERT_ACQUIRED;
m_sharedMemory->getHeader()->lhb_history = history->his_next;
}
else
{
ASSERT_ACQUIRED;
shb* recover = (shb*) SRQ_ABS_PTR(m_sharedMemory->getHeader()->lhb_secondary);
history = (his*) SRQ_ABS_PTR(recover->shb_history);
recover->shb_history = history->his_next;
}
history->his_operation = operation;
history->his_process = process;
history->his_lock = lock;
history->his_request = request;
}
void LockManager::post_pending(lbl* lock)
{
/**************************************
*
* p o s t _ p e n d i n g
*
**************************************
*
* Functional description
* There has been a change in state of a lock. Check pending
* requests to see if something can be granted. If so, do it.
*
**************************************/
#ifdef DEV_BUILD
USHORT pending_counter = 0;
#endif
if (lock->lbl_pending_lrq_count == 0)
return;
// Loop thru granted requests looking for pending conversions. If one
// is found, check to see if it can be granted. Even if a request cannot
// be granted for compatibility reason, post_wakeup () that owner so that
// it can post_blockage() to the newly granted owner of the lock.
srq* lock_srq;
SRQ_LOOP(lock->lbl_requests, lock_srq)
{
lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_lbl_requests));
if (!(request->lrq_flags & LRQ_pending))
continue;
if (request->lrq_state)
{
--lock->lbl_counts[request->lrq_state];
const UCHAR temp_state = lock_state(lock);
if (compatibility[request->lrq_requested][temp_state])
grant(request, lock);
else
{
#ifdef DEV_BUILD
pending_counter++;
#endif
++lock->lbl_counts[request->lrq_state];
own* owner = (own*) SRQ_ABS_PTR(request->lrq_owner);
post_wakeup(owner);
CHECK(lock->lbl_pending_lrq_count >= pending_counter);
break;
}
}
else if (compatibility[request->lrq_requested][lock->lbl_state])
grant(request, lock);
else
{
#ifdef DEV_BUILD
pending_counter++;
#endif
own* owner = (own*) SRQ_ABS_PTR(request->lrq_owner);
post_wakeup(owner);
CHECK(lock->lbl_pending_lrq_count >= pending_counter);
break;
}
}
CHECK(lock->lbl_pending_lrq_count >= pending_counter);
if (lock->lbl_pending_lrq_count)
{
SRQ_LOOP(lock->lbl_requests, lock_srq)
{
lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_lbl_requests));
if (request->lrq_flags & LRQ_pending)
break;
if (!(request->lrq_flags & (LRQ_blocking | LRQ_blocking_seen)) &&
request->lrq_ast_routine)
{
request->lrq_flags |= LRQ_just_granted;
}
}
}
}
void LockManager::post_wakeup(own* owner)
{
/**************************************
*
* p o s t _ w a k e u p
*
**************************************
*
* Functional description
* Wakeup whoever is waiting on a lock.
*
**************************************/
if (owner->own_waits)
{
++(m_sharedMemory->getHeader()->lhb_wakeups);
owner->own_flags |= OWN_wakeup;
(void) m_sharedMemory->eventPost(&owner->own_wakeup);
}
}
bool LockManager::probe_processes()
{
/**************************************
*
* p r o b e _ p r o c e s s e s
*
**************************************
*
* Functional description
* Probe processes to see if any has died. If one has, get rid of it.
*
**************************************/
ASSERT_ACQUIRED;
bool purged = false;
SRQ lock_srq;
SRQ_LOOP(m_sharedMemory->getHeader()->lhb_processes, lock_srq)
{
prc* const process = (prc*) ((UCHAR*) lock_srq - offsetof(prc, prc_lhb_processes));
if (process->prc_process_id != PID && !ISC_check_process_existence(process->prc_process_id))
{
lock_srq = SRQ_PREV((*lock_srq));
purge_process(process);
purged = true;
}
}
return purged;
}
void LockManager::purge_owner(SRQ_PTR purging_owner_offset, own* owner)
{
/**************************************
*
* p u r g e _ o w n e r
*
**************************************
*
* Functional description
* Purge an owner and all of its associated locks.
*
**************************************/
LOCK_TRACE(("purge_owner (%ld)\n", purging_owner_offset));
post_history(his_del_owner, purging_owner_offset, SRQ_REL_PTR(owner), 0, false);
// Release any locks that are active
SRQ lock_srq;
while ((lock_srq = SRQ_NEXT(owner->own_requests)) != &owner->own_requests)
{
lrq* request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_own_requests));
release_request(request);
}
// Release any repost requests left dangling on blocking queue
while ((lock_srq = SRQ_NEXT(owner->own_blocks)) != &owner->own_blocks)
{
lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_own_blocks));
remove_que(&request->lrq_own_blocks);
request->lrq_type = type_null;
insert_tail(&m_sharedMemory->getHeader()->lhb_free_requests, &request->lrq_lbl_requests);
}
// Release owner block
remove_que(&owner->own_prc_owners);
remove_que(&owner->own_lhb_owners);
insert_tail(&m_sharedMemory->getHeader()->lhb_free_owners, &owner->own_lhb_owners);
owner->own_owner_type = 0;
owner->own_owner_id = 0;
owner->own_process = 0;
owner->own_flags = 0;
m_sharedMemory->eventFini(&owner->own_wakeup);
}
void LockManager::purge_process(prc* process)
{
/**************************************
*
* p u r g e _ p r o c e s s
*
**************************************
*
* Functional description
* Purge all owners of the given process.
*
**************************************/
LOCK_TRACE(("purge_process (%ld)\n", process->prc_process_id));
SRQ lock_srq;
while ((lock_srq = SRQ_NEXT(process->prc_owners)) != &process->prc_owners)
{
own* owner = (own*) ((UCHAR*) lock_srq - offsetof(own, own_prc_owners));
purge_owner(SRQ_REL_PTR(owner), owner);
}
remove_que(&process->prc_lhb_processes);
insert_tail(&m_sharedMemory->getHeader()->lhb_free_processes, &process->prc_lhb_processes);
process->prc_process_id = 0;
process->prc_flags = 0;
m_sharedMemory->eventFini(&process->prc_blocking);
}
void LockManager::remap_local_owners()
{
/**************************************
*
* r e m a p _ l o c a l _ o w n e r s
*
**************************************
*
* Functional description
* Wakeup all local (in-process) waiting owners
* and prepare them for the shared region being remapped.
*
**************************************/
if (!m_processOffset)
return;
fb_assert(m_process);
prc* const process = (prc*) SRQ_ABS_PTR(m_processOffset);
srq* lock_srq;
SRQ_LOOP(process->prc_owners, lock_srq)
{
own* const owner = (own*) ((UCHAR*) lock_srq - offsetof(own, own_prc_owners));
if (owner->own_waits)
{
if (m_sharedMemory->eventPost(&owner->own_wakeup) != FB_SUCCESS)
{
bug(NULL, "remap failed: ISC_event_post() failed");
}
}
}
while (m_waitingOwners.value() > 0)
Thread::sleep(1);
}
void LockManager::remove_que(SRQ node)
{
/**************************************
*
* r e m o v e _ q u e
*
**************************************
*
* Functional description
* Remove a node from a self-relative lock_srq.
*
* To handle the event of the process terminating during
* the removal of the node, we set shb_remove_node to the
* node to be removed. Then, should we be unsuccessful
* in the node removal, the next process into the lock table
* will notice the uncompleted work and complete it.
*
* Note that the work is completed by again calling this routine,
* specifing the node to be removed. As the prior and following
* nodes may have changed prior to the crash, we need to redo the
* work only based on what is in <node>.
*
**************************************/
ASSERT_ACQUIRED;
shb* recover = (shb*) SRQ_ABS_PTR(m_sharedMemory->getHeader()->lhb_secondary);
DEBUG_DELAY;
recover->shb_remove_node = SRQ_REL_PTR(node);
DEBUG_DELAY;
SRQ lock_srq = (SRQ) SRQ_ABS_PTR(node->srq_forward);
// The next link might point back to us, or our prior link should
// the backlink change occur before a crash
CHECK(lock_srq->srq_backward == SRQ_REL_PTR(node) ||
lock_srq->srq_backward == node->srq_backward);
DEBUG_DELAY;
lock_srq->srq_backward = node->srq_backward;
DEBUG_DELAY;
lock_srq = (SRQ) SRQ_ABS_PTR(node->srq_backward);
// The prior link might point forward to us, or our following link should
// the change occur before a crash
CHECK(lock_srq->srq_forward == SRQ_REL_PTR(node) ||
lock_srq->srq_forward == node->srq_forward);
DEBUG_DELAY;
lock_srq->srq_forward = node->srq_forward;
DEBUG_DELAY;
recover->shb_remove_node = 0;
DEBUG_DELAY;
// To prevent trying to remove this entry a second time, which could occur
// for instance, when we're removing an owner, and crash while removing
// the owner's blocking requests, reset the lock_srq entry in this node.
// Note that if we get here, shb_remove_node has been cleared, so we
// no longer need the queue information.
SRQ_INIT((*node));
}
void LockManager::release_shmem(SRQ_PTR owner_offset)
{
/**************************************
*
* r e l e a s e _ s h m e m
*
**************************************
*
* Functional description
* Release the mapped lock file. Advance the event count to wake up
* anyone waiting for it. If there appear to be blocking items
* posted.
*
**************************************/
if (!m_sharedMemory->getHeader())
return;
if (owner_offset && m_sharedMemory->getHeader()->lhb_active_owner != owner_offset)
bug(NULL, "release when not owner");
#ifdef VALIDATE_LOCK_TABLE
// Validate the lock table occasionally (every 500 releases)
if ((m_sharedMemory->getHeader()->lhb_acquires % (HISTORY_BLOCKS / 2)) == 0)
validate_lhb(m_sharedMemory->getHeader());
#endif
if (!m_sharedMemory->getHeader()->lhb_active_owner)
bug(NULL, "release when not active");
DEBUG_DELAY;
m_sharedMemory->getHeader()->lhb_active_owner = 0;
m_sharedMemory->mutexUnlock();
DEBUG_DELAY;
}
void LockManager::release_request(lrq* request)
{
/**************************************
*
* r e l e a s e _ r e q u e s t
*
**************************************
*
* Functional description
* Release a request. This is called both by release lock
* and by the cleanup handler.
*
**************************************/
ASSERT_ACQUIRED;
// Start by disconnecting request from both lock and process
remove_que(&request->lrq_lbl_requests);
remove_que(&request->lrq_own_requests);
request->lrq_type = type_null;
insert_tail(&m_sharedMemory->getHeader()->lhb_free_requests, &request->lrq_lbl_requests);
lbl* const lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
// If the request is marked as blocking, clean it up
if (request->lrq_flags & LRQ_blocking)
{
remove_que(&request->lrq_own_blocks);
request->lrq_flags &= ~LRQ_blocking;
}
// Update counts if we are cleaning up something we're waiting on!
// This should only happen if we are purging out an owner that died.
if (request->lrq_flags & LRQ_pending)
{
remove_que(&request->lrq_own_pending);
request->lrq_flags &= ~LRQ_pending;
lock->lbl_pending_lrq_count--;
}
request->lrq_flags &= ~(LRQ_blocking_seen | LRQ_just_granted);
// If there are no outstanding requests, release the lock
if (SRQ_EMPTY(lock->lbl_requests))
{
CHECK(lock->lbl_pending_lrq_count == 0);
remove_que(&lock->lbl_lhb_hash);
remove_que(&lock->lbl_lhb_data);
lock->lbl_type = type_null;
insert_tail(&m_sharedMemory->getHeader()->lhb_free_locks, &lock->lbl_lhb_hash);
return;
}
// Re-compute the state of the lock and post any compatible pending requests
if ((request->lrq_state != LCK_none) && !(--lock->lbl_counts[request->lrq_state]))
{
lock->lbl_state = lock_state(lock);
if (request->lrq_state != LCK_null)
{
post_pending(lock);
return;
}
}
// If a lock enqueue failed because of a deadlock or timeout, the pending
// request may be holding up compatible, pending lock requests queued
// behind it.
// Or, even if this request had been granted, it's now being released,
// so we might be holding up requests or conversions queued up behind.
post_pending(lock);
}
bool LockManager::signal_owner(thread_db* tdbb, own* blocking_owner)
{
/**************************************
*
* s i g n a l _ o w n e r
*
**************************************
*
* Functional description
* Send a signal to a process.
*
* The second parameter is a possible offset to the
* blocked owner (or NULL), which is passed on to
* blocking_action().
*
**************************************/
ASSERT_ACQUIRED;
// If a process, other than ourselves, hasn't yet seen a signal
// that was sent, don't bother to send another one
DEBUG_DELAY;
blocking_owner->own_flags |= OWN_signaled;
DEBUG_DELAY;
prc* const process = (prc*) SRQ_ABS_PTR(blocking_owner->own_process);
// Deliver signal either locally or remotely
if (process->prc_process_id == PID)
{
DEBUG_DELAY;
blocking_action(tdbb, SRQ_REL_PTR(blocking_owner));
DEBUG_DELAY;
return true;
}
DEBUG_DELAY;
if (m_sharedMemory->eventPost(&process->prc_blocking) == FB_SUCCESS)
return true;
DEBUG_MSG(1, ("signal_owner - direct delivery failed\n"));
blocking_owner->own_flags &= ~OWN_signaled;
DEBUG_DELAY;
// We couldn't deliver signal. Let someone to purge the process.
return false;
}
const USHORT EXPECT_inuse = 0;
const USHORT EXPECT_freed = 1;
const USHORT RECURSE_yes = 0;
const USHORT RECURSE_not = 1;
void LockManager::validate_history(const SRQ_PTR history_header)
{
/**************************************
*
* v a l i d a t e _ h i s t o r y
*
**************************************
*
* Functional description
* Validate a circular list of history blocks.
*
**************************************/
ULONG count = 0;
LOCK_TRACE(("validate_history: %ld\n", history_header));
for (const his* history = (his*) SRQ_ABS_PTR(history_header); true;
history = (his*) SRQ_ABS_PTR(history->his_next))
{
count++;
CHECK(history->his_type == type_his);
CHECK(history->his_operation <= his_MAX);
if (history->his_next == history_header)
break;
CHECK(count <= HISTORY_BLOCKS);
}
}
void LockManager::validate_lhb(const lhb* alhb)
{
/**************************************
*
* v a l i d a t e _ l h b
*
**************************************
*
* Functional description
* Validate the LHB structure and everything that hangs off of it.
*
**************************************/
LOCK_TRACE(("validate_lhb:\n"));
// Prevent recursive reporting of validation errors
if (m_bugcheck)
return;
CHECK(alhb != NULL);
CHECK(alhb->mhb_type == SharedMemoryBase::SRAM_LOCK_MANAGER);
CHECK(alhb->mhb_header_version == MemoryHeader::HEADER_VERSION);
CHECK(alhb->mhb_version == LHB_VERSION);
CHECK(alhb->lhb_type == type_lhb);
validate_shb(alhb->lhb_secondary);
if (alhb->lhb_active_owner > 0)
validate_owner(alhb->lhb_active_owner, EXPECT_inuse);
const srq* lock_srq;
SRQ_LOOP(alhb->lhb_owners, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
const own* const owner = (own*) ((UCHAR*) lock_srq - offsetof(own, own_lhb_owners));
validate_owner(SRQ_REL_PTR(owner), EXPECT_inuse);
}
SRQ_LOOP(alhb->lhb_free_owners, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
const own* const owner = (own*) ((UCHAR*) lock_srq - offsetof(own, own_lhb_owners));
validate_owner(SRQ_REL_PTR(owner), EXPECT_freed);
}
SRQ_LOOP(alhb->lhb_free_locks, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
const lbl* const lock = (lbl*) ((UCHAR*) lock_srq - offsetof(lbl, lbl_lhb_hash));
validate_lock(SRQ_REL_PTR(lock), EXPECT_freed, (SRQ_PTR) 0);
}
SRQ_LOOP(alhb->lhb_free_requests, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
const lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_lbl_requests));
validate_request(SRQ_REL_PTR(request), EXPECT_freed, RECURSE_not);
}
CHECK(alhb->lhb_used <= alhb->lhb_length);
validate_history(alhb->lhb_history);
DEBUG_MSG(0, ("validate_lhb completed:\n"));
}
void LockManager::validate_lock(const SRQ_PTR lock_ptr, USHORT freed, const SRQ_PTR lrq_ptr)
{
/**************************************
*
* v a l i d a t e _ l o c k
*
**************************************
*
* Functional description
* Validate the lock structure and everything that hangs off of it.
*
**************************************/
LOCK_TRACE(("validate_lock: %ld\n", lock_ptr));
const lbl* lock = (lbl*) SRQ_ABS_PTR(lock_ptr);
if (freed == EXPECT_freed)
CHECK(lock->lbl_type == type_null);
else
CHECK(lock->lbl_type == type_lbl);
CHECK(lock->lbl_state < LCK_max);
CHECK(lock->lbl_length <= lock->lbl_size);
// The lbl_count's should never roll over to be negative
for (ULONG i = 0; i < FB_NELEM(lock->lbl_counts); i++)
CHECK(!(lock->lbl_counts[i] & 0x8000));
// The count of pending locks should never roll over to be negative
CHECK(!(lock->lbl_pending_lrq_count & 0x8000));
USHORT direct_counts[LCK_max];
memset(direct_counts, 0, sizeof(direct_counts));
ULONG found = 0, found_pending = 0, found_incompatible = 0;
const srq* lock_srq;
SRQ_LOOP(lock->lbl_requests, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
// Any requests of a freed lock should also be free
CHECK(freed == EXPECT_inuse);
const lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_lbl_requests));
// Note: Don't try to validate_request here, it leads to recursion
if (SRQ_REL_PTR(request) == lrq_ptr)
found++;
CHECK(found <= 1); // check for a loop in the queue
// Request must be for this lock
CHECK(request->lrq_lock == lock_ptr);
if (request->lrq_flags & LRQ_pending)
{
// If the request is pending, then it must be incompatible with current
// state of the lock - OR there is at least one incompatible request
// in the queue before this request.
CHECK(!compatibility[request->lrq_requested][lock->lbl_state] || found_incompatible);
found_pending++;
}
else
{
// If the request is NOT pending, then it must be rejected or
// compatible with the current state of the lock
CHECK((request->lrq_flags & LRQ_rejected) ||
(request->lrq_requested == lock->lbl_state) ||
compatibility[request->lrq_requested][lock->lbl_state]);
}
if (!compatibility[request->lrq_requested][lock->lbl_state])
found_incompatible++;
direct_counts[request->lrq_state]++;
}
if ((freed == EXPECT_inuse) && (lrq_ptr != 0)) {
CHECK(found == 1); // request is in lock's queue
}
if (freed == EXPECT_inuse)
{
CHECK(found_pending == lock->lbl_pending_lrq_count);
// The counter in the lock header should match the actual counts
// lock->lbl_counts [LCK_null] isn't maintained, so don't check it
for (USHORT j = LCK_null; j < LCK_max; j++)
CHECK(direct_counts[j] == lock->lbl_counts[j]);
}
}
void LockManager::validate_owner(const SRQ_PTR own_ptr, USHORT freed)
{
/**************************************
*
* v a l i d a t e _ o w n e r
*
**************************************
*
* Functional description
* Validate the owner structure and everything that hangs off of it.
*
**************************************/
LOCK_TRACE(("validate_owner: %ld\n", own_ptr));
const own* const owner = (own*) SRQ_ABS_PTR(own_ptr);
CHECK(owner->own_type == type_own);
if (freed == EXPECT_freed)
CHECK(owner->own_owner_type == 0);
else {
CHECK(owner->own_owner_type <= 2);
}
CHECK(owner->own_acquire_time <= m_sharedMemory->getHeader()->lhb_acquires);
// Check that no invalid flag bit is set
CHECK(!(owner->own_flags & ~(OWN_scanned | OWN_wakeup | OWN_signaled)));
const srq* lock_srq;
SRQ_LOOP(owner->own_requests, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
CHECK(freed == EXPECT_inuse); // should not be in loop for freed owner
const lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_own_requests));
validate_request(SRQ_REL_PTR(request), EXPECT_inuse, RECURSE_not);
CHECK(request->lrq_owner == own_ptr);
// Make sure that request marked as blocking also exists in the blocking list
if (request->lrq_flags & LRQ_blocking)
{
ULONG found = 0;
const srq* que2;
SRQ_LOOP(owner->own_blocks, que2)
{
// Validate that the next backpointer points back to us
const srq* const que2_next = SRQ_NEXT((*que2));
CHECK(que2_next->srq_backward == SRQ_REL_PTR(que2));
const lrq* const request2 = (lrq*) ((UCHAR*) que2 - offsetof(lrq, lrq_own_blocks));
CHECK(request2->lrq_owner == own_ptr);
if (SRQ_REL_PTR(request2) == SRQ_REL_PTR(request))
found++;
CHECK(found <= 1); // watch for loops in queue
}
CHECK(found == 1); // request marked as blocking must be in blocking queue
}
// Make sure that request marked as pending also exists in the pending list,
// as well as in the queue for the lock
if (request->lrq_flags & LRQ_pending)
{
ULONG found = 0;
const srq* que2;
SRQ_LOOP(owner->own_pending, que2)
{
// Validate that the next backpointer points back to us
const srq* const que2_next = SRQ_NEXT((*que2));
CHECK(que2_next->srq_backward == SRQ_REL_PTR(que2));
const lrq* const request2 = (lrq*) ((UCHAR*) que2 - offsetof(lrq, lrq_own_pending));
CHECK(request2->lrq_owner == own_ptr);
if (SRQ_REL_PTR(request2) == SRQ_REL_PTR(request))
found++;
CHECK(found <= 1); // watch for loops in queue
}
CHECK(found == 1); // request marked as pending must be in pending queue
// Make sure the pending request is on the list of requests for the lock
const lbl* const lock = (lbl*) SRQ_ABS_PTR(request->lrq_lock);
bool found_pending = false;
const srq* que_of_lbl_requests;
SRQ_LOOP(lock->lbl_requests, que_of_lbl_requests)
{
const lrq* const pending =
(lrq*) ((UCHAR*) que_of_lbl_requests - offsetof(lrq, lrq_lbl_requests));
if (SRQ_REL_PTR(pending) == SRQ_REL_PTR(request))
{
found_pending = true;
break;
}
}
// pending request must exist in the lock's request queue
CHECK(found_pending);
}
}
// Check each item in the blocking queue
SRQ_LOOP(owner->own_blocks, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
CHECK(freed == EXPECT_inuse); // should not be in loop for freed owner
const lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_own_blocks));
validate_request(SRQ_REL_PTR(request), EXPECT_inuse, RECURSE_not);
LOCK_TRACE(("Validate own_block: %ld\n", SRQ_REL_PTR(request)));
CHECK(request->lrq_owner == own_ptr);
// A repost won't be in the request list
if (request->lrq_flags & LRQ_repost)
continue;
// Make sure that each block also exists in the request list
ULONG found = 0;
const srq* que2;
SRQ_LOOP(owner->own_requests, que2)
{
// Validate that the next backpointer points back to us
const srq* const que2_next = SRQ_NEXT((*que2));
CHECK(que2_next->srq_backward == SRQ_REL_PTR(que2));
const lrq* const request2 = (lrq*) ((UCHAR*) que2 - offsetof(lrq, lrq_own_requests));
CHECK(request2->lrq_owner == own_ptr);
if (SRQ_REL_PTR(request2) == SRQ_REL_PTR(request))
found++;
CHECK(found <= 1); // watch for loops in queue
}
CHECK(found == 1); // blocking request must be in request queue
}
// Check each item in the pending queue
SRQ_LOOP(owner->own_pending, lock_srq)
{
// Validate that the next backpointer points back to us
const srq* const que_next = SRQ_NEXT((*lock_srq));
CHECK(que_next->srq_backward == SRQ_REL_PTR(lock_srq));
CHECK(freed == EXPECT_inuse); // should not be in loop for freed owner
const lrq* const request = (lrq*) ((UCHAR*) lock_srq - offsetof(lrq, lrq_own_pending));
validate_request(SRQ_REL_PTR(request), EXPECT_inuse, RECURSE_not);
LOCK_TRACE(("Validate own_block: %ld\n", SRQ_REL_PTR(request)));
CHECK(request->lrq_owner == own_ptr);
// A repost cannot be pending
CHECK(!(request->lrq_flags & LRQ_repost));
// Make sure that each pending request also exists in the request list
ULONG found = 0;
const srq* que2;
SRQ_LOOP(owner->own_requests, que2)
{
// Validate that the next backpointer points back to us
const srq* const que2_next = SRQ_NEXT((*que2));
CHECK(que2_next->srq_backward == SRQ_REL_PTR(que2));
const lrq* const request2 = (lrq*) ((UCHAR*) que2 - offsetof(lrq, lrq_own_requests));
CHECK(request2->lrq_owner == own_ptr);
if (SRQ_REL_PTR(request2) == SRQ_REL_PTR(request))
found++;
CHECK(found <= 1); // watch for loops in queue
}
CHECK(found == 1); // pending request must be in request queue
}
}
void LockManager::validate_request(const SRQ_PTR lrq_ptr, USHORT freed, USHORT recurse)
{
/**************************************
*
* v a l i d a t e _ r e q u e s t
*
**************************************
*
* Functional description
* Validate the request structure and everything that hangs off of it.
*
**************************************/
LOCK_TRACE(("validate_request: %ld\n", lrq_ptr));
const lrq* const request = (lrq*) SRQ_ABS_PTR(lrq_ptr);
if (freed == EXPECT_freed)
CHECK(request->lrq_type == type_null);
else
CHECK(request->lrq_type == type_lrq);
// Check that no invalid flag bit is set
CHECK(!(request->lrq_flags &
~(LRQ_blocking | LRQ_pending | LRQ_rejected | LRQ_deadlock | LRQ_repost |
LRQ_scanned | LRQ_blocking_seen | LRQ_just_granted | LRQ_wait_timeout)));
// Once a request is rejected, it CAN'T be pending any longer
if (request->lrq_flags & LRQ_rejected) {
CHECK(!(request->lrq_flags & LRQ_pending));
}
// Can't both be scanned & marked for deadlock walk
CHECK((request->lrq_flags & (LRQ_deadlock | LRQ_scanned)) != (LRQ_deadlock | LRQ_scanned));
CHECK(request->lrq_requested < LCK_max);
CHECK(request->lrq_state < LCK_max);
if (freed == EXPECT_inuse)
{
if (recurse == RECURSE_yes)
validate_owner(request->lrq_owner, EXPECT_inuse);
// Reposted request are pseudo requests, not attached to any real lock
if (!(request->lrq_flags & LRQ_repost))
validate_lock(request->lrq_lock, EXPECT_inuse, SRQ_REL_PTR(request));
}
}
void LockManager::validate_shb(const SRQ_PTR shb_ptr)
{
/**************************************
*
* v a l i d a t e _ s h b
*
**************************************
*
* Functional description
* Validate the SHB structure and everything that hangs off of
* it.
* Of course, it would have been a VERY good thing if someone
* had moved this into lhb when we made a unique v4 lock
* manager....
* 1995-April-13 David Schnepper
*
**************************************/
LOCK_TRACE(("validate_shb: %ld\n", shb_ptr));
const shb* secondary_header = (shb*) SRQ_ABS_PTR(shb_ptr);
CHECK(secondary_header->shb_type == type_shb);
validate_history(secondary_header->shb_history);
}
void LockManager::wait_for_request(thread_db* tdbb, lrq* request, SSHORT lck_wait)
{
/**************************************
*
* w a i t _ f o r _ r e q u e s t
*
**************************************
*
* Functional description
* There is a request that needs satisfaction, but is waiting for
* somebody else. Mark the request as pending and go to sleep until
* the lock gets poked. When we wake up, see if somebody else has
* cleared the pending flag. If not, go back to sleep.
* Returns
* FB_SUCCESS - we waited until the request was granted or rejected
* FB_FAILURE - Insufficient resouces to wait (eg: no semaphores)
*
**************************************/
ASSERT_ACQUIRED;
++(m_sharedMemory->getHeader()->lhb_waits);
const ULONG scan_interval = m_sharedMemory->getHeader()->lhb_scan_interval;
// lrq_count will be off if we wait for a pending request
CHECK(!(request->lrq_flags & LRQ_pending));
const SRQ_PTR request_offset = SRQ_REL_PTR(request);
const SRQ_PTR owner_offset = request->lrq_owner;
own* owner = (own*) SRQ_ABS_PTR(owner_offset);
owner->own_flags &= ~(OWN_scanned | OWN_wakeup);
owner->own_waits++;
request->lrq_flags &= ~LRQ_rejected;
request->lrq_flags |= LRQ_pending;
insert_tail(&owner->own_pending, &request->lrq_own_pending);
const SRQ_PTR lock_offset = request->lrq_lock;
lbl* lock = (lbl*) SRQ_ABS_PTR(lock_offset);
lock->lbl_pending_lrq_count++;
if (!request->lrq_state)
{
// If this is a conversion of an existing lock in LCK_none state -
// put the lock to the end of the list so it's not taking cuts in the lineup
remove_que(&request->lrq_lbl_requests);
insert_tail(&lock->lbl_requests, &request->lrq_lbl_requests);
}
if (lck_wait <= 0)
request->lrq_flags |= LRQ_wait_timeout;
SLONG value = m_sharedMemory->eventClear(&owner->own_wakeup);
// Post blockage. If the blocking owner has disappeared, the blockage
// may clear spontaneously.
post_blockage(tdbb, request, lock);
post_history(his_wait, owner_offset, lock_offset, request_offset, true);
owner = (own*) SRQ_ABS_PTR(owner_offset);
request = (lrq*) SRQ_ABS_PTR(request_offset);
lock = (lbl*) SRQ_ABS_PTR(lock_offset);
time_t current_time = time(NULL);
// If a lock timeout was requested (wait < 0) then figure
// out the time when the lock request will timeout
const time_t lock_timeout = (lck_wait < 0) ? current_time + (-lck_wait) : 0;
time_t deadlock_timeout = current_time + tdbb->adjustWait(scan_interval);
// Wait in a loop until the lock becomes available
#ifdef DEV_BUILD
ULONG repost_counter = 0;
#endif
while (true)
{
owner = (own*) SRQ_ABS_PTR(owner_offset);
request = (lrq*) SRQ_ABS_PTR(request_offset);
lock = (lbl*) SRQ_ABS_PTR(lock_offset);
// Before starting to wait - look to see if someone resolved
// the request for us - if so we're out easy!
if (!(request->lrq_flags & LRQ_pending))
break;
int ret = FB_FAILURE;
// Recalculate when we next want to wake up, the lesser of a
// deadlock scan interval or when the lock request wanted a timeout
time_t timeout = deadlock_timeout;
if (lck_wait < 0 && lock_timeout < deadlock_timeout)
timeout = lock_timeout;
// Prepare to wait for a timeout or a wakeup from somebody else
if (!(owner->own_flags & OWN_wakeup))
{
// Re-initialize value each time thru the loop to make sure that the
// semaphore looks 'un-poked'
{ // checkout scope
LockTableCheckout checkout(this, FB_FUNCTION);
{ // scope
ReadLockGuard guard(m_remapSync, FB_FUNCTION);
owner = (own*) SRQ_ABS_PTR(owner_offset);
++m_waitingOwners;
}
{ // scope
EngineCheckout cout(tdbb, FB_FUNCTION, true);
ret = m_sharedMemory->eventWait(&owner->own_wakeup, value, (timeout - current_time) * 1000000);
--m_waitingOwners;
}
}
owner = (own*) SRQ_ABS_PTR(owner_offset);
request = (lrq*) SRQ_ABS_PTR(request_offset);
lock = (lbl*) SRQ_ABS_PTR(lock_offset);
}
// We've woken up from the wait - now look around and see why we wokeup
// If somebody else has resolved the lock, we're done
if (!(request->lrq_flags & LRQ_pending))
break;
// See if we wokeup due to another owner deliberately waking us up
// ret==FB_SUCCESS --> we were deliberately woken up
// ret==FB_FAILURE --> we still don't know why we woke up
// Only if we came out of the m_sharedMemory->eventWait() because of a post_wakeup()
// by another owner is OWN_wakeup set. This is the only FB_SUCCESS case.
if (ret == FB_SUCCESS)
{
value = m_sharedMemory->eventClear(&owner->own_wakeup);
}
if (owner->own_flags & OWN_wakeup)
ret = FB_SUCCESS;
else
ret = FB_FAILURE;
current_time = time(NULL);
// See if we woke up for a bogus reason - if so
// go right back to sleep. We wokeup bogus unless
// - we weren't deliberatly woken up
// - it's not time for a deadlock scan
// - it's not time for the lock timeout to expire
// Bogus reasons for wakeups include signal reception on some
// platforms (eg: SUN4) and remapping notification.
// Note: we allow a 1 second leaway on declaring a bogus
// wakeup due to timing differences (we use seconds here,
// eventWait() uses finer granularity)
if ((ret != FB_SUCCESS) && (current_time + 1 < timeout))
continue;
// We apparently woke up for some real reason.
// Make sure everyone is still with us. Then see if we're still blocked.
owner->own_flags &= ~OWN_wakeup;
// See if we've waited beyond the lock timeout -
// if so we mark our own request as rejected
// !!! this will be changed to have no dependency on thread_db !!!
const bool cancelled = (tdbb->getCancelState() != FB_SUCCESS);
if (cancelled || (lck_wait < 0 && lock_timeout <= current_time))
{
// We're going to reject our lock - it's the callers responsibility
// to do cleanup and make sure post_pending() is called to wakeup
// other owners we might be blocking
request->lrq_flags |= LRQ_rejected;
remove_que(&request->lrq_own_pending);
request->lrq_flags &= ~LRQ_pending;
lock->lbl_pending_lrq_count--;
// and test - may be timeout due to missing process to deliver request
probe_processes();
break;
}
// We're going to do some real work - reset when we next want to
// do a deadlock scan
deadlock_timeout = current_time + tdbb->adjustWait(scan_interval);
// Handle lock event first
if (ret == FB_SUCCESS)
{
// Someone posted our wakeup event, but DIDN'T grant our request.
// Re-post what we're blocking on and continue to wait.
// This could happen if the lock was granted to a different request,
// we have to tell the new owner of the lock that they are blocking us.
post_blockage(tdbb, request, lock);
continue;
}
// See if all the other owners are still alive. Dead ones will be purged,
// purging one might resolve our lock request.
// Do not do rescan of owners if we received notification that
// blocking ASTs have completed - will do it next time if needed.
if (probe_processes() && !(request->lrq_flags & LRQ_pending))
break;
// If we've not previously been scanned for a deadlock and going to wait
// forever, go do a deadlock scan
lrq* blocking_request;
if (!(owner->own_flags & OWN_scanned) &&
!(request->lrq_flags & LRQ_wait_timeout) &&
(blocking_request = deadlock_scan(owner, request)))
{
// Something has been selected for rejection to prevent a
// deadlock. Clean things up and go on. We still have to
// wait for our request to be resolved.
DEBUG_MSG(0, ("wait_for_request: selecting something for deadlock kill\n"));
++(m_sharedMemory->getHeader()->lhb_deadlocks);
blocking_request->lrq_flags |= LRQ_rejected;
remove_que(&blocking_request->lrq_own_pending);
blocking_request->lrq_flags &= ~LRQ_pending;
lbl* const blocking_lock = (lbl*) SRQ_ABS_PTR(blocking_request->lrq_lock);
blocking_lock->lbl_pending_lrq_count--;
own* const blocking_owner = (own*) SRQ_ABS_PTR(blocking_request->lrq_owner);
blocking_owner->own_flags &= ~OWN_scanned;
if (blocking_request != request)
post_wakeup(blocking_owner);
// else
// We rejected our own request to avoid a deadlock.
// When we get back to the top of the master loop we
// fall out and start cleaning up.
}
else
{
// Our request is not resolved, all the owners are alive, there's
// no deadlock -- there's nothing else to do. Let's
// make sure our request hasn't been forgotten by reminding
// all the owners we're waiting - some plaforms under CLASSIC
// architecture had problems with "missing signals" - which is
// another reason to repost the blockage.
// Also, the ownership of the lock could have changed, and we
// weren't woken up because we weren't next in line for the lock.
// We need to inform the new owner.
DEBUG_MSG(0, ("wait_for_request: forcing a resignal of blockers\n"));
post_blockage(tdbb, request, lock);
#ifdef DEV_BUILD
repost_counter++;
if (repost_counter % 50 == 0)
{
gds__log("wait_for_request: owner %d reposted %ld times for lock %d",
owner_offset,
repost_counter,
lock_offset);
DEBUG_MSG(0,
("wait_for_request: reposted %ld times for this lock!\n",
repost_counter));
}
#endif
}
}
CHECK(!(request->lrq_flags & LRQ_pending));
request->lrq_flags &= ~LRQ_wait_timeout;
owner->own_waits--;
}
void LockManager::mutexBug(int state, char const* text)
{
string message;
message.printf("%s: error code %d\n", text, state);
bug(NULL, message.c_str());
}
#ifdef USE_SHMEM_EXT
void LockManager::Extent::assign(const SharedMemoryBase& p)
{
SharedMemoryBase* me = this;
me->setHeader(p.getHeader());
me->sh_mem_mutex = p.sh_mem_mutex;
me->sh_mem_length_mapped = p.sh_mem_length_mapped;
me->sh_mem_handle = p.sh_mem_handle;
strcpy(me->sh_mem_name, p.sh_mem_name);
}
#endif // USE_SHMEM_EXT
} // namespace
| 26.945777 | 141 | 0.659829 | stbergmann |
04ab74f15c8ddc6da39258a45e8f3134b11829ae | 2,109 | cc | C++ | rslib/encoder.cc | sycy600/rslib | 513dc54414443169b4162e635c17ccf9f898ecd1 | [
"BSD-2-Clause"
] | null | null | null | rslib/encoder.cc | sycy600/rslib | 513dc54414443169b4162e635c17ccf9f898ecd1 | [
"BSD-2-Clause"
] | null | null | null | rslib/encoder.cc | sycy600/rslib | 513dc54414443169b4162e635c17ccf9f898ecd1 | [
"BSD-2-Clause"
] | 1 | 2020-04-25T08:16:10.000Z | 2020-04-25T08:16:10.000Z | // Copyright 2013 sycy600
#include <rslib/encoder.h>
namespace rslib {
Encoder::Encoder(unsigned int errorCorrectionCapability,
const ExtendedField& extendedField)
: codeGenerator_(buildCodeGenerator(errorCorrectionCapability,
extendedField)),
encodingShifter_(buildEncodingShifter(errorCorrectionCapability,
extendedField)) {
}
Polynomial<ExtendedFieldElement> Encoder::encode(
const Polynomial<ExtendedFieldElement>& information) const {
Polynomial<ExtendedFieldElement> result = information * encodingShifter_;
result -= (result % codeGenerator_);
return result;
}
Polynomial<ExtendedFieldElement> Encoder::getCodeGenerator() const {
return codeGenerator_;
}
Polynomial<ExtendedFieldElement> Encoder::buildEncodingShifter(
unsigned int errorCorrectionCapability,
const ExtendedField& extendedField) const {
Polynomial<ExtendedFieldElement> shifter =
Polynomial<ExtendedFieldElement>({
ExtendedFieldElement(0, extendedField),
ExtendedFieldElement(1, extendedField)});
unsigned int numIterations = 2 * errorCorrectionCapability - 1;
Polynomial<ExtendedFieldElement> result = shifter;
for (unsigned int i = 0; i < numIterations; ++i) {
result *= shifter;
}
return result;
}
Polynomial<ExtendedFieldElement> Encoder::buildCodeGenerator(
unsigned int errorCorrectionCapability,
const ExtendedField& extendedField) const {
Polynomial<ExtendedFieldElement> generator =
Polynomial<ExtendedFieldElement>({
-ExtendedFieldElement(2, extendedField),
ExtendedFieldElement(1, extendedField)});
Polynomial<ExtendedFieldElement> monomial = generator;
unsigned int numIterations = 2 * errorCorrectionCapability - 1;
ExtendedFieldElement alpha(2, extendedField);
for (unsigned int i = 0; i < numIterations; ++i) {
monomial.setValue(0, monomial.getValue(0) * alpha);
generator *= monomial;
}
return generator;
}
} // namespace rslib
| 34.57377 | 75 | 0.703177 | sycy600 |
04ae5471911dc5f960fe1d0ccd0f66f4210536c2 | 1,023 | hpp | C++ | src/jet/live/AsyncEventQueue.hpp | vejmartin/jet-live | d60dfb90e2a227d61a15fcf89c709855b3aafd86 | [
"MIT"
] | 325 | 2019-01-05T12:40:46.000Z | 2022-03-26T09:06:40.000Z | src/jet/live/AsyncEventQueue.hpp | vejmartin/jet-live | d60dfb90e2a227d61a15fcf89c709855b3aafd86 | [
"MIT"
] | 23 | 2019-01-05T19:43:47.000Z | 2022-01-10T20:11:06.000Z | src/jet/live/AsyncEventQueue.hpp | vejmartin/jet-live | d60dfb90e2a227d61a15fcf89c709855b3aafd86 | [
"MIT"
] | 29 | 2019-01-05T18:49:08.000Z | 2022-03-20T19:14:30.000Z |
#pragma once
#include <memory>
#include <mutex>
#include <queue>
#include "jet/live/IEvent.hpp"
#include "jet/live/ILiveListener.hpp"
#include "jet/live/events/LogEvent.hpp"
namespace jet
{
class AsyncEventQueue
{
public:
void addLog(LogSeverity severity, std::string&& message);
LogEvent* getLogEvent();
void popLogEvent();
void addEvent(std::unique_ptr<IEvent>&& event);
IEvent* getEvent();
void popEvent();
private:
struct QueueComparator
{
bool operator()(const std::unique_ptr<IEvent>& l, const std::unique_ptr<IEvent>& r)
{
return l->getPriority() < r->getPriority();
}
};
template <typename T>
using queue_t = std::priority_queue<T, std::vector<T>, QueueComparator>;
std::mutex m_logQueueMutex;
std::queue<std::unique_ptr<LogEvent>> m_logQueue;
std::mutex m_queueMutex;
queue_t<std::unique_ptr<IEvent>> m_queue;
};
}
| 24.357143 | 95 | 0.603128 | vejmartin |
04af9aaa486f5936a7c45cfc1d844f7f3b0ce613 | 12,418 | cpp | C++ | source/clayout/LInterpreter.cpp | chromaScript/chroma.io | c484354df6f3c84a049ffadfe37c677c0ccb6390 | [
"MIT"
] | null | null | null | source/clayout/LInterpreter.cpp | chromaScript/chroma.io | c484354df6f3c84a049ffadfe37c677c0ccb6390 | [
"MIT"
] | null | null | null | source/clayout/LInterpreter.cpp | chromaScript/chroma.io | c484354df6f3c84a049ffadfe37c677c0ccb6390 | [
"MIT"
] | null | null | null | #include "../include/clayout/LInterpreter.h"
#include "../include/cscript/CEnvironment.h"
#include "../include/cscript/ChromaScript.h"
#include "../include/cscript/CObject.h"
#include "../include/clayout/ChromaLayout.h"
#include "../include/clayout/LToken.h"
#include "../include/clayout/LProc.h"
#include "../include/entities/widgets/WidgetStyle.h"
#include "../include/cscript/CEnums.h"
#include "../include/entities/widgets/Widget.h"
#include "../include/cscript/CStmt.h"
#include "../include/entities/widgets/Graph_ToolControl.h"
#include "../include/entities/widgets/Noise_ToolControl.h"
#include "../include/Application.h"
#include "../include/entities/UserInterface.h"
#include <string>
#include <vector>
#include <exception>
#include <map>
#include <stack>
#include <filesystem>
#include <iostream>
#include <memory>
LInterpreter::LInterpreter()
{
}
void LInterpreter::initialize(std::shared_ptr<ChromaLayout> console)
{
this->console = console;
this->ui = console.get()->owner.get()->getUI();
}
//
void LInterpreter::constructWidgets(
std::vector<std::shared_ptr<LStmt>> statements,
std::shared_ptr<CEnvironment> rootEnvironment,
std::filesystem::path rootDir)
{
currentEnvironment = rootEnvironment;
currentRootDir = rootDir;
for (std::shared_ptr<LStmt> statement : statements)
{
build(statement);
}
currentRootDir.clear();
currentEnvironment = console.get()->scriptConsole.get()->global;
}
//
void LInterpreter::clearUnresolvedSymbols()
{
unresolvedSymbols.clear();
}
//
void LInterpreter::checkUnresolvedSymbols()
{
for (auto const& item : unresolvedSymbols)
{
if (item.second != nullptr)
{
console.get()->error("[resolver:0101] Unresolved style declaration at '"
+ item.first + "'. Check spelling errors and make sure style is defined.");
}
}
}
//
void LInterpreter::build(std::shared_ptr<LStmt> stmt)
{
stmt->accept(*this);
}
void LInterpreter::build(std::shared_ptr<LExpr> expr)
{
expr->acceptBuilder(*this);
}
////////////////////////////////////////////////////////////////////////////////////////////////
//
// layoutResolver Statements
//
////////////////////////////////////////////////////////////////////////////////////////////////
// LStmt_Root
void LInterpreter::visit(std::shared_ptr<LStmt_Root> stmt)
{
// Initialize constructor call parameters
basicAttribs.clear();
std::shared_ptr<WidgetStyle> style = std::make_shared<WidgetStyle>(); // Empty style, won't be used
std::shared_ptr<Shader> shader = console.get()->owner.get()->getWidgetShader();
// Set Widget constructor call parameters
unboundAttribs.clear();
basicOnly = true;
for (std::shared_ptr<LExpr> attrib : stmt.get()->attributes)
{
attrib.get()->acceptBuilder(*this);
}
basicOnly = false;
// Make the widget (may only have one child)
ui.get()->rootWidgets.push_back(stmt.get()->childElements[0].get()->acceptBuilder(*this));
ui.get()->rootWidgets.back().get()->isRoot = true;
ui.get()->rootWidgets.back().get()->rootId = stmt.get()->id;
ui.get()->rootWidgets.back().get()->setLocation((int)stmt.get()->defaultX, (int)stmt.get()->defaultY);
ui.get()->rootWidgets.back().get()->_namespace = currentEnvironment.get()->_namespace;
// Clean up and exit
currentElement.reset();
//currentRoot.reset();
unboundAttribs.clear();
basicAttribs.clear();
return;
}
// LStmt_Proto
void LInterpreter::visit(std::shared_ptr<LStmt_Proto> stmt)
{
// Initialize constructor call parameters
basicAttribs.clear();
std::shared_ptr<WidgetStyle> style = std::make_shared<WidgetStyle>(); // Empty style, won't be used
std::shared_ptr<Shader> shader = console.get()->owner.get()->getWidgetShader();
// Set Widget constructor call parameters
unboundAttribs.clear();
basicOnly = true;
for (std::shared_ptr<LExpr> attrib : stmt.get()->attributes)
{
attrib.get()->acceptBuilder(*this);
}
basicOnly = false;
// Make the widget (Can only be one child)
std::shared_ptr<Widget> protoFirst = stmt.get()->childElements[0].get()->acceptBuilder(*this);
if (ui.get()->prototypeFactoryTable.count(stmt.get()->id) == 1)
{
ui.get()->prototypeFactoryTable.at(stmt.get()->id) = protoFirst;
}
else
{
ui.get()->prototypeFactoryTable.insert(
std::pair<std::string, std::shared_ptr<Widget>>(
stmt.get()->id, stmt.get()->childElements[0].get()->acceptBuilder(*this)));
}
ui.get()->prototypeFactoryTable.at(stmt.get()->id).get()->isRoot = true;
ui.get()->prototypeFactoryTable.at(stmt.get()->id).get()->rootId = stmt.get()->id;
ui.get()->prototypeFactoryTable.at(stmt.get()->id).get()->setLocation((int)stmt.get()->defaultX, (int)stmt.get()->defaultY);
ui.get()->prototypeFactoryTable.at(stmt.get()->id).get()->_namespace = currentEnvironment.get()->_namespace;
// Clean up and exit
currentElement.reset();
currentRoot.reset();
unboundAttribs.clear();
basicAttribs.clear();
return;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//
// layoutResolver Expressions
//
////////////////////////////////////////////////////////////////////////////////////////////////
// LExpr_Element
std::shared_ptr<Widget> LInterpreter::visit(std::shared_ptr<LExpr_Element> expr)
{
// Initialize constructor call parameters
basicAttribs.clear();
std::shared_ptr<WidgetStyle> style = std::make_shared<WidgetStyle>();
std::shared_ptr<Shader> shader = nullptr;
switch (expr.get()->widgetType.get()->type)
{
case LTokenType::H_BOX:
shader = console.get()->owner.get()->getWidgetShader(); break;
case LTokenType::V_BOX:
shader = console.get()->owner.get()->getWidgetShader(); break;
case LTokenType::IMAGE:
shader = console.get()->owner.get()->getWidgetShader(); break;
case LTokenType::T_GRAPH:
shader = console.get()->owner.get()->getGraphWidgetShader(); break;
case LTokenType::T_NOISE:
shader = console.get()->owner.get()->getNoiseWidgetShader(); break;
case LTokenType::TEXT:
case LTokenType::LINE:
case LTokenType::BLOCK:
case LTokenType::PARAGRAPH:
shader = console.get()->owner.get()->getTextShader(); break;
case LTokenType::GRADIENT_BOX:
shader = console.get()->owner.get()->getGradientBoxShader(); break;
default:
shader = console.get()->owner.get()->getWidgetShader(); break;
}
if (expr.get()->id != "")
{
std::shared_ptr<CObject> idStyle = currentEnvironment.get()->get("#" + expr.get()->id);
if (idStyle != nullptr)
{
style.get()->mergeStyle(std::get<std::shared_ptr<WidgetStyle>>(idStyle.get()->obj));
}
}
for (std::string className : expr.get()->classes)
{
std::shared_ptr<CObject> classStyle = currentEnvironment.get()->get("." + className);
if (classStyle != nullptr)
{
style.get()->mergeStyle(std::get<std::shared_ptr<WidgetStyle>>(classStyle.get()->obj));
}
}
// Set constructor call parameters
unboundAttribs.clear();
basicOnly = true;
for (std::shared_ptr<LExpr> attrib : expr.get()->attributes)
{
attrib.get()->acceptBuilder(*this);
}
basicOnly = false;
std::shared_ptr<Widget> element = ui.get()->createWidget(expr.get()->widgetType.get()->type, basicAttribs, currentElement, style, shader);
// Set properties
element.get()->_namespace = currentEnvironment.get()->_namespace;
element.get()->classAttribs = expr.get()->classes;
element.get()->groupsAttribs = expr.get()->groups;
// Resolve unbound attributes
currentElement = element;
for (std::shared_ptr<LExpr> attrib : unboundAttribs)
{
attrib.get()->acceptBuilder(*this);
}
// Create child widgets
for (std::shared_ptr<LExpr> child : expr.get()->childElements)
{
currentElement = element;
std::shared_ptr<Widget> childWidget = child.get()->acceptBuilder(*this);
if (childWidget != nullptr)
{
element.get()->childWidgets.push_back(childWidget);
}
}
// Do special initialization functions
if (element.get()->type == LTokenType::T_GRAPH)
{
std::dynamic_pointer_cast<Graph_ToolControl>(element).get()->initializeWidget(console.get()->owner.get()->ui);
}
// Do special initialization functions
else if (element.get()->type == LTokenType::T_NOISE)
{
std::dynamic_pointer_cast<Noise_ToolControl>(element).get()->initializeWidget(console.get()->owner.get()->ui);
}
// Clean up and exit
unboundAttribs.clear();
basicAttribs.clear();
return element;
}
// LExpr_RootAttrib
std::shared_ptr<Widget> LInterpreter::visit(std::shared_ptr<LExpr_RootAttrib> expr)
{
std::string attribName = expr.get()->attribName.get()->typeString();
std::string attribValue = expr.get()->attribValue.get()->lexeme;
switch (expr.get()->attribName.get()->type)
{
case LTokenType::ID:
basicAttribs.insert(std::pair<std::string, std::string>(attribName, attribValue));
break;
}
return nullptr;
}
// LExpr_ElementAttrib
std::shared_ptr<Widget> LInterpreter::visit(std::shared_ptr<LExpr_ElementAttrib> expr)
{
std::string attribName = expr.get()->attribName.get()->typeString();
std::string attribValue = expr.get()->attribValue.get()->lexeme;
switch (expr.get()->attribName.get()->type)
{
case LTokenType::ID:
basicAttribs.insert(std::pair<std::string, std::string>(attribName, attribValue));
break;
case LTokenType::NAME:
basicAttribs.insert(std::pair<std::string, std::string>(attribName, attribValue));
break;
case LTokenType::VALUE:
basicAttribs.insert(std::pair<std::string, std::string>(attribName, attribValue));
break;
case LTokenType::IMG:
basicAttribs.insert(std::pair<std::string, std::string>(attribName, attribValue));
break;
case LTokenType::INNER_CONTENT:
basicAttribs.insert(std::pair<std::string, std::string>(attribName, attribValue));
break;
case LTokenType::STYLE:
if (basicOnly) { unboundAttribs.push_back(expr); break; }
else
{
std::shared_ptr<WidgetStyle> overWrite = console.get()->owner.get()->styleConsole.get()->create(
attribValue, currentEnvironment.get()->_namespace, currentRootDir);
if (overWrite != nullptr && !currentElement.expired())
{
currentElement.lock().get()->style.mergeStyle(overWrite);
}
} break;
case LTokenType::ON_BLUR:
case LTokenType::ON_FOCUS:
case LTokenType::ON_CLICK:
case LTokenType::ON_RIGGHTCLICK:
case LTokenType::ON_DBL_CLICK:
case LTokenType::ON_DBL_RIGHTCLICK:
case LTokenType::ON_MIDDLECLICK:
case LTokenType::ON_DBL_MIDDLECLICK:
case LTokenType::ON_DRAG:
case LTokenType::ON_DRAG_START:
case LTokenType::ON_DRAG_END:
case LTokenType::ON_DRAG_ENTER:
case LTokenType::ON_DRAG_OVER:
case LTokenType::ON_DRAG_LEAVE:
case LTokenType::ON_DROP:
case LTokenType::ON_KEY_DOWN:
case LTokenType::ON_KEY_PRESS:
case LTokenType::ON_KEY_UP:
case LTokenType::ON_LOAD:
case LTokenType::ON_COPY:
case LTokenType::ON_PASTE:
case LTokenType::ON_CUT:
case LTokenType::ON_MOUSE_OVER:
case LTokenType::ON_MOUSE_ENTER:
case LTokenType::ON_MOUSE_LEAVE:
case LTokenType::ON_MOUSE_WHEELUP:
case LTokenType::ON_MOUSE_WHEELDOWN:
case LTokenType::ON_RESIZE:
case LTokenType::ON_RELEASE:
case LTokenType::ON_CANCEL:
case LTokenType::ON_ENTRY:
if (basicOnly) { unboundAttribs.push_back(expr); break; }
else
{
bool isExpr = false;
if (attribValue.find(";") == std::string::npos) { isExpr = true; }
if (!currentElement.expired())
{
currentElement.lock().get()->callbackMap.insert(
std::pair<std::string, std::vector<std::shared_ptr<CStmt>>>(
attribName,
console.get()->scriptConsole.get()->entry_compileOnly(attribValue, currentEnvironment.get()->_namespace, isExpr)));
}
} break;
case LTokenType::DRAGGABLE:
if (basicOnly) { unboundAttribs.push_back(expr); break; }
else
{
bool value = false;
if (attribValue == "true") { value = true; }
if (!currentElement.expired())
{
currentElement.lock().get()->isDraggable = value;
}
} break;
case LTokenType::DROPPABLE:
if (basicOnly) { unboundAttribs.push_back(expr); break; }
else
{
bool value = false;
if (attribValue == "true") { value = true; }
if (!currentElement.expired())
{
currentElement.lock().get()->isDroppable = value;
}
} break;
case LTokenType::DRAG_TYPE:
if (basicOnly) { unboundAttribs.push_back(expr); break; }
else
{
if (!currentElement.expired())
{
currentElement.lock().get()->dragType = attribValue;
}
} break;
case LTokenType::DROP_TYPE:
if (basicOnly) { unboundAttribs.push_back(expr); break; }
else
{
if (!currentElement.expired())
{
currentElement.lock().get()->dragType = attribValue;
}
} break;
}
return nullptr;
}
| 30.890547 | 139 | 0.68755 | chromaScript |
04b35dac200e870b840953e790230f52b68a0693 | 2,266 | hpp | C++ | src/vendor/cget/cget/pkg/pqrs-org__cpp-osx-json_file_monitor/install/include/pqrs/osx/json_file_monitor.hpp | egelwan/Karabiner-Elements | 896439dd2130904275553282063dd7fe4852e1a8 | [
"Unlicense"
] | 5,422 | 2019-10-27T17:51:04.000Z | 2022-03-31T15:45:41.000Z | src/vendor/cget/cget/pkg/pqrs-org__cpp-osx-json_file_monitor/install/include/pqrs/osx/json_file_monitor.hpp | XXXalice/Karabiner-Elements | 52f579cbf60251cf18915bd938eb4431360b763b | [
"Unlicense"
] | 1,310 | 2019-10-28T04:57:24.000Z | 2022-03-31T04:55:37.000Z | src/vendor/cget/cget/pkg/pqrs-org__cpp-osx-json_file_monitor/install/include/pqrs/osx/json_file_monitor.hpp | XXXalice/Karabiner-Elements | 52f579cbf60251cf18915bd938eb4431360b763b | [
"Unlicense"
] | 282 | 2019-10-28T02:36:04.000Z | 2022-03-19T06:18:54.000Z | #pragma once
// pqrs::osx::json_file_monitor v1.0
// (C) Copyright Takayama Fumihiko 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
#include <nlohmann/json.hpp>
#include <pqrs/osx/file_monitor.hpp>
namespace pqrs {
namespace osx {
class json_file_monitor final : public dispatcher::extra::dispatcher_client {
public:
// Signals (invoked from the dispatcher thread)
nod::signal<void(const std::string& changed_file_path, std::shared_ptr<nlohmann::json> json)> json_file_changed;
nod::signal<void(const std::string&)> error_occurred;
nod::signal<void(const std::string& file_path, const std::string& message)> json_error_occurred;
// Methods
json_file_monitor(std::weak_ptr<dispatcher::dispatcher> weak_dispatcher,
const std::vector<std::string>& files) : dispatcher_client(weak_dispatcher) {
file_monitor_ = std::make_unique<file_monitor>(weak_dispatcher,
files);
file_monitor_->file_changed.connect([this](auto&& changed_file_path, auto&& changed_file_body) {
std::shared_ptr<nlohmann::json> json;
if (changed_file_body) {
try {
json = std::make_shared<nlohmann::json>(
nlohmann::json::parse(std::begin(*changed_file_body),
std::end(*changed_file_body)));
} catch (std::exception& e) {
auto message = e.what();
enqueue_to_dispatcher([this, changed_file_path, message] {
json_error_occurred(changed_file_path, message);
});
return;
}
}
enqueue_to_dispatcher([this, changed_file_path, json] {
json_file_changed(changed_file_path, json);
});
});
file_monitor_->error_occurred.connect([this](auto&& message) {
enqueue_to_dispatcher([this, message] {
error_occurred(message);
});
});
}
virtual ~json_file_monitor(void) {
// dispatcher_client
detach_from_dispatcher([this] {
file_monitor_ = nullptr;
});
}
void async_start(void) {
file_monitor_->async_start();
}
private:
std::unique_ptr<file_monitor> file_monitor_;
};
} // namespace osx
} // namespace pqrs
| 30.213333 | 114 | 0.650044 | egelwan |
04ba2b05a9e620c081b1b7eb78f0507bc508d533 | 7,042 | cpp | C++ | tools/shard-seeder/shard-seeder.cpp | vipinsun/opencbdc-tx | 724f307548f92676423e98d7f2c1bfc2c66f79ef | [
"MIT"
] | 1 | 2022-02-09T22:25:02.000Z | 2022-02-09T22:25:02.000Z | tools/shard-seeder/shard-seeder.cpp | vipinsun/opencbdc-tx | 724f307548f92676423e98d7f2c1bfc2c66f79ef | [
"MIT"
] | null | null | null | tools/shard-seeder/shard-seeder.cpp | vipinsun/opencbdc-tx | 724f307548f92676423e98d7f2c1bfc2c66f79ef | [
"MIT"
] | 1 | 2022-02-10T02:31:32.000Z | 2022-02-10T02:31:32.000Z | // Copyright (c) 2021 MIT Digital Currency Initiative,
// Federal Reserve Bank of Boston
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "uhs/transaction/transaction.hpp"
#include "uhs/transaction/wallet.hpp"
#include "util/common/config.hpp"
#include "util/serialization/buffer_serializer.hpp"
#include "util/serialization/format.hpp"
#include "util/serialization/ostream_serializer.hpp"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <thread>
static constexpr int leveldb_buffer_size
= 16 * 1024 * 1024; // 16MB can hold ~ 500K UHS_IDs
static constexpr int write_batch_size
= 450000; // well within the write buffer size
auto get_2pc_uhs_key(const cbdc::hash_t& uhs_id) -> std::string {
auto ret = std::string();
ret.resize(uhs_id.size() + 1);
std::memcpy(&ret[1], uhs_id.data(), uhs_id.size());
ret.front() = 'u';
return ret;
}
auto main(int argc, char** argv) -> int {
auto args = cbdc::config::get_args(argc, argv);
auto logger = cbdc::logging::log(cbdc::logging::log_level::info);
static constexpr auto min_arg_count = 5;
if(args.size() < min_arg_count) {
std::cout
<< "Usage: shard-seeder [number of shards] [number of utxos] "
"[utxo value] [witness_commitment_hex] [mode]\n\n "
" where [mode] = 0 (Atomizer), 1 (Two-phase commit)"
<< std::endl;
return -1;
}
auto start = std::chrono::system_clock::now();
;
auto num_shards = std::stoi(args[1]);
auto num_utxos = std::stoi(args[2]);
auto utxo_val = std::stoi(args[3]);
auto witness_commitment_str = args[4];
static constexpr auto mode_arg_idx = 5;
auto mode = std::stoi(args[mode_arg_idx]);
cbdc::hash_t witness_commitment
= cbdc::hash_from_hex(witness_commitment_str);
cbdc::transaction::wallet wal;
wal.seed_readonly(witness_commitment, utxo_val, 0, num_utxos);
auto shard_range
= (std::numeric_limits<cbdc::config::shard_range_t::first_type>::max()
+ 1)
/ num_shards;
auto gen_threads = std::vector<std::thread>(num_shards);
for(int i = 0; i < num_shards; i++) {
std::thread t(
[&](int shard_idx) {
auto shard_start = shard_idx * shard_range;
auto shard_end = (shard_idx + 1) * shard_range - 1;
if(shard_idx == num_shards - 1) {
shard_end = std::numeric_limits<
cbdc::config::shard_range_t::first_type>::max();
}
std::stringstream shard_db_dir;
if(mode == 1) {
shard_db_dir << "2pc_";
}
shard_db_dir << "shard_preseed_" << num_utxos << "_"
<< shard_start << "_" << shard_end;
logger.info("Starting seeding of shard ",
shard_idx,
" to database ",
shard_db_dir.str());
if(mode == 0) {
leveldb::Options opt;
opt.create_if_missing = true;
opt.write_buffer_size = leveldb_buffer_size;
leveldb::WriteOptions wopt;
leveldb::DB* db_ptr{};
const auto res
= leveldb::DB::Open(opt, shard_db_dir.str(), &db_ptr);
auto db = std::unique_ptr<leveldb::DB>(db_ptr);
if(!res.ok()) {
logger.error("Failed to open shard DB ",
shard_db_dir.str(),
" for shard ",
shard_idx,
": ",
res.ToString());
return;
}
auto tx = wal.create_seeded_transaction(0).value();
auto batch_size = 0;
leveldb::WriteBatch batch;
for(auto tx_idx = 0; tx_idx != num_utxos; tx_idx++) {
tx.m_inputs[0].m_prevout.m_index = tx_idx;
cbdc::transaction::compact_tx ctx(tx);
const cbdc::hash_t& output_hash = ctx.m_uhs_outputs[0];
if(output_hash[0] >= shard_start
&& output_hash[0] <= shard_end) {
std::array<char, sizeof(output_hash)> hash_arr{};
std::memcpy(hash_arr.data(),
output_hash.data(),
sizeof(output_hash));
leveldb::Slice hash_key(hash_arr.data(),
output_hash.size());
batch.Put(hash_key, leveldb::Slice());
batch_size++;
if(batch_size >= write_batch_size) {
db->Write(wopt, &batch);
batch.Clear();
batch_size = 0;
}
}
}
if(batch_size > 0) {
db->Write(wopt, &batch);
}
logger.info("Shard ", shard_idx, " succesfully seeded");
} else if(mode == 1) { // 2PC Shard
auto out
= std::ofstream(shard_db_dir.str(), std::ios::binary);
size_t count = 0;
// write dummy size
auto ser = cbdc::ostream_serializer(out);
ser << count;
auto tx = wal.create_seeded_transaction(0).value();
for(auto tx_idx = 0; tx_idx != num_utxos; tx_idx++) {
tx.m_inputs[0].m_prevout.m_index = tx_idx;
cbdc::transaction::compact_tx ctx(tx);
const cbdc::hash_t& output_hash = ctx.m_uhs_outputs[0];
if(output_hash[0] >= shard_start
&& output_hash[0] <= shard_end) {
ser << output_hash;
count++;
}
}
ser.reset();
ser << count;
}
},
i);
gen_threads[i] = std::move(t);
}
for(int i = 0; i < num_shards; i++) {
gen_threads[i].join();
}
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now() - start)
.count();
logger.info("Done in ", duration, "ms");
}
| 41.181287 | 79 | 0.472735 | vipinsun |
04bbded7bfda9c66cf28cb5d07828da734ad89a1 | 4,661 | cpp | C++ | demo_app/main.cpp | nvpro-samples/vk_compute_mipmaps | 613b94e4d36e6f357472e9c7a3163046deb55678 | [
"Apache-2.0"
] | 12 | 2021-07-24T18:33:22.000Z | 2022-03-12T16:20:49.000Z | demo_app/main.cpp | nvpro-samples/vk_compute_mipmaps | 613b94e4d36e6f357472e9c7a3163046deb55678 | [
"Apache-2.0"
] | null | null | null | demo_app/main.cpp | nvpro-samples/vk_compute_mipmaps | 613b94e4d36e6f357472e9c7a3163046deb55678 | [
"Apache-2.0"
] | 3 | 2021-08-04T02:27:12.000Z | 2022-03-13T08:43:24.000Z | // Copyright 2021 NVIDIA CORPORATION
// SPDX-License-Identifier: Apache-2.0
// Main function of the sample.
// Mostly just initializing GLFW, instance, device, extensions,
// then parsing arguments and passing control to the App implementation.
#include <cassert>
#include <stdio.h>
#include <string>
#include <vulkan/vulkan.h>
#include "GLFW/glfw3.h"
#include "nvvk/context_vk.hpp"
#include "nvvk/error_vk.hpp"
#include "app_args.hpp"
#include "mipmaps_app.hpp"
int main(int argc, char** argv)
{
AppArgs args;
parseArgs(argc, argv, &args);
// Create Vulkan glfw window unless disabled.
GLFWwindow* pWindow = nullptr;
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions = nullptr;
if (args.openWindow)
{
glfwInit();
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
const char* pTitle = "Compute Mipmaps";
pWindow = glfwCreateWindow(1920, 1080, pTitle, nullptr, nullptr);
assert(pWindow != nullptr);
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
assert(glfwExtensions != nullptr);
}
// Init Vulkan 1.1 device.
nvvk::Context ctx;
nvvk::ContextCreateInfo deviceInfo;
deviceInfo.apiMajor = 1;
deviceInfo.apiMinor = 1;
for (uint32_t i = 0; i < glfwExtensionCount; ++i)
{
deviceInfo.addInstanceExtension(glfwExtensions[i]);
}
#ifdef USE_DEBUG_UTILS
deviceInfo.addInstanceExtension(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
#endif
if (args.openWindow)
{
deviceInfo.addDeviceExtension(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
}
// Pipeline stats flag requires extension.
VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pipelinePropertyFeatures =
{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR};
if (args.dumpPipelineStats)
{
deviceInfo.addDeviceExtension(
VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME,
false,
&pipelinePropertyFeatures);
}
// Also need half floats.
VkPhysicalDeviceShaderFloat16Int8Features shaderFloat16Features = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES, nullptr,
true /* float16 */, false /* int8 */};
deviceInfo.addDeviceExtension(
VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME,
false,
&shaderFloat16Features);
ctx.init(deviceInfo);
ctx.ignoreDebugMessage(1303270965); // Bogus "general layout" perf warning.
// Query needed subgroup properties.
VkPhysicalDeviceSubgroupProperties subgroupProperties = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES};
VkPhysicalDeviceProperties2 physicalDeviceProperties = {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroupProperties};
vkGetPhysicalDeviceProperties2(ctx.m_physicalDevice, &physicalDeviceProperties);
if (subgroupProperties.subgroupSize < 16)
{
fprintf(stderr, "Expected subgroup size at least 16.\n");
return 1;
}
else if (subgroupProperties.subgroupSize != 32)
{
fprintf(stderr, "\x1b[35m\x1b[1mWARNING:\x1b[0m "
"Only tested with subgroup size 32, not %u.\nI /expect/ "
"it to work anyway, notify dakeley@nvidia.com if not.\n",
subgroupProperties.subgroupSize);
}
#define NEED_BIT(var, bit) \
if (!(var & bit)) \
{ \
fprintf(stderr, "Needed capability: %s\n", #bit); \
return -1; \
}
NEED_BIT(subgroupProperties.supportedStages, VK_SHADER_STAGE_COMPUTE_BIT);
NEED_BIT(subgroupProperties.supportedOperations, VK_SUBGROUP_FEATURE_SHUFFLE_BIT);
#undef NEED_BIT
// Query needed feature for pipeline stats.
if (args.dumpPipelineStats && !pipelinePropertyFeatures.pipelineExecutableInfo)
{
fprintf(stderr,
"missing VK_KHR_pipeline_executable_properties;\n"
"needed for -stats flag\n");
return 1;
}
// Query half float feature.
if (!shaderFloat16Features.shaderFloat16)
{
fprintf(stderr, "missing shaderFloat16 feature\n");
return 1;
}
// Get the surface to draw to.
VkSurfaceKHR surface = VK_NULL_HANDLE;
if (args.openWindow)
{
NVVK_CHECK(glfwCreateWindowSurface(
ctx.m_instance, pWindow, nullptr, &surface));
}
else
{
fprintf(stderr, "Window implicitly disabled.\n");
}
// Start the main loop.
mipmapsApp(ctx, pWindow, surface, args);
// At this point, FrameManager's destructor in mainLoop ensures all
// pending commands are complete. So, we can clean up the surface,
// Vulkan device, and glfw.
if (args.openWindow)
{
vkDestroySurfaceKHR(ctx.m_instance, surface, nullptr);
glfwTerminate();
}
ctx.deinit();
}
| 30.664474 | 86 | 0.721948 | nvpro-samples |
04bcb616c7b897efb490f830e87b1d5544b34162 | 26,909 | cc | C++ | crawl-ref/source/los.cc | ludamad/bcrawl-hacks | 0c82f6181d8c2ffcb58f374a58887694cdd407ae | [
"CC0-1.0"
] | 58 | 2018-12-10T05:09:50.000Z | 2022-01-17T02:22:49.000Z | crawl-ref/source/los.cc | ludamad/bcrawl-hacks | 0c82f6181d8c2ffcb58f374a58887694cdd407ae | [
"CC0-1.0"
] | 501 | 2020-04-06T07:19:01.000Z | 2022-02-23T13:04:40.000Z | crawl-ref/source/los.cc | alexjurkiewicz/crawl-ref | b30f108f014aa9282fecf9cd6d84024ab3608e69 | [
"CC0-1.0"
] | 74 | 2020-04-06T07:40:50.000Z | 2021-05-21T00:13:36.000Z | /**
* @file
* @brief Line-of-sight algorithm.
*
*
*
* == Definition of visibility ==
*
* Two cells are in view of each other if there is any straight
* line that meets both cells and that doesn't meet any opaque
* cell in between, and if the cells are in LOS range of each
* other.
*
* Here, to "meet" a cell means to intersect the interior. In
* particular, rays can pass between to diagonally adjacent
* walls (as can the player).
*
* == Terminology ==
*
* A _ray_ is a line, specified by starting point (accx, accy)
* and slope. A ray determines its _footprint_: the sequence of
* cells whose interiour it meets.
*
* Any prefix of the footprint of a ray is called a _cellray_.
*
* For the purposes of LOS calculation, only the footprints
* are relevant, but rays are also used for shooting beams,
* which may travel beyond LOS and which can be reflected.
* See ray.cc.
*
* == Overview ==
*
* At first use, the LOS code makes some precomputations,
* filling a list of all relevant rays in one quadrant,
* and filling data structures that allow calculating LOS
* in a quadrant without checking each ray.
*
* The code provides functions for filling LOS information
* around a given center efficiently, and for querying rays
* between two given cells.
**/
#include "AppHdr.h"
#include "los.h"
#include <algorithm>
#include <cmath>
#include "areas.h"
#include "coord.h"
#include "coordit.h"
#include "env.h"
#include "losglobal.h"
#include "mon-act.h"
// These determine what rays are cast in the precomputation,
// and affect start-up time significantly.
// XXX: Argue that these values are sufficient.
#define LOS_MAX_ANGLE (2*LOS_MAX_RANGE-2)
#define LOS_INTERCEPT_MULT (2)
// These store all unique (in terms of footprint) full rays.
// The footprint of ray=fullray[i] consists of ray.length cells,
// stored in ray_coords[ray.start..ray.length-1].
// These are filled during precomputation (_register_ray).
// XXX: fullrays is not needed anymore after precomputation.
struct los_ray;
static vector<los_ray> fullrays;
static vector<coord_def> ray_coords;
// These store all unique minimal cellrays. For each i,
// cellray i ends in cellray_ends[i] and passes through
// thoses cells p that have blockrays(p)[i] set. In other
// words, blockrays(p)[i] is set iff an opaque cell p blocks
// the cellray with index i.
static vector<coord_def> cellray_ends;
typedef FixedArray<bit_vector*, LOS_MAX_RANGE+1, LOS_MAX_RANGE+1> blockrays_t;
static blockrays_t blockrays;
// We also store the minimal cellrays by target position
// for efficient retrieval by find_ray.
// XXX: Consider condensing this representation.
struct cellray;
static FixedArray<vector<cellray>, LOS_MAX_RANGE+1, LOS_MAX_RANGE+1> min_cellrays;
// Temporary arrays used in losight() to track which rays
// are blocked or have seen a smoke cloud.
// Allocated when doing the precomputations.
static bit_vector *dead_rays = nullptr;
static bit_vector *smoke_rays = nullptr;
class quadrant_iterator : public rectangle_iterator
{
public:
quadrant_iterator()
: rectangle_iterator(coord_def(0,0),
coord_def(LOS_MAX_RANGE, LOS_MAX_RANGE))
{
}
};
void clear_rays_on_exit()
{
delete dead_rays;
delete smoke_rays;
for (quadrant_iterator qi; qi; ++qi)
delete blockrays(*qi);
}
// LOS radius.
int los_radius = LOS_DEFAULT_RANGE;
static void _handle_los_change();
void set_los_radius(int r)
{
ASSERT(r <= LOS_RADIUS);
los_radius = r;
invalidate_los();
_handle_los_change();
}
int get_los_radius()
{
return los_radius;
}
bool double_is_zero(const double x)
{
return x > -EPSILON_VALUE && x < EPSILON_VALUE;
}
struct los_ray : public ray_def
{
// The footprint of this ray is stored in
// ray_coords[start..start+length-1].
unsigned int start;
unsigned int length;
los_ray(geom::ray _r)
: ray_def(_r), start(0), length(0)
{
}
// Shoot a ray from the given start point (accx, accy) with the given
// slope, bounded by the pre-calc bounds shape.
// Returns the cells it travels through, excluding the origin.
// Returns an empty vector if this was a bad ray.
vector<coord_def> footprint()
{
vector<coord_def> cs;
los_ray copy = *this;
coord_def c;
coord_def old;
int cellnum;
for (cellnum = 0; true; ++cellnum)
{
old = c;
if (!copy.advance())
{
// dprf("discarding corner ray (%f,%f) + t*(%f,%f)",
// r.start.x, r.start.y, r.dir.x, r.dir.y);
cs.clear();
break;
}
c = copy.pos();
if (c.rdist() > LOS_RADIUS)
break;
cs.push_back(c);
ASSERT((c - old).rdist() == 1);
}
return cs;
}
coord_def operator[](unsigned int i)
{
ASSERT(i < length);
return ray_coords[start+i];
}
};
// Check if the passed rays have identical footprint.
static bool _is_same_ray(los_ray ray, vector<coord_def> newray)
{
if (ray.length != newray.size())
return false;
for (unsigned int i = 0; i < ray.length; i++)
if (ray[i] != newray[i])
return false;
return true;
}
// Check if the passed ray has already been created.
static bool _is_duplicate_ray(vector<coord_def> newray)
{
for (los_ray lray : fullrays)
if (_is_same_ray(lray, newray))
return true;
return false;
}
// A cellray given by fullray and index of end-point.
struct cellray
{
// A cellray passes through cells ray_coords[ray.start..ray.start+end].
los_ray ray;
unsigned int end; // Relative index (inside ray) of end cell.
cellray(const los_ray& r, unsigned int e)
: ray(r), end(e), imbalance(-1), first_diag(false)
{
}
// The end-point's index inside ray_coord.
int index() const { return ray.start + end; }
// The end-point.
coord_def target() const { return ray_coords[index()]; }
// XXX: Currently ray/cellray[0] is the first point outside the origin.
coord_def operator[](unsigned int i)
{
ASSERT(i <= end);
return ray_coords[ray.start+i];
}
// Parameters used in find_ray. These need to be calculated
// only for the minimal cellrays.
int imbalance;
bool first_diag;
void calc_params();
};
// Compare two cellrays to the same target.
// This determines which ray is considered better by find_ray,
// used with list::sort.
// Returns true if a is strictly better than b, false else.
static bool _is_better(const cellray& a, const cellray& b)
{
// Only compare cellrays with equal target.
ASSERT(a.target() == b.target());
// calc_params() has been called.
ASSERT(a.imbalance >= 0);
ASSERT(b.imbalance >= 0);
if (a.imbalance < b.imbalance)
return true;
else if (a.imbalance > b.imbalance)
return false;
else
return a.first_diag && !b.first_diag;
}
enum class compare_type
{
neither,
subray,
superray,
};
// Check whether one of the passed cellrays is a subray of the
// other in terms of footprint.
static compare_type _compare_cellrays(const cellray& a, const cellray& b)
{
if (a.target() != b.target())
return compare_type::neither;
int cura = a.ray.start;
int curb = b.ray.start;
int enda = cura + a.end;
int endb = curb + b.end;
bool maybe_sub = true;
bool maybe_super = true;
while (cura < enda && curb < endb && (maybe_sub || maybe_super))
{
coord_def pa = ray_coords[cura];
coord_def pb = ray_coords[curb];
if (pa.x > pb.x || pa.y > pb.y)
{
maybe_super = false;
curb++;
}
if (pa.x < pb.x || pa.y < pb.y)
{
maybe_sub = false;
cura++;
}
if (pa == pb)
{
cura++;
curb++;
}
}
maybe_sub = maybe_sub && cura == enda;
maybe_super = maybe_super && curb == endb;
if (maybe_sub)
return compare_type::subray; // includes equality
else if (maybe_super)
return compare_type::superray;
else
return compare_type::neither;
}
// Determine all minimal cellrays.
// They're stored globally by target in min_cellrays,
// and returned as a list of indices into ray_coords.
static vector<int> _find_minimal_cellrays()
{
FixedArray<list<cellray>, LOS_MAX_RANGE+1, LOS_MAX_RANGE+1> minima;
list<cellray>::iterator min_it;
for (los_ray ray : fullrays)
{
for (unsigned int i = 0; i < ray.length; ++i)
{
// Is the cellray ray[0..i] duplicated so far?
bool dup = false;
cellray c(ray, i);
list<cellray>& min = minima(c.target());
bool erased = false;
for (min_it = min.begin();
min_it != min.end() && !dup;)
{
switch (_compare_cellrays(*min_it, c))
{
case compare_type::subray:
dup = true;
break;
case compare_type::superray:
min_it = min.erase(min_it);
erased = true;
// clear this should be added, but might have
// to erase more
break;
case compare_type::neither:
default:
break;
}
if (!erased)
++min_it;
else
erased = false;
}
if (!dup)
min.push_back(c);
}
}
vector<int> result;
for (quadrant_iterator qi; qi; ++qi)
{
list<cellray>& min = minima(*qi);
for (min_it = min.begin(); min_it != min.end(); ++min_it)
{
// Calculate imbalance and slope difference for sorting.
min_it->calc_params();
result.push_back(min_it->index());
}
min.sort(_is_better);
min_cellrays(*qi) = vector<cellray>(min.begin(), min.end());
}
return result;
}
// Create and register the ray defined by the arguments.
static void _register_ray(geom::ray r)
{
los_ray ray = los_ray(r);
vector<coord_def> coords = ray.footprint();
if (coords.empty() || _is_duplicate_ray(coords))
return;
ray.start = ray_coords.size();
ray.length = coords.size();
for (coord_def c : coords)
ray_coords.push_back(c);
fullrays.push_back(ray);
}
static void _create_blockrays()
{
// First, we calculate blocking information for all cell rays.
// Cellrays are numbered according to the index of their end
// cell in ray_coords.
const int n_cellrays = ray_coords.size();
blockrays_t all_blockrays;
for (quadrant_iterator qi; qi; ++qi)
all_blockrays(*qi) = new bit_vector(n_cellrays);
for (los_ray ray : fullrays)
{
for (unsigned int i = 0; i < ray.length; ++i)
{
// Every cell is contained in (thus blocks)
// all following cellrays.
for (unsigned int j = i + 1; j < ray.length; ++j)
all_blockrays(ray[i])->set(ray.start + j);
}
}
// We've built the basic blockray array; now compress it, keeping
// only the nonduplicated cellrays.
// Determine minimal cellrays and store their indices in ray_coords.
vector<int> min_indices = _find_minimal_cellrays();
const int n_min_rays = min_indices.size();
cellray_ends.resize(n_min_rays);
for (int i = 0; i < n_min_rays; ++i)
cellray_ends[i] = ray_coords[min_indices[i]];
// Compress blockrays accordingly.
for (quadrant_iterator qi; qi; ++qi)
{
blockrays(*qi) = new bit_vector(n_min_rays);
for (int i = 0; i < n_min_rays; ++i)
{
blockrays(*qi)->set(i, all_blockrays(*qi)
->get(min_indices[i]));
}
}
// We can throw away all_blockrays now.
for (quadrant_iterator qi; qi; ++qi)
delete all_blockrays(*qi);
dead_rays = new bit_vector(n_min_rays);
smoke_rays = new bit_vector(n_min_rays);
dprf("Cellrays: %d Fullrays: %u Minimal cellrays: %u",
n_cellrays, (unsigned int)fullrays.size(), n_min_rays);
}
static int _gcd(int x, int y)
{
int tmp;
while (y != 0)
{
x %= y;
tmp = x;
x = y;
y = tmp;
}
return x;
}
static bool _complexity_lt(const pair<int,int>& lhs, const pair<int,int>& rhs)
{
return lhs.first * lhs.second < rhs.first * rhs.second;
}
// Cast all rays
static void raycast()
{
static bool done_raycast = false;
if (done_raycast)
return;
// Creating all rays for first quadrant
// We have a considerable amount of overkill.
done_raycast = true;
// register perpendiculars FIRST, to make them top choice
// when selecting beams
_register_ray(geom::ray(0.5, 0.5, 0.0, 1.0));
_register_ray(geom::ray(0.5, 0.5, 1.0, 0.0));
// For a slope of M = y/x, every x we move on the X axis means
// that we move y on the y axis. We want to look at the resolution
// of x/y: in that case, every step on the X axis means an increase
// of 1 in the Y axis at the intercept point. We can assume gcd(x,y)=1,
// so we look at steps of 1/y.
// Changing the order a bit. We want to order by the complexity
// of the beam, which is log(x) + log(y) ~ xy.
vector<pair<int,int> > xyangles;
for (int xangle = 1; xangle <= LOS_MAX_ANGLE; ++xangle)
for (int yangle = 1; yangle <= LOS_MAX_ANGLE; ++yangle)
{
if (_gcd(xangle, yangle) == 1)
xyangles.emplace_back(xangle, yangle);
}
sort(xyangles.begin(), xyangles.end(), _complexity_lt);
for (auto xyangle : xyangles)
{
const int xangle = xyangle.first;
const int yangle = xyangle.second;
for (int intercept = 1; intercept < LOS_INTERCEPT_MULT*yangle; ++intercept)
{
double xstart = ((double)intercept) / (LOS_INTERCEPT_MULT*yangle);
double ystart = 0.5;
_register_ray(geom::ray(xstart, ystart, xangle, yangle));
// also draw the identical ray in octant 2
_register_ray(geom::ray(ystart, xstart, yangle, xangle));
}
}
// Now create the appropriate blockrays array
_create_blockrays();
}
static int _imbalance(ray_def ray, const coord_def& target)
{
int imb = 0;
int diags = 0, straights = 0;
while (ray.pos() != target)
{
coord_def old = ray.pos();
if (!ray.advance())
die("can't advance ray");
switch ((ray.pos() - old).abs())
{
case 1:
diags = 0;
if (++straights > imb)
imb = straights;
break;
case 2:
straights = 0;
if (++diags > imb)
imb = diags;
break;
default:
die("ray imbalance out of range");
}
}
return imb;
}
void cellray::calc_params()
{
coord_def trg = target();
imbalance = _imbalance(ray, trg);
first_diag = ((*this)[0].abs() == 2);
}
// Find ray in positive quadrant.
// opc has been translated for this quadrant.
// XXX: Allow finding ray of minimum opacity.
static bool _find_ray_se(const coord_def& target, ray_def& ray,
const opacity_func& opc, int range, bool cycle)
{
ASSERT(target.x >= 0);
ASSERT(target.y >= 0);
ASSERT(!target.origin());
if (target.rdist() > range)
return false;
ASSERT(target.rdist() <= LOS_RADIUS);
// Ensure the precalculations have been done.
raycast();
const vector<cellray> &min = min_cellrays(target);
ASSERT(!min.empty());
cellray c = min[0]; // XXX: const cellray &c ?
unsigned int index = 0;
if (cycle)
dprf("cycling from %d (total %u)", ray.cycle_idx, (unsigned int)min.size());
unsigned int start = cycle ? ray.cycle_idx + 1 : 0;
ASSERT(start <= min.size());
int blocked = OPC_OPAQUE;
for (unsigned int i = start;
(blocked >= OPC_OPAQUE) && (i < start + min.size()); i++)
{
index = i % min.size();
c = min[index];
blocked = OPC_CLEAR;
// Check all inner points.
for (unsigned int j = 0; j < c.end && blocked < OPC_OPAQUE; j++)
blocked += opc(c[j]);
}
if (blocked >= OPC_OPAQUE)
return false;
ray = c.ray;
ray.cycle_idx = index;
return true;
}
// Coordinate transformation so we can find_ray quadrant-by-quadrant.
struct opacity_trans : public opacity_func
{
const coord_def& source;
int signx, signy;
const opacity_func& orig;
opacity_trans(const opacity_func& opc, const coord_def& s, int sx, int sy)
: source(s), signx(sx), signy(sy), orig(opc)
{
}
CLONE(opacity_trans)
opacity_type operator()(const coord_def &l) const override
{
return orig(transform(l));
}
coord_def transform(const coord_def &l) const
{
return coord_def(source.x + signx*l.x, source.y + signy*l.y);
}
};
// Find a nonblocked ray from source to target. Return false if no
// such ray could be found, otherwise return true and fill ray
// appropriately.
// if range is too great or all rays are blocked.
// If cycle is false, find the first fitting ray. If it is true,
// assume that ray is appropriately filled in, and look for the next
// ray. We only ever use ray.cycle_idx.
bool find_ray(const coord_def& source, const coord_def& target,
ray_def& ray, const opacity_func& opc, int range,
bool cycle)
{
if (target == source || !map_bounds(source) || !map_bounds(target))
return false;
const int signx = ((target.x - source.x >= 0) ? 1 : -1);
const int signy = ((target.y - source.y >= 0) ? 1 : -1);
const int absx = signx * (target.x - source.x);
const int absy = signy * (target.y - source.y);
const coord_def abs = coord_def(absx, absy);
opacity_trans opc_trans = opacity_trans(opc, source, signx, signy);
if (!_find_ray_se(abs, ray, opc_trans, range, cycle))
return false;
if (signx < 0)
ray.r.start.x = 1.0 - ray.r.start.x;
if (signy < 0)
ray.r.start.y = 1.0 - ray.r.start.y;
ray.r.dir.x *= signx;
ray.r.dir.y *= signy;
ray.r.start.x += source.x;
ray.r.start.y += source.y;
return true;
}
bool exists_ray(const coord_def& source, const coord_def& target,
const opacity_func& opc, int range)
{
ray_def ray;
return find_ray(source, target, ray, opc, range);
}
// Assuming that target is in view of source, but line of
// fire is blocked, what is it blocked by?
dungeon_feature_type ray_blocker(const coord_def& source,
const coord_def& target)
{
ray_def ray;
if (!find_ray(source, target, ray, opc_default))
{
ASSERT(you.xray_vision);
return NUM_FEATURES;
}
ray.advance();
int blocked = 0;
while (ray.pos() != target)
{
blocked += opc_solid_see(ray.pos());
if (blocked >= OPC_OPAQUE)
return env.grid(ray.pos());
ray.advance();
}
ASSERT(false);
return NUM_FEATURES;
}
// Returns a straight ray from source to target.
void fallback_ray(const coord_def& source, const coord_def& target,
ray_def& ray)
{
ray.r.start.x = source.x + 0.5;
ray.r.start.y = source.y + 0.5;
coord_def diff = target - source;
ray.r.dir.x = diff.x;
ray.r.dir.y = diff.y;
ray.on_corner = false;
}
// Count the number of matching features between two points along
// a beam-like path; the path will pass through solid features.
// By default, it excludes end points from the count.
// If just_check is true, the function will return early once one
// such feature is encountered.
int num_feats_between(const coord_def& source, const coord_def& target,
dungeon_feature_type min_feat,
dungeon_feature_type max_feat,
bool exclude_endpoints, bool just_check)
{
ray_def ray;
int count = 0;
int max_dist = grid_distance(source, target);
ASSERT(map_bounds(source));
ASSERT(map_bounds(target));
if (source == target)
return 0; // XXX: might want to count the cell.
// We don't need to find the shortest beam, any beam will suffice.
fallback_ray(source, target, ray);
if (exclude_endpoints && ray.pos() == source)
{
ray.advance();
max_dist--;
}
int dist = 0;
bool reached_target = false;
while (dist++ <= max_dist)
{
const dungeon_feature_type feat = grd(ray.pos());
if (ray.pos() == target)
reached_target = true;
if (feat >= min_feat && feat <= max_feat
&& (!exclude_endpoints || !reached_target))
{
count++;
if (just_check) // Only needs to be > 0.
return count;
}
if (reached_target)
break;
ray.advance();
}
return count;
}
// Is p2 visible from p1, disregarding half-opaque objects?
bool cell_see_cell_nocache(const coord_def& p1, const coord_def& p2)
{
return exists_ray(p1, p2, opc_fullyopaque);
}
// We use raycasting. The algorithm:
// PRECOMPUTATION:
// Create a large bundle of rays and cast them.
// Mark, for each one, which cells kill it (and where.)
// Also, for each one, note which cells it passes.
// ACTUAL LOS:
// Unite the ray-killers for the given map; this tells you which rays
// are dead.
// Look up which cells the surviving rays have, and that's your LOS!
// OPTIMIZATIONS:
// WLOG, we can assume that we're in a specific quadrant - say the
// first quadrant - and just mirror everything after that. We can
// likely get away with a single octant, but we don't do that. (To
// do...)
// Rays are actually split by each cell they pass. So each "ray" only
// identifies a single cell, and we can do logical ORs. Once a cell
// kills a cellray, it will kill all remaining cellrays of that ray.
// Also, rays are checked to see if they are duplicates of each
// other. If they are, they're eliminated.
// Some cellrays can also be eliminated. In general, a cellray is
// unnecessary if there is another cellray with the same coordinates,
// and whose path (up to those coordinates) is a subset, not necessarily
// proper, of the original path. We still store the original cellrays
// fully for beam detection and such.
// PERFORMANCE:
// With reasonable values we have around 6000 cellrays, meaning
// around 600Kb (75 KB) of data. This gets cut down to 700 cellrays
// after removing duplicates. That means that we need to do
// around 22*100*4 ~ 9,000 memory reads + writes per LOS call on a
// 32-bit system. Not too bad.
// IMPROVEMENTS:
// Smoke will now only block LOS after two cells of smoke. This is
// done by updating with a second array.
static void _losight_quadrant(los_grid& sh, const los_param& dat, int sx, int sy)
{
const unsigned int num_cellrays = cellray_ends.size();
dead_rays->reset();
smoke_rays->reset();
for (quadrant_iterator qi; qi; ++qi)
{
coord_def p = coord_def(sx*(qi->x), sy*(qi->y));
if (!dat.los_bounds(p))
continue;
switch (dat.opacity(p))
{
case OPC_OPAQUE:
// Block the appropriate rays.
*dead_rays |= *blockrays(*qi);
break;
case OPC_HALF:
// Block rays which have already seen a cloud.
*dead_rays |= (*smoke_rays & *blockrays(*qi));
*smoke_rays |= *blockrays(*qi);
break;
default:
break;
}
}
// Ray calculation done. Now work out which cells in this
// quadrant are visible.
for (unsigned int rayidx = 0; rayidx < num_cellrays; ++rayidx)
{
// make the cells seen by this ray at this point visible
if (!dead_rays->get(rayidx))
{
// This ray is alive, thus the end cell is visible.
const coord_def p = coord_def(sx * cellray_ends[rayidx].x,
sy * cellray_ends[rayidx].y);
if (dat.los_bounds(p))
sh(p) = true;
}
}
}
struct los_param_funcs : public los_param
{
coord_def center;
const opacity_func& opc;
const circle_def& bounds;
los_param_funcs(const coord_def& c,
const opacity_func& o, const circle_def& b)
: center(c), opc(o), bounds(b)
{
}
bool los_bounds(const coord_def& p) const override
{
return map_bounds(p + center) && bounds.contains(p);
}
opacity_type opacity(const coord_def& p) const override
{
return opc(p + center);
}
};
void losight(los_grid& sh, const coord_def& center,
const opacity_func& opc, const circle_def& bounds)
{
const los_param& dat = los_param_funcs(center, opc, bounds);
sh.init(false);
// Do precomputations if necessary.
raycast();
const int quadrant_x[4] = { 1, -1, -1, 1 };
const int quadrant_y[4] = { 1, 1, -1, -1 };
for (int q = 0; q < 4; ++q)
_losight_quadrant(sh, dat, quadrant_x[q], quadrant_y[q]);
// Center is always visible.
const coord_def o = coord_def(0,0);
sh(o) = true;
}
opacity_type mons_opacity(const monster* mon, los_type how)
{
// no regard for LOS_ARENA
if (mons_species(mon->type) == MONS_BUSH
&& how != LOS_SOLID)
{
return OPC_HALF;
}
return OPC_CLEAR;
}
/////////////////////////////////////
// A start at tracking LOS changes.
// Something that affects LOS (with default parameters)
// has changed somewhere.
static void _handle_los_change()
{
invalidate_agrid();
}
static bool _mons_block_sight(const monster* mons)
{
// must be the least permissive one
return mons_opacity(mons, LOS_SOLID_SEE) != OPC_CLEAR;
}
void los_actor_moved(const actor* act, const coord_def& oldpos)
{
if (act->is_monster() && _mons_block_sight(act->as_monster()))
{
invalidate_los_around(oldpos);
invalidate_los_around(act->pos());
_handle_los_change();
}
}
void los_monster_died(const monster* mon)
{
if (_mons_block_sight(mon))
{
invalidate_los_around(mon->pos());
_handle_los_change();
}
}
// Might want to pass new/old terrain.
void los_terrain_changed(const coord_def& p)
{
invalidate_los_around(p);
_handle_los_change();
}
void los_changed()
{
mons_reset_just_seen();
invalidate_los();
_handle_los_change();
}
| 28.565817 | 84 | 0.608309 | ludamad |
04becf19b985a7092dc89ea17e5530b33b2f347a | 2,802 | hpp | C++ | Nacro/SDK/FN_Niagara_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_Niagara_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_Niagara_parameters.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Niagara.NiagaraFunctionLibrary.SpawnEffectAttached
struct UNiagaraFunctionLibrary_SpawnEffectAttached_Params
{
class UNiagaraEffect* EffectTemplate; // (Parm, ZeroConstructor, IsPlainOldData)
class USceneComponent* AttachToComponent; // (Parm, ZeroConstructor, InstancedReference, IsPlainOldData)
struct FName AttachPointName; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector Location; // (Parm, IsPlainOldData)
struct FRotator Rotation; // (Parm, IsPlainOldData)
TEnumAsByte<EAttachLocation> LocationType; // (Parm, ZeroConstructor, IsPlainOldData)
bool bAutoDestroy; // (Parm, ZeroConstructor, IsPlainOldData)
class UNiagaraComponent* ReturnValue; // (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData)
};
// Function Niagara.NiagaraFunctionLibrary.SpawnEffectAtLocation
struct UNiagaraFunctionLibrary_SpawnEffectAtLocation_Params
{
class UObject* WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData)
class UNiagaraEffect* EffectTemplate; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector Location; // (Parm, IsPlainOldData)
struct FRotator Rotation; // (Parm, IsPlainOldData)
bool bAutoDestroy; // (Parm, ZeroConstructor, IsPlainOldData)
class UNiagaraComponent* ReturnValue; // (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 60.913043 | 207 | 0.445039 | Milxnor |
04c035d70f5da417000ddff4f4f933657b3a7c1f | 861 | cpp | C++ | Code/Platform/Platform.cpp | WarzesProject/IsekaiWorld | 2abbf0fba0cf7aef884dd93ebada402f14b98359 | [
"MIT"
] | 1 | 2019-10-07T08:59:01.000Z | 2019-10-07T08:59:01.000Z | Code/Platform/Platform.cpp | WarzesProject/IsekaiWorld | 2abbf0fba0cf7aef884dd93ebada402f14b98359 | [
"MIT"
] | null | null | null | Code/Platform/Platform.cpp | WarzesProject/IsekaiWorld | 2abbf0fba0cf7aef884dd93ebada402f14b98359 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Platform.h"
//-----------------------------------------------------------------------------
Platform::Platform()
{
#if SE_PLATFORM_WINDOWS
if (timeBeginPeriod(1) == TIMERR_NOCANDO)
{
TODO("Log");//"Unable to set timer resolution to 1ms.This can cause significant waste in performance for waiting threads.";
}
#endif
setValid(true);
}
//-----------------------------------------------------------------------------
Platform::~Platform()
{
#if SE_PLATFORM_WINDOWS
timeEndPeriod(1);
#endif
}
//-----------------------------------------------------------------------------
void Platform::PrintDebugOutput(std::string_view str)
{
#if SE_COMPILER_MSVC && SE_DEBUG
OutputDebugStringA(str.data());
OutputDebugStringA("\n");
#else
(void)str;
#endif
}
//----------------------------------------------------------------------------- | 27.774194 | 125 | 0.463415 | WarzesProject |
04c88acf6d3202be67cf11e2fe02c3ea3ee0d62f | 2,594 | cpp | C++ | keychain_win/secmodlib/src/NamedPipeServer.cpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 29 | 2018-03-21T09:21:18.000Z | 2020-09-22T16:31:03.000Z | keychain_win/secmodlib/src/NamedPipeServer.cpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 119 | 2018-03-16T14:02:04.000Z | 2019-04-16T21:16:32.000Z | keychain_win/secmodlib/src/NamedPipeServer.cpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 3 | 2018-03-21T15:00:16.000Z | 2019-12-25T09:03:58.000Z | #include "NamedPipeServer.h"
#include <keychain_lib/pipeline_parser.hpp>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <future>
#include "SecureModuleWrapper.h"
#include <keychain_lib/keychain_logger.hpp>
NamedPipeServer::NamedPipeServer() {
//_secManage = new SecurityManager();
}
NamedPipeServer::~NamedPipeServer() {
}
using namespace keychain_app;
void NamedPipeServer::ListenChannel(/*LPTSTR channelName*/) {
lpszPipename = (LPTSTR)__TEXT("\\\\.\\pipe\\keychainservice");//channelName;
auto& log = logger_singleton::instance();
BOOST_LOG_SEV(log.lg, info) << "Creating NamedPipe object";
hPipe = CreateNamedPipe(
lpszPipename, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
BUFSIZE, // output buffer size
BUFSIZE, // input buffer size
0, // client time-out
NULL); // default security attribute
BOOST_LOG_SEV(log.lg, info) << "NamedPipe object is created";
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
BOOST_LOG_SEV(log.lg, info) << "ConnectingNamePipe";
if (!fConnected)
{
BOOST_LOG_SEV(log.lg, error) << "Connection error";
BOOST_LOG_SEV(log.lg, error) << std::to_string(GetLastError());
// The client could not connect, so close the pipe.
CloseHandle(hPipe);
return;
}
auto fd = _open_osfhandle(reinterpret_cast<intptr_t>(hPipe), _O_APPEND | _O_RDWR);
BOOST_LOG_SEV(log.lg, info) << "Client connected, creating a processing thread.";
auto res = std::async(std::launch::async, [this](int fd)->int {
SecureModuleWrapper secureModuleWrapper;
auto& keychain_ref = keychain::instance();
secureModuleWrapper.connect(keychain_ref);
keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1);
pipeline_parser pipe_line_parser_(std::move(f), fd, fd);
int res = pipe_line_parser_.run();
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return res;
}, fd);
try
{
if (res.get() == -1)
BOOST_LOG_SEV(log.lg, error) << "Error: cannot read from pipe";
}
catch (const std::exception& e)
{
BOOST_LOG_SEV(log.lg, error) << "Error: cannot read from pipe";
BOOST_LOG_SEV(log.lg, error) << e.what();
}
};
| 31.634146 | 102 | 0.661527 | jokefor300 |
04c8a817f73d528d1e13da00c3ecd6aed24a43ac | 608 | hpp | C++ | src/Ast/Block.hpp | JCube001/pl0 | a6ce723ffc7f639ab64d1a06946990fb6ec295d5 | [
"MIT"
] | null | null | null | src/Ast/Block.hpp | JCube001/pl0 | a6ce723ffc7f639ab64d1a06946990fb6ec295d5 | [
"MIT"
] | null | null | null | src/Ast/Block.hpp | JCube001/pl0 | a6ce723ffc7f639ab64d1a06946990fb6ec295d5 | [
"MIT"
] | null | null | null | #ifndef PL0_AST_BLOCK_HPP
#define PL0_AST_BLOCK_HPP
#include "Ast/Node.hpp"
#include <memory>
#include <vector>
namespace PL0 {
namespace Ast {
struct Constant;
struct Identifier;
struct Procedure;
struct Statement;
struct Block final : public Node
{
void accept(Visitor& visitor) override
{ visitor.visit(*this); }
std::vector<std::unique_ptr<Constant>> constants;
std::vector<std::unique_ptr<Identifier>> variables;
std::vector<std::unique_ptr<Procedure>> procedures;
std::unique_ptr<Statement> statement;
};
} // namespace Ast
} // namespace PL0
#endif // PL0_AST_BLOCK_HPP
| 19.612903 | 55 | 0.731908 | JCube001 |
04c8b5681af094cb9ec710f32945e579d39739ff | 3,024 | hpp | C++ | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/VisualShaderNodeGroupBase.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 5 | 2021-05-27T21:50:33.000Z | 2022-01-28T11:54:32.000Z | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/VisualShaderNodeGroupBase.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | null | null | null | climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/VisualShaderNodeGroupBase.hpp | jerry871002/CSE201-project | c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4 | [
"MIT"
] | 1 | 2021-01-04T21:12:05.000Z | 2021-01-04T21:12:05.000Z | #ifndef GODOT_CPP_VISUALSHADERNODEGROUPBASE_HPP
#define GODOT_CPP_VISUALSHADERNODEGROUPBASE_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "VisualShaderNode.hpp"
namespace godot {
class VisualShaderNodeGroupBase : public VisualShaderNode {
struct ___method_bindings {
godot_method_bind *mb_add_input_port;
godot_method_bind *mb_add_output_port;
godot_method_bind *mb_clear_input_ports;
godot_method_bind *mb_clear_output_ports;
godot_method_bind *mb_get_free_input_port_id;
godot_method_bind *mb_get_free_output_port_id;
godot_method_bind *mb_get_input_port_count;
godot_method_bind *mb_get_inputs;
godot_method_bind *mb_get_output_port_count;
godot_method_bind *mb_get_outputs;
godot_method_bind *mb_get_size;
godot_method_bind *mb_has_input_port;
godot_method_bind *mb_has_output_port;
godot_method_bind *mb_is_valid_port_name;
godot_method_bind *mb_remove_input_port;
godot_method_bind *mb_remove_output_port;
godot_method_bind *mb_set_input_port_name;
godot_method_bind *mb_set_input_port_type;
godot_method_bind *mb_set_inputs;
godot_method_bind *mb_set_output_port_name;
godot_method_bind *mb_set_output_port_type;
godot_method_bind *mb_set_outputs;
godot_method_bind *mb_set_size;
};
static ___method_bindings ___mb;
static void *_detail_class_tag;
public:
static void ___init_method_bindings();
inline static size_t ___get_id() { return (size_t)_detail_class_tag; }
static inline const char *___get_class_name() { return (const char *) "VisualShaderNodeGroupBase"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
// constants
static VisualShaderNodeGroupBase *_new();
// methods
void add_input_port(const int64_t id, const int64_t type, const String name);
void add_output_port(const int64_t id, const int64_t type, const String name);
void clear_input_ports();
void clear_output_ports();
int64_t get_free_input_port_id() const;
int64_t get_free_output_port_id() const;
int64_t get_input_port_count() const;
String get_inputs() const;
int64_t get_output_port_count() const;
String get_outputs() const;
Vector2 get_size() const;
bool has_input_port(const int64_t id) const;
bool has_output_port(const int64_t id) const;
bool is_valid_port_name(const String name) const;
void remove_input_port(const int64_t id);
void remove_output_port(const int64_t id);
void set_input_port_name(const int64_t id, const String name);
void set_input_port_type(const int64_t id, const int64_t type);
void set_inputs(const String inputs);
void set_output_port_name(const int64_t id, const String name);
void set_output_port_type(const int64_t id, const int64_t type);
void set_outputs(const String outputs);
void set_size(const Vector2 size);
};
}
#endif | 34.758621 | 245 | 0.813823 | jerry871002 |
04cd1733ebf9be34cd2bd02f60a72ceca1b0aee9 | 5,982 | hpp | C++ | core/util/shapes/include/vertexBuffer.hpp | masscry/badbaby | f0b2e793081491ed7598d3170725fe4b48ae1fff | [
"MIT"
] | null | null | null | core/util/shapes/include/vertexBuffer.hpp | masscry/badbaby | f0b2e793081491ed7598d3170725fe4b48ae1fff | [
"MIT"
] | null | null | null | core/util/shapes/include/vertexBuffer.hpp | masscry/badbaby | f0b2e793081491ed7598d3170725fe4b48ae1fff | [
"MIT"
] | null | null | null | /**
* @file vertexBuffer.hpp
*
* Vertex buffer data abstarction
*
*/
#pragma once
#ifndef __BB_CORE_UTIL_VERTEX_BUFFER_HEADER__
#define __BB_CORE_UTIL_VERTEX_BUFFER_HEADER__
#include <deque>
#include <vector>
#include <memory>
#include <cassert>
#include <common.hpp>
#include <camera.hpp>
namespace bb
{
class basicVertexBuffer_t
{
public:
virtual int Append(const basicVertexBuffer_t& src) = 0;
virtual size_t Size() const = 0;
virtual GLint Dimensions() const = 0;
virtual GLenum Type() const = 0;
virtual GLboolean Normalized() const = 0;
virtual const void* Data() const = 0;
virtual ~basicVertexBuffer_t() = 0;
virtual basicVertexBuffer_t* Copy() const = 0;
size_t TypeSize() const;
size_t ByteSize() const;
};
class defaultVertexBuffer_t final: public basicVertexBuffer_t
{
std::unique_ptr<uint8_t[]> data;
size_t size;
GLint dim;
GLenum type;
GLboolean normalized;
int Assign(const basicVertexBuffer_t& src);
public:
int Append(const basicVertexBuffer_t& src) override;
size_t Size() const override;
GLint Dimensions() const override;
GLenum Type() const override;
GLboolean Normalized() const override;
const void* Data() const override;
basicVertexBuffer_t* Copy() const override;
defaultVertexBuffer_t();
defaultVertexBuffer_t(const void* data, size_t size, GLint dim, GLenum type, GLboolean normalized);
defaultVertexBuffer_t(const defaultVertexBuffer_t&);
defaultVertexBuffer_t(defaultVertexBuffer_t&&);
defaultVertexBuffer_t& operator=(const defaultVertexBuffer_t&);
defaultVertexBuffer_t& operator=(defaultVertexBuffer_t&&);
~defaultVertexBuffer_t() override;
};
template<typename data_t>
class vertexBuffer_t final: public basicVertexBuffer_t
{
using array_t = std::vector<data_t>;
array_t self;
GLboolean isNormalized;
public:
vertexBuffer_t(const array_t& copy);
vertexBuffer_t(array_t&& src);
vertexBuffer_t(const vertexBuffer_t<data_t>&) = default;
vertexBuffer_t& operator=(const vertexBuffer_t<data_t>&) = default;
vertexBuffer_t(vertexBuffer_t<data_t>&&) = default;
vertexBuffer_t& operator=(vertexBuffer_t<data_t>&&) = default;
vertexBuffer_t();
array_t& Self();
const array_t& Self() const;
void SetNormalized(GLboolean value);
int Append(const basicVertexBuffer_t& src) override;
size_t Size() const override;
GLint Dimensions() const override;
GLenum Type() const override;
GLboolean Normalized() const override;
const void* Data() const override;
basicVertexBuffer_t* Copy() const override;
~vertexBuffer_t() override;
};
template<typename data_t>
std::unique_ptr<basicVertexBuffer_t> MakeVertexBuffer(std::vector<data_t>&& src)
{
return std::unique_ptr<basicVertexBuffer_t>(new vertexBuffer_t<data_t>(std::move(src)));
}
template<typename data_t, size_t size>
std::unique_ptr<basicVertexBuffer_t> MakeVertexBuffer(const data_t (&data)[size])
{
return std::unique_ptr<basicVertexBuffer_t>(
new vertexBuffer_t<data_t>(
std::vector<data_t>(
data, data + size
)
)
);
}
template<typename data_t>
vertexBuffer_t<data_t>::vertexBuffer_t()
: isNormalized(GL_FALSE)
{
;
}
template<typename data_t>
vertexBuffer_t<data_t>::vertexBuffer_t(const array_t& copy)
: self(copy),
isNormalized(GL_FALSE)
{
;
}
template<typename data_t>
vertexBuffer_t<data_t>::vertexBuffer_t(array_t&& src)
: self(std::move(src)),
isNormalized(GL_FALSE)
{
;
}
template<typename data_t>
vertexBuffer_t<data_t>::~vertexBuffer_t()
{
;
}
template<typename data_t>
inline typename vertexBuffer_t<data_t>::array_t& vertexBuffer_t<data_t>::Self()
{
return this->self;
}
template<typename data_t>
inline const typename vertexBuffer_t<data_t>::array_t& vertexBuffer_t<data_t>::Self() const
{
return this->self;
}
template<typename data_t>
size_t vertexBuffer_t<data_t>::Size() const
{
return this->self.size();
}
template<>
GLint vertexBuffer_t<float>::Dimensions() const;
template<typename data_t>
GLint vertexBuffer_t<data_t>::Dimensions() const
{
static_assert(
std::is_same<typename data_t::value_type, float>::value,
"data_t must contain floats"
);
return sizeof(data_t)/sizeof(float);
}
template<typename data_t>
GLenum vertexBuffer_t<data_t>::Type() const
{
return GL_FLOAT;
}
template<typename data_t>
GLboolean vertexBuffer_t<data_t>::Normalized() const
{
return this->isNormalized;
}
template<typename data_t>
inline void vertexBuffer_t<data_t>::SetNormalized(GLboolean value)
{
this->isNormalized = value;
}
template<typename data_t>
const void* vertexBuffer_t<data_t>::Data() const
{
return this->self.data();
}
template<typename data_t>
basicVertexBuffer_t* vertexBuffer_t<data_t>::Copy() const
{
return new vertexBuffer_t<data_t>(*this);
}
template<typename data_t>
int vertexBuffer_t<data_t>::Append(const basicVertexBuffer_t& src)
{
if (this == &src)
{
// Programmer's error!
bb::Error("Can't append buffer to itself");
assert(0);
return -1;
}
if (
(src.Dimensions() != this->Dimensions())
|| (src.Type() != this->Type())
|| (src.Normalized() != this->Normalized())
)
{
// Programmer's error!
bb::Error("Trying to append vertex buffer of different kind");
assert(0);
return -1;
}
auto itemsToAppend = reinterpret_cast<const data_t*>(src.Data());
size_t itemsSize = src.Size();
this->self.insert(this->self.end(), itemsToAppend, itemsToAppend + itemsSize);
return 0;
}
} // namespace bb
#endif /* __BB_CORE_UTIL_VERTEX_BUFFER_HEADER__ */
| 23.928 | 103 | 0.6777 | masscry |
04d16b8cdeac1782f84f7114760a310930e6cf3a | 4,749 | cpp | C++ | csl/cslbase/dyndemo.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | csl/cslbase/dyndemo.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | csl/cslbase/dyndemo.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | // dyndemo.cpp Copyright (C) 2016-2020, Codemist
//
// This is a test and demonstration of run-time loading of a module
// of code. This is an idea I was pursuing at one stage but am not now!
//
/**************************************************************************
* Copyright (C) 2020, Codemist. A C Norman *
* *
* 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 relevant *
* copyright notice, this list of conditions and the following *
* disclaimer. *
* * Redistributions in binary form must reproduce the above *
* copyright notice, this list of conditions and the following *
* disclaimer in the documentation and/or other materials provided *
* with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* COPYRIGHT OWNERS 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. *
*************************************************************************/
// $Id: dyndemo.cpp 5433 2020-10-15 21:09:02Z arthurcnorman $
#include <cstdio>
#ifdef WIN32
#include <windows.h>
#else
#include <dlfcn.h>
#endif
extern "C"
{ extern int variable_in_base;
extern int function_in_base(int x);
};
int function_in_base(int x)
{ return 314159265*x + 271828459;
}
int variable_in_base = 0x12345678;
//
// So that I can check results I have a copy here of the function
// I put in the loadable module...
//
int clone(int x)
{ return 3*function_in_base(x) + 1;
}
typedef int onearg(int a);
int main(int argc, char *argv[])
{ onearg *b = nullptr;
#ifdef WIN32
HMODULE a = LoadLibrary(".\\dynmodule.dll");
std::printf("Dynamic loading of test code for Windows\na = %p\n",
reinterpret_cast<void *>(a));
std::fflush(stdout);
if (a == 0)
{ DWORD err = GetLastError();
char errbuf[80];
std::printf("Error code %ld = %lx\n", static_cast<long>(err),
static_cast<long>(err));
err = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, err, 0, errbuf, 80, nullptr);
if (err != 0) std::printf("%s", errbuf);
return 0;
}
b = (onearg *)GetProcAddress(a, "callme");
#else
void *a;
std::printf("Dynamic loading test code for *ix, BSD, MacOSX etc\n");
std::fflush(stdout);
a = dlopen("./dynmodule.so", RTLD_NOW | RTLD_GLOBAL);
std::printf("Result of call to dlopen is in 'a'\n");
std::printf("a = %p\n", a);
std::fflush(stdout);
if (a == nullptr)
{ std::printf("Err = <%s>\n", dlerror()); std::fflush(stdout);
return 0;
}
b = (onearg *)dlsym(a, "callme");
#endif
std::printf("The 'callme' entrypoint should now be in b\n");
std::printf("b = %p\n", b);
std::fflush(stdout);
if (b == nullptr) return 0;
std::printf("variable as printed from base = %.8x @ %p\n",
variable_in_base, &variable_in_base);
std::printf("function as printed from base = %p\n",
function_in_base);
//
// The next 2 lines are expected to display the same numeric value.
//
std::printf("b(7) = %x\n", ((onearg *)b)(7));
std::printf("clone(7) = %x\n", clone(7));
std::fflush(stdout);
#ifdef WIN32
FreeLibrary(a);
#else
dlclose(a);
#endif
return 0;
}
// end of dyndemo.cpp
| 38.298387 | 75 | 0.54622 | arthurcnorman |
04d235f350f76303cab24879528777495227a182 | 520 | hpp | C++ | src/engine/systems/ClientNetworkSystem.hpp | arthurchaloin/indie | 84fa7f0864c54e4b35620235ca4e852d7b85fffd | [
"MIT"
] | null | null | null | src/engine/systems/ClientNetworkSystem.hpp | arthurchaloin/indie | 84fa7f0864c54e4b35620235ca4e852d7b85fffd | [
"MIT"
] | null | null | null | src/engine/systems/ClientNetworkSystem.hpp | arthurchaloin/indie | 84fa7f0864c54e4b35620235ca4e852d7b85fffd | [
"MIT"
] | null | null | null | //
// ClientNetworkSystem.hpp
// engine
//
// Created by Arthur Chaloin on 14/05/2018.
//
#pragma once
#include <thread>
#include "engine/core/Scene.hpp"
#include "engine/core/System.hpp"
#include "engine/network/Selector.hpp"
namespace engine {
class ClientNetworkSystem : public System {
public:
explicit ClientNetworkSystem(network::ClientSocket const& socket, Scene::Events& events);
~ClientNetworkSystem();
void update(Scene& scene, float tick) override;
private:
std::thread _netThread;
};
}
| 17.931034 | 91 | 0.726923 | arthurchaloin |
04d311c2524015bb4ce58eb8b23e4b50f7bfda3d | 1,022 | cpp | C++ | tutorial/minimal/MinimalGraphic.cpp | ljwall/er-301 | d6b5f440f3b558fc1b4135bd2de05a7dc93fd1fb | [
"MIT"
] | 102 | 2021-03-01T10:39:56.000Z | 2022-03-31T00:28:15.000Z | tutorial/minimal/MinimalGraphic.cpp | ljwall/er-301 | d6b5f440f3b558fc1b4135bd2de05a7dc93fd1fb | [
"MIT"
] | 62 | 2021-03-01T19:38:54.000Z | 2022-03-21T00:51:24.000Z | tutorial/minimal/MinimalGraphic.cpp | ljwall/er-301 | d6b5f440f3b558fc1b4135bd2de05a7dc93fd1fb | [
"MIT"
] | 19 | 2021-03-01T19:52:10.000Z | 2021-07-29T03:25:19.000Z | #include <MinimalGraphic.h>
#include <math.h>
MinimalGraphic::MinimalGraphic(int left, int bottom, int width, int height) : od::Graphic(left, bottom, width, height)
{
}
MinimalGraphic::~MinimalGraphic()
{
}
void MinimalGraphic::draw(od::FrameBuffer &fb)
{
const int MARGIN = 2;
// The coordinate system.
// (mWorldLeft, mWorldBottom) are the screen coordinates of the (left, bottom) of this graphic.
// (mWidth, mHeight) are the width and height in pixels of this graphic.
// All FrameBuffer methods assume screen coordinates.
// Calculate the radius of a circle that will fit within this graphic's area including a margin.
int radius = MIN(mWidth / 2, mHeight / 2) - MARGIN;
// Calculate the screen coordinates of the center of this graphic.
int centerX = mWorldLeft + mWidth / 2;
int centerY = mWorldBottom + mHeight / 2;
// Draw the outer circular.
// Colors available are: BLACK, GRAY1, ..., GRAY14, WHITE
fb.circle(GRAY5, centerX, centerY, radius);
}
| 31.9375 | 119 | 0.690802 | ljwall |
04d3c2e954b8dbb90c7ebd20f36bd773afe629e6 | 3,637 | cpp | C++ | Assignment 4/TreeNodeDisplay.cpp | chendante/Principles-of-Compilers-Assignments | eb2e33c0bf122ab93ee2a576306cf236c544fa44 | [
"Apache-2.0"
] | 11 | 2019-11-19T16:04:51.000Z | 2021-09-27T12:35:24.000Z | Assignment 4/TreeNodeDisplay.cpp | chendante/Principles-of-Compilers-Assignments | eb2e33c0bf122ab93ee2a576306cf236c544fa44 | [
"Apache-2.0"
] | null | null | null | Assignment 4/TreeNodeDisplay.cpp | chendante/Principles-of-Compilers-Assignments | eb2e33c0bf122ab93ee2a576306cf236c544fa44 | [
"Apache-2.0"
] | 8 | 2019-11-18T01:26:52.000Z | 2020-12-31T12:44:03.000Z | #include "TreeNode.h"
// 展示每个节点
void TreeNode::display()
{
for(int i=0;i<MAXCHILDREN;i++)
{
if(this->children[i] != NULL)
this->children[i]->display();
}
this->printNode();
if(this->sibling != NULL)
{
this->sibling->display();
}
}
void TreeNode::printNode()
{
cout<<this->num<<":\t";
switch(this->nodekind)
{
case StmtK:
this->printStmt();
break;
case ExpK:
this->printExp();
break;
case TypeK:
this->printType();
break;
}
cout<<"Children: ";
for(int i=0;i<MAXCHILDREN;i++)
{
if(this->children[i] != NULL)
cout<<" "<<this->children[i]->num;
}
if(this->sibling !=NULL)
{
cout<<" "<<this->sibling->num;
}
cout<<endl;
}
void TreeNode::printType()
{
cout<<"Type\t\t";
switch(this->type)
{
case Integer:
cout<<"Integer\t";
break;
case Char:
cout<<"Char\t\t";
break;
}
}
void TreeNode::printStmt()
{
string stmt_list[] = {"If Stmt","While Stmt","For Stmt","Assign Stmt","Input Stmt","Output Stmt","Decl Stmt","Stmts"};
cout<<stmt_list[this->kind.stmt]<<"\t\t\t";
}
void TreeNode::printExp()
{
switch(this->kind.expr)
{
case OpK:
cout<<"Expr\t\t";
this->printOp();
break;
case ConstK:
this->printConst();
break;
case IdK:
cout<<"ID\t\t";
this->printId();
break;
}
}
void TreeNode::printOp()
{
switch(this->attr.op)
{
case ADD:
cout<<"OP: +\t\t";
break;
case SUB:
cout<<"OP: -\t\t";
break;
case MUL:
cout<<"OP: *\t\t";
break;
case DIV:
cout<<"OP: /\t\t";
break;
case MOD:
cout<<"OP: %\t\t";
break;
case USUB:
cout<<"OP: -\t\t";
break;
case INC:
cout<<"OP: ++\t\t";
break;
case DEC:
cout<<"OP: --\t\t";
break;
case M_LEFT:
cout<<"OP: <<\t\t";
break;
case M_RIGHT:
cout<<"OP: >>\t\t";
break;
case EQ:
cout<<"OP: ==\t\t";
break;
case GRT:
cout<<"OP: >\t\t";
break;
case LET:
cout<<"OP: <\t\t";
break;
case GRE:
cout<<"OP: >=\t\t";
break;
case LEE:
cout<<"OP: <=\t\t";
break;
case NE:
cout<<"OP: !=\t\t";
break;
case AND:
cout<<"OP: &&\t\t";
break;
case OR:
cout<<"OP: ||\t\t";
break;
case NOT:
cout<<"OP: !\t\t";
break;
case B_AND:
cout<<"OP: &\t\t";
break;
case B_EOR:
cout<<"OP: ^\t\t";
break;
case B_IOR:
cout<<"OP: |\t\t";
break;
case B_OPP:
cout<<"OP: ~\t\t";
break;
}
}
void TreeNode::printId()
{
cout<<string(this->attr.name)<<"\t\t";
}
void TreeNode::printConst()
{
switch(this->type)
{
case Char:
cout<<"Char\t\t";
cout<<this->attr.c_value<<"\t\t";
break;
case Integer:
cout<<"Integer\t\t";
cout<<this->attr.val<<"\t\t";
break;
}
} | 20.432584 | 122 | 0.392081 | chendante |
3e246d100d1b4e8d7cf55610636e73236f693c31 | 2,792 | cpp | C++ | source/QtMultimedia/QMediaGaplessPlaybackControlSlots.cpp | orangesocks/Qt5xHb | 03aa383d9ae86cdadf7289d846018f8a3382a0e4 | [
"MIT"
] | 11 | 2017-01-30T14:19:11.000Z | 2020-05-30T13:39:16.000Z | source/QtMultimedia/QMediaGaplessPlaybackControlSlots.cpp | orangesocks/Qt5xHb | 03aa383d9ae86cdadf7289d846018f8a3382a0e4 | [
"MIT"
] | 1 | 2017-02-24T20:57:32.000Z | 2018-05-29T13:43:05.000Z | source/QtMultimedia/QMediaGaplessPlaybackControlSlots.cpp | orangesocks/Qt5xHb | 03aa383d9ae86cdadf7289d846018f8a3382a0e4 | [
"MIT"
] | 5 | 2017-01-30T14:19:12.000Z | 2020-03-28T08:54:56.000Z | /*
Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QMediaGaplessPlaybackControlSlots.h"
QMediaGaplessPlaybackControlSlots::QMediaGaplessPlaybackControlSlots( QObject *parent ) : QObject( parent )
{
}
QMediaGaplessPlaybackControlSlots::~QMediaGaplessPlaybackControlSlots()
{
}
void QMediaGaplessPlaybackControlSlots::advancedToNextMedia()
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "advancedToNextMedia()" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QMEDIAGAPLESSPLAYBACKCONTROL" );
hb_vmEvalBlockV( cb, 1, psender );
hb_itemRelease( psender );
}
}
void QMediaGaplessPlaybackControlSlots::crossfadeTimeChanged( qreal crossfadeTime )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "crossfadeTimeChanged(qreal)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QMEDIAGAPLESSPLAYBACKCONTROL" );
PHB_ITEM pcrossfadeTime = hb_itemPutND( NULL, crossfadeTime );
hb_vmEvalBlockV( cb, 2, psender, pcrossfadeTime );
hb_itemRelease( psender );
hb_itemRelease( pcrossfadeTime );
}
}
void QMediaGaplessPlaybackControlSlots::nextMediaChanged( const QMediaContent & media )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "nextMediaChanged(QMediaContent)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QMEDIAGAPLESSPLAYBACKCONTROL" );
PHB_ITEM pmedia = Qt5xHb::Signals_return_object( (void *) &media, "QMEDIACONTENT" );
hb_vmEvalBlockV( cb, 2, psender, pmedia );
hb_itemRelease( psender );
hb_itemRelease( pmedia );
}
}
void QMediaGaplessPlaybackControlSlots_connect_signal( const QString & signal, const QString & slot )
{
QMediaGaplessPlaybackControl * obj = (QMediaGaplessPlaybackControl *) Qt5xHb::itemGetPtrStackSelfItem();
if( obj )
{
QMediaGaplessPlaybackControlSlots * s = QCoreApplication::instance()->findChild<QMediaGaplessPlaybackControlSlots *>();
if( s == NULL )
{
s = new QMediaGaplessPlaybackControlSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt5xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
| 28.783505 | 124 | 0.704513 | orangesocks |
3e25a2f8c2a5af35e835fd898be81be6385ce98d | 2,278 | cpp | C++ | code/Fork.cpp | JasonCheeeeen/Fork_and_Shell_in_os | 3aeecef9830f475edc04cb93759a838daf6bedea | [
"MIT"
] | null | null | null | code/Fork.cpp | JasonCheeeeen/Fork_and_Shell_in_os | 3aeecef9830f475edc04cb93759a838daf6bedea | [
"MIT"
] | null | null | null | code/Fork.cpp | JasonCheeeeen/Fork_and_Shell_in_os | 3aeecef9830f475edc04cb93759a838daf6bedea | [
"MIT"
] | null | null | null | #include<iostream>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<ctime>
/*
run in linux to use fork and getpid() to get process ID
pid > 0 -- parent
pid = 0 -- child
pid < 0 -- fail
*/
using namespace std;
void with_control();
void without_control();
int main()
{
srand(time(0));
if(rand()%2 == 0)
{
without_control();
}
else
{
with_control();
}
}
void with_control()
{
int prevent;
pid_t pid;
pid = fork();
if(pid > 0)
{
wait(&prevent);
cout<<"Also, my grandpa's name is "<<getpid()<<"\n";
}
else
{
pid_t pid2 = fork();
if(pid2 > 0)
{
wait(&prevent);
cout<<getpid()<<".\n";
pid_t pid3 = fork();
if(pid3 == 0)
{
cout<<"I have a brother, his name is "<<getpid()<<".\n";
exit(0);
}
else if(pid3 > 0)
{
wait(&prevent);
}
else
{
cout<<"Construct Fail!"<<"\n";
}
}
else if(pid2 == 0)
{
cout<<"I am a child, my name is "<<getpid()<<",\nand My dad's name is ";
exit(0);
}
else
{
cout<<"Construct Fail!"<<"\n";
}
exit(0);
}
}
void without_control()
{
int prevent;
pid_t pid;
pid = fork();
if(pid > 0)
{
sleep(1);
cout<<"Grandpa's name is "<<getpid()<<"\n";
exit(0);
}
else
{
pid_t pid2 = fork();
if(pid2 > 0)
{
sleep(1);
cout<<"Dad's name is "<<getpid()<<".\n";
pid_t pid3 = fork();
if(pid3 == 0)
{
cout<<"Brother's name is "<<getpid()<<".\n";
}
else if(pid3 > 0)
{
sleep(1);
exit(0);
}
else
{
cout<<"Construct Fail!"<<"\n";
}
}
else if(pid2 == 0)
{
cout<<"My name is "<<getpid()<<".\n";
}
else
{
cout<<"Construct Fail!"<<"\n";
}
}
}
| 18.520325 | 84 | 0.37928 | JasonCheeeeen |
3e2872e31e95bc647a5510f013403ebcf8bd3c3e | 480 | cpp | C++ | Numeric Patterns/numericpattern242.cpp | Starkl7/CPlusPlus-PatternHouse | cf53feac9857d0d87981909e0e8daeda26cb02f4 | [
"MIT"
] | 4 | 2021-09-21T03:43:26.000Z | 2022-01-07T03:07:56.000Z | Numeric Patterns/numericpattern242.cpp | Mahak008/CPlusPlus-PatternHouse | cb1af94590acdf8686dcb5a1aec8da646ca180ff | [
"MIT"
] | 916 | 2021-09-01T15:40:24.000Z | 2022-01-10T17:57:59.000Z | Numeric Patterns/numericpattern242.cpp | Mahak008/CPlusPlus-PatternHouse | cb1af94590acdf8686dcb5a1aec8da646ca180ff | [
"MIT"
] | 20 | 2021-09-30T18:13:58.000Z | 2022-01-06T09:55:36.000Z | #include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if (i==n){
cout<<j<<" ";
}
else if(j==1 || j==i){
cout<<j<<" ";
}
else {
cout<<" ";
}
}
cout<<endl;
}
}
// Sample Input :- 5
// Output :-
// 1
// 1 2
// 1 3
// 1 4
// 1 2 3 4 5
| 15.483871 | 38 | 0.289583 | Starkl7 |
3e2caf4e192a100c65e3348371e1afebad406cf9 | 15,692 | hpp | C++ | include/ginkgo/core/matrix/fbcsr.hpp | lksriemer/ginkgo | 00a4f67054d73689f07276cc50fb4adc302633fa | [
"BSD-3-Clause"
] | 234 | 2018-01-12T10:12:31.000Z | 2022-03-31T16:27:13.000Z | include/ginkgo/core/matrix/fbcsr.hpp | kho19/ginkgo | cb17428bd2381a15d6c01cac42fa1e7016891239 | [
"BSD-3-Clause"
] | 862 | 2018-02-07T15:07:35.000Z | 2022-03-31T13:00:30.000Z | include/ginkgo/core/matrix/fbcsr.hpp | kho19/ginkgo | cb17428bd2381a15d6c01cac42fa1e7016891239 | [
"BSD-3-Clause"
] | 62 | 2018-01-24T07:58:11.000Z | 2022-03-20T11:49:00.000Z | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2021, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#ifndef GKO_PUBLIC_CORE_MATRIX_FBCSR_HPP_
#define GKO_PUBLIC_CORE_MATRIX_FBCSR_HPP_
#include <ginkgo/core/base/array.hpp>
#include <ginkgo/core/base/lin_op.hpp>
#include <ginkgo/core/base/math.hpp>
namespace gko {
namespace matrix {
template <typename ValueType>
class Dense;
template <typename ValueType, typename IndexType>
class Csr;
template <typename ValueType, typename IndexType>
class SparsityCsr;
template <typename ValueType, typename IndexType>
class Fbcsr;
template <typename ValueType, typename IndexType>
class FbcsrBuilder;
namespace detail {
/**
* Computes the number of blocks in some array of given size
*
* @param block_size The size of each block
* @param size The total size of some array/vector
* @return The number of blocks, ie.,
* quotient of the size divided by the block size.
*
* @throw BlockSizeError when block_size does not divide the total size.
*/
template <typename IndexType>
inline IndexType get_num_blocks(const int block_size, const IndexType size)
{
GKO_ASSERT_BLOCK_SIZE_CONFORMANT(size, block_size);
return size / block_size;
}
} // namespace detail
/**
* @brief Fixed-block compressed sparse row storage matrix format
*
* FBCSR is a matrix format meant for matrices having a natural block structure
* made up of small, dense, disjoint blocks. It is similar to CSR \sa Csr.
* However, unlike Csr, each non-zero location stores a small dense block of
* entries having a constant size. This reduces the number of integers that need
* to be stored in order to refer to a given non-zero entry, and enables
* efficient implementation of certain block methods.
*
* The block size is expected to be known in advance and passed to the
* constructor.
*
* @note The total number of rows and the number of columns are expected to be
* divisible by the block size.
*
* The nonzero elements are stored in a 1D array row-wise, and accompanied
* with a row pointer array which stores the starting index of each block-row.
* An additional block-column index array is used to identify the block-column
* of each nonzero block.
*
* The Fbcsr LinOp supports different operations:
*
* ```cpp
* matrix::Fbcsr *A, *B, *C; // matrices
* matrix::Dense *b, *x; // vectors tall-and-skinny matrices
* matrix::Dense *alpha, *beta; // scalars of dimension 1x1
*
* // Applying to Dense matrices computes an SpMV/SpMM product
* A->apply(b, x) // x = A*b
* A->apply(alpha, b, beta, x) // x = alpha*A*b + beta*x
* ```
*
* @tparam ValueType precision of matrix elements
* @tparam IndexType precision of matrix indexes
*
* @ingroup fbcsr
* @ingroup mat_formats
* @ingroup LinOp
*/
template <typename ValueType = default_precision, typename IndexType = int32>
class Fbcsr : public EnableLinOp<Fbcsr<ValueType, IndexType>>,
public EnableCreateMethod<Fbcsr<ValueType, IndexType>>,
public ConvertibleTo<Fbcsr<next_precision<ValueType>, IndexType>>,
public ConvertibleTo<Dense<ValueType>>,
public ConvertibleTo<Csr<ValueType, IndexType>>,
public ConvertibleTo<SparsityCsr<ValueType, IndexType>>,
public DiagonalExtractable<ValueType>,
public ReadableFromMatrixData<ValueType, IndexType>,
public WritableToMatrixData<ValueType, IndexType>,
public Transposable,
public EnableAbsoluteComputation<
remove_complex<Fbcsr<ValueType, IndexType>>> {
friend class EnableCreateMethod<Fbcsr>;
friend class EnablePolymorphicObject<Fbcsr, LinOp>;
friend class Dense<ValueType>;
friend class SparsityCsr<ValueType, IndexType>;
friend class FbcsrBuilder<ValueType, IndexType>;
friend class Fbcsr<to_complex<ValueType>, IndexType>;
public:
using value_type = ValueType;
using index_type = IndexType;
using transposed_type = Fbcsr<ValueType, IndexType>;
using mat_data = matrix_data<ValueType, IndexType>;
using device_mat_data = device_matrix_data<ValueType, IndexType>;
using absolute_type = remove_complex<Fbcsr>;
/**
* For moving to another Fbcsr of the same type, use the default
* implementation provided by EnableLinOp via the
* EnablePolymorphicAssignment mixin.
*/
using EnableLinOp<Fbcsr<ValueType, IndexType>>::move_to;
/**
* For converting (copying) to another Fbcsr of the same type,
* use the default implementation provided by EnableLinOp.
*/
using EnableLinOp<Fbcsr<ValueType, IndexType>>::convert_to;
friend class Fbcsr<next_precision<ValueType>, IndexType>;
void convert_to(
Fbcsr<next_precision<ValueType>, IndexType>* result) const override;
void move_to(Fbcsr<next_precision<ValueType>, IndexType>* result) override;
void convert_to(Dense<ValueType>* other) const override;
void move_to(Dense<ValueType>* other) override;
/**
* Converts the matrix to CSR format
*
* @note Any explicit zeros in the original matrix are retained
* in the converted result.
*/
void convert_to(Csr<ValueType, IndexType>* result) const override;
void move_to(Csr<ValueType, IndexType>* result) override;
/**
* Get the block sparsity pattern in CSR-like format
*
* @note The actual non-zero values are never copied;
* the result always has a value array of size 1 with the value 1.
*/
void convert_to(SparsityCsr<ValueType, IndexType>* result) const override;
void move_to(SparsityCsr<ValueType, IndexType>* result) override;
/**
* Reads a @ref matrix_data into Fbcsr format.
* Requires the block size to be set beforehand @sa set_block_size.
*
* @warning Unlike Csr::read, here explicit non-zeros are NOT dropped.
*/
void read(const mat_data& data) override;
void read(const device_mat_data& data) override;
void write(mat_data& data) const override;
std::unique_ptr<LinOp> transpose() const override;
std::unique_ptr<LinOp> conj_transpose() const override;
std::unique_ptr<Diagonal<ValueType>> extract_diagonal() const override;
std::unique_ptr<absolute_type> compute_absolute() const override;
void compute_absolute_inplace() override;
/**
* Sorts the values blocks and block-column indices in each row
* by column index
*/
void sort_by_column_index();
/**
* Tests if all row entry pairs (value, col_idx) are sorted by column index
*
* @returns True if all row entry pairs (value, col_idx) are sorted by
* column index
*/
bool is_sorted_by_column_index() const;
/**
* @return The values of the matrix.
*/
value_type* get_values() noexcept { return values_.get_data(); }
/**
* @copydoc Fbcsr::get_values()
*
* @note This is the constant version of the function, which can be
* significantly more memory efficient than the non-constant version,
* so always prefer this version.
*/
const value_type* get_const_values() const noexcept
{
return values_.get_const_data();
}
/**
* @return The column indexes of the matrix.
*/
index_type* get_col_idxs() noexcept { return col_idxs_.get_data(); }
/**
* @copydoc Fbcsr::get_col_idxs()
*
* @note This is the constant version of the function, which can be
* significantly more memory efficient than the non-constant version,
* so always prefer this version.
*/
const index_type* get_const_col_idxs() const noexcept
{
return col_idxs_.get_const_data();
}
/**
* @return The row pointers of the matrix.
*/
index_type* get_row_ptrs() noexcept { return row_ptrs_.get_data(); }
/**
* @copydoc Fbcsr::get_row_ptrs()
*
* @note This is the constant version of the function, which can be
* significantly more memory efficient than the non-constant version,
* so always prefer this version.
*/
const index_type* get_const_row_ptrs() const noexcept
{
return row_ptrs_.get_const_data();
}
/**
* @return The number of elements explicitly stored in the matrix
*/
size_type get_num_stored_elements() const noexcept
{
return values_.get_num_elems();
}
/**
* @return The number of non-zero blocks explicitly stored in the matrix
*/
size_type get_num_stored_blocks() const noexcept
{
return col_idxs_.get_num_elems();
}
/**
* @return The fixed block size for this matrix
*/
int get_block_size() const noexcept { return bs_; }
/**
* @return The number of block-rows in the matrix
*/
index_type get_num_block_rows() const noexcept
{
return this->get_size()[0] / bs_;
}
/**
* @return The number of block-columns in the matrix
*/
index_type get_num_block_cols() const noexcept
{
return this->get_size()[1] / bs_;
}
/**
* Creates a constant (immutable) Fbcsr matrix from a constant array.
*
* @param exec the executor to create the matrix on
* @param size the dimensions of the matrix
* @param blocksize the block size of the matrix
* @param values the value array of the matrix
* @param col_idxs the block column index array of the matrix
* @param row_ptrs the block row pointer array of the matrix
* @returns A smart pointer to the constant matrix wrapping the input arrays
* (if they reside on the same executor as the matrix) or a copy of
* the arrays on the correct executor.
*/
static std::unique_ptr<const Fbcsr> create_const(
std::shared_ptr<const Executor> exec, const dim<2>& size, int blocksize,
gko::detail::ConstArrayView<ValueType>&& values,
gko::detail::ConstArrayView<IndexType>&& col_idxs,
gko::detail::ConstArrayView<IndexType>&& row_ptrs)
{
// cast const-ness away, but return a const object afterwards,
// so we can ensure that no modifications take place.
return std::unique_ptr<const Fbcsr>(
new Fbcsr{exec, size, blocksize,
gko::detail::array_const_cast(std::move(values)),
gko::detail::array_const_cast(std::move(col_idxs)),
gko::detail::array_const_cast(std::move(row_ptrs))});
}
protected:
/**
* Creates an uninitialized FBCSR matrix with the given block size.
*
* @param exec Executor associated to the matrix
* @param block_size The desired size of the dense square nonzero blocks;
* defaults to 1.
*/
Fbcsr(std::shared_ptr<const Executor> exec, int block_size = 1)
: Fbcsr(std::move(exec), dim<2>{}, {}, block_size)
{}
/**
* Creates an uninitialized FBCSR matrix of the specified size.
*
* @param exec Executor associated to the matrix
* @param size size of the matrix
* @param num_nonzeros number of stored nonzeros. It needs to be a multiple
* of block_size * block_size.
* @param block_size size of the small dense square blocks
*/
Fbcsr(std::shared_ptr<const Executor> exec, const dim<2>& size,
size_type num_nonzeros, int block_size)
: EnableLinOp<Fbcsr>(exec, size),
bs_{block_size},
values_(exec, num_nonzeros),
col_idxs_(exec, detail::get_num_blocks(block_size * block_size,
num_nonzeros)),
row_ptrs_(exec, detail::get_num_blocks(block_size, size[0]) + 1)
{
GKO_ASSERT_BLOCK_SIZE_CONFORMANT(size[1], bs_);
}
/**
* Creates a FBCSR matrix from already allocated (and initialized) row
* pointer, column index and value arrays.
*
* @tparam ValuesArray type of `values` array
* @tparam ColIdxsArray type of `col_idxs` array
* @tparam RowPtrsArray type of `row_ptrs` array
*
* @param exec Executor associated to the matrix
* @param size size of the matrix
* @param block_size Size of the small square dense nonzero blocks
* @param values array of matrix values
* @param col_idxs array of column indexes
* @param row_ptrs array of row pointers
*
* @note If one of `row_ptrs`, `col_idxs` or `values` is not an rvalue, not
* an array of IndexType, IndexType and ValueType, respectively, or
* is on the wrong executor, an internal copy of that array will be
* created, and the original array data will not be used in the
* matrix.
*/
template <typename ValuesArray, typename ColIdxsArray,
typename RowPtrsArray>
Fbcsr(std::shared_ptr<const Executor> exec, const dim<2>& size,
int block_size, ValuesArray&& values, ColIdxsArray&& col_idxs,
RowPtrsArray&& row_ptrs)
: EnableLinOp<Fbcsr>(exec, size),
bs_{block_size},
values_{exec, std::forward<ValuesArray>(values)},
col_idxs_{exec, std::forward<ColIdxsArray>(col_idxs)},
row_ptrs_{exec, std::forward<RowPtrsArray>(row_ptrs)}
{
GKO_ASSERT_EQ(values_.get_num_elems(),
col_idxs_.get_num_elems() * bs_ * bs_);
GKO_ASSERT_EQ(this->get_size()[0] / bs_ + 1, row_ptrs_.get_num_elems());
}
void apply_impl(const LinOp* b, LinOp* x) const override;
void apply_impl(const LinOp* alpha, const LinOp* b, const LinOp* beta,
LinOp* x) const override;
private:
int bs_; ///< Block size
Array<value_type> values_; ///< Non-zero values of all blocks
Array<index_type> col_idxs_; ///< Block-column indices of all blocks
Array<index_type> row_ptrs_; ///< Block-row pointers into @ref col_idxs_
};
} // namespace matrix
} // namespace gko
#endif // GKO_PUBLIC_CORE_MATRIX_FBCSR_HPP_
| 35.826484 | 80 | 0.672572 | lksriemer |
3e2d2aa00597cd96aa6bcf0e1adc54db26a6d4b1 | 2,255 | cpp | C++ | GStreamerStatic.cpp | ashley-b/PothosGStreamer | c29ecb227f67a367a796f6c8918d5818d70ee309 | [
"BSL-1.0"
] | 2 | 2018-03-30T17:45:30.000Z | 2018-08-09T01:57:07.000Z | GStreamerStatic.cpp | ashley-b/PothosGStreamer | c29ecb227f67a367a796f6c8918d5818d70ee309 | [
"BSL-1.0"
] | null | null | null | GStreamerStatic.cpp | ashley-b/PothosGStreamer | c29ecb227f67a367a796f6c8918d5818d70ee309 | [
"BSL-1.0"
] | null | null | null | /// Copyright (c) 2017-2018 Ashley Brighthope
/// SPDX-License-Identifier: BSL-1.0
#include "GStreamerStatic.hpp"
#include "GStreamerTypes.hpp"
#include <gst/gst.h>
namespace {
struct GStreamerStatic
{
GstTypes::GErrorPtr initError;
GStreamerStatic(const GStreamerStatic &) = delete;
GStreamerStatic& operator=(const GStreamerStatic &) = delete;
GStreamerStatic(GStreamerStatic &&) = delete;
GStreamerStatic& operator=(GStreamerStatic &&) = delete;
GStreamerStatic() :
initError( )
{
if ( GstTypes::debug_extra )
{
poco_information(GstTypes::logger(), "GStreamerStatic::GStreamerStatic() - gst_is_initialized() = " + GstTypes::boolToString( gst_is_initialized() ) );
}
// gst_segtrap_set_enabled(FALSE);
// Run GStreamer registry update in this thread
gst_registry_fork_set_enabled( FALSE );
if ( gst_init_check( nullptr, nullptr, GstTypes::uniqueOutArg( initError ) ) == FALSE )
{
poco_error( GstTypes::logger(), "GStreamerStatic::GStreamerStatic(): gst_init_check error: " + GstTypes::gerrorToString( initError.get() ) );
}
if ( GstTypes::debug_extra )
{
poco_information( GstTypes::logger(), "GStreamer version: " + GstStatic::getVersion() );
}
}
~GStreamerStatic()
{
if ( GstTypes::debug_extra )
{
poco_information(GstTypes::logger(), "GStreamerStatic::~GStreamerStatic() - gst_is_initialized() = " + GstTypes::boolToString( gst_is_initialized() ) );
}
// Only deinit GStreamer if it was initialized
if ( gst_is_initialized() == TRUE )
{
gst_deinit();
}
}
}; // struct GStreamerStatic
} // namespace
static GStreamerStatic gstreamerStatic;
namespace GstStatic
{
GError* getInitError()
{
return gstreamerStatic.initError.get();
}
std::string getVersion()
{
return GstTypes::gcharToString( GstTypes::GCharPtr( gst_version_string() ).get() ).value();
}
} // namespace GstStatic
| 30.890411 | 168 | 0.590244 | ashley-b |
3e2f44c85ad3075a1028e1763cf6ecaa8793e5f4 | 23,339 | cpp | C++ | Kits/DirectXTex/DirectXTexXboxDDS.cpp | dephora/Xbox-ATG-Samples | 31e482c9e23def36073542ce614a0f0b145d7112 | [
"MIT"
] | 1 | 2020-12-13T15:58:44.000Z | 2020-12-13T15:58:44.000Z | Kits/DirectXTex/DirectXTexXboxDDS.cpp | dephora/Xbox-ATG-Samples | 31e482c9e23def36073542ce614a0f0b145d7112 | [
"MIT"
] | null | null | null | Kits/DirectXTex/DirectXTexXboxDDS.cpp | dephora/Xbox-ATG-Samples | 31e482c9e23def36073542ce614a0f0b145d7112 | [
"MIT"
] | 1 | 2020-07-30T11:13:23.000Z | 2020-07-30T11:13:23.000Z | //--------------------------------------------------------------------------------------
// File: DirectXTexXboxDDS.cpp
//
// DirectXTex Auxillary functions for saving "XBOX" Xbox One variants of DDS files
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//--------------------------------------------------------------------------------------
#include "DirectXTexP.h"
#include "DirectXTexXbox.h"
#include "DDS.h"
#include "xdk.h"
using namespace DirectX;
using namespace Xbox;
namespace
{
const DDS_PIXELFORMAT DDSPF_XBOX =
{ sizeof(DDS_PIXELFORMAT), DDS_FOURCC, MAKEFOURCC('X','B','O','X'), 0, 0, 0, 0, 0 };
#pragma pack(push,1)
struct DDS_HEADER_XBOX
// Must match structure in XboxDDSTextureLoader module
{
DXGI_FORMAT dxgiFormat;
uint32_t resourceDimension;
uint32_t miscFlag; // see DDS_RESOURCE_MISC_FLAG
uint32_t arraySize;
uint32_t miscFlags2; // see DDS_MISC_FLAGS2
uint32_t tileMode; // see XG_TILE_MODE
uint32_t baseAlignment;
uint32_t dataSize;
uint32_t xdkVer; // matching _XDK_VER
};
#pragma pack(pop)
static_assert(sizeof(DDS_HEADER_XBOX) == 36, "DDS XBOX Header size mismatch");
static_assert(sizeof(DDS_HEADER_XBOX) >= sizeof(DDS_HEADER_DXT10), "DDS XBOX Header should be larger than DX10 header");
static const size_t XBOX_HEADER_SIZE = sizeof(uint32_t) + sizeof(DDS_HEADER) + sizeof(DDS_HEADER_XBOX);
//-------------------------------------------------------------------------------------
// Decodes DDS header using XBOX extended header (variant of DX10 header)
//-------------------------------------------------------------------------------------
HRESULT DecodeDDSHeader(
_In_reads_bytes_(size) const void* pSource,
size_t size,
DirectX::TexMetadata& metadata,
_Out_opt_ XboxTileMode* tmode,
_Out_opt_ uint32_t* dataSize,
_Out_opt_ uint32_t* baseAlignment)
{
if (!pSource)
return E_INVALIDARG;
if (tmode)
*tmode = c_XboxTileModeInvalid;
if (dataSize)
*dataSize = 0;
if (baseAlignment)
*baseAlignment = 0;
memset(&metadata, 0, sizeof(TexMetadata));
if (size < (sizeof(DDS_HEADER) + sizeof(uint32_t)))
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
// DDS files always start with the same magic number ("DDS ")
uint32_t dwMagicNumber = *reinterpret_cast<const uint32_t*>(pSource);
if (dwMagicNumber != DDS_MAGIC)
{
return E_FAIL;
}
auto pHeader = reinterpret_cast<const DDS_HEADER*>(reinterpret_cast<const uint8_t*>(pSource) + sizeof(uint32_t));
// Verify header to validate DDS file
if (pHeader->size != sizeof(DDS_HEADER)
|| pHeader->ddspf.size != sizeof(DDS_PIXELFORMAT))
{
return E_FAIL;
}
metadata.mipLevels = pHeader->mipMapCount;
if (metadata.mipLevels == 0)
metadata.mipLevels = 1;
// Check for XBOX extension
if (!(pHeader->ddspf.flags & DDS_FOURCC)
|| (MAKEFOURCC('X', 'B', 'O', 'X') != pHeader->ddspf.fourCC))
{
// We know it's a DDS file, but it's not an XBOX extension
return S_FALSE;
}
// Buffer must be big enough for both headers and magic value
if (size < XBOX_HEADER_SIZE)
{
return E_FAIL;
}
auto xboxext = reinterpret_cast<const DDS_HEADER_XBOX*>(
reinterpret_cast<const uint8_t*>(pSource) + sizeof(uint32_t) + sizeof(DDS_HEADER));
if (xboxext->xdkVer < _XDK_VER)
{
OutputDebugStringA("WARNING: DDS XBOX file may be outdated and need regeneration\n");
}
metadata.arraySize = xboxext->arraySize;
if (metadata.arraySize == 0)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
metadata.format = xboxext->dxgiFormat;
if (!IsValid(metadata.format))
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
static_assert(static_cast<int>(TEX_MISC_TEXTURECUBE) == static_cast<int>(DDS_RESOURCE_MISC_TEXTURECUBE), "DDS header mismatch");
metadata.miscFlags = xboxext->miscFlag & ~static_cast<uint32_t>(TEX_MISC_TEXTURECUBE);
switch (xboxext->resourceDimension)
{
case DDS_DIMENSION_TEXTURE1D:
if ((pHeader->flags & DDS_HEIGHT) && pHeader->height != 1)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
metadata.width = pHeader->width;
metadata.height = 1;
metadata.depth = 1;
metadata.dimension = TEX_DIMENSION_TEXTURE1D;
break;
case DDS_DIMENSION_TEXTURE2D:
if (xboxext->miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE)
{
metadata.miscFlags |= TEX_MISC_TEXTURECUBE;
metadata.arraySize *= 6;
}
metadata.width = pHeader->width;
metadata.height = pHeader->height;
metadata.depth = 1;
metadata.dimension = TEX_DIMENSION_TEXTURE2D;
break;
case DDS_DIMENSION_TEXTURE3D:
if (!(pHeader->flags & DDS_HEADER_FLAGS_VOLUME))
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
if (metadata.arraySize > 1)
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
metadata.width = pHeader->width;
metadata.height = pHeader->height;
metadata.depth = pHeader->depth;
metadata.dimension = TEX_DIMENSION_TEXTURE3D;
break;
default:
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
if (static_cast<XboxTileMode>(xboxext->tileMode) == c_XboxTileModeInvalid)
{
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
static_assert(static_cast<int>(TEX_MISC2_ALPHA_MODE_MASK) == static_cast<int>(DDS_MISC_FLAGS2_ALPHA_MODE_MASK), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_UNKNOWN) == static_cast<int>(DDS_ALPHA_MODE_UNKNOWN), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_STRAIGHT) == static_cast<int>(DDS_ALPHA_MODE_STRAIGHT), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_PREMULTIPLIED) == static_cast<int>(DDS_ALPHA_MODE_PREMULTIPLIED), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_OPAQUE) == static_cast<int>(DDS_ALPHA_MODE_OPAQUE), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_CUSTOM) == static_cast<int>(DDS_ALPHA_MODE_CUSTOM), "DDS header mismatch");
metadata.miscFlags2 = xboxext->miscFlags2;
if (tmode)
*tmode = static_cast<XboxTileMode>(xboxext->tileMode);
if (baseAlignment)
*baseAlignment = xboxext->baseAlignment;
if (dataSize)
*dataSize = xboxext->dataSize;
return S_OK;
}
//-------------------------------------------------------------------------------------
// Encodes DDS file header (magic value, header, XBOX extended header)
//-------------------------------------------------------------------------------------
HRESULT EncodeDDSHeader(
const XboxImage& xbox,
_Out_writes_(maxsize) void* pDestination,
size_t maxsize)
{
if (!pDestination)
return E_POINTER;
if (maxsize < XBOX_HEADER_SIZE)
return E_NOT_SUFFICIENT_BUFFER;
*reinterpret_cast<uint32_t*>(pDestination) = DDS_MAGIC;
auto header = reinterpret_cast<DDS_HEADER*>(reinterpret_cast<uint8_t*>(pDestination) + sizeof(uint32_t));
memset(header, 0, sizeof(DDS_HEADER));
header->size = sizeof(DDS_HEADER);
header->flags = DDS_HEADER_FLAGS_TEXTURE;
header->caps = DDS_SURFACE_FLAGS_TEXTURE;
auto& metadata = xbox.GetMetadata();
if (metadata.mipLevels > 0)
{
header->flags |= DDS_HEADER_FLAGS_MIPMAP;
if (metadata.mipLevels > UINT32_MAX)
return E_INVALIDARG;
header->mipMapCount = static_cast<uint32_t>(metadata.mipLevels);
if (header->mipMapCount > 1)
header->caps |= DDS_SURFACE_FLAGS_MIPMAP;
}
switch (metadata.dimension)
{
case TEX_DIMENSION_TEXTURE1D:
if (metadata.width > UINT32_MAX)
return E_INVALIDARG;
header->width = static_cast<uint32_t>(metadata.width);
header->height = header->depth = 1;
break;
case TEX_DIMENSION_TEXTURE2D:
if (metadata.height > UINT32_MAX
|| metadata.width > UINT32_MAX)
return E_INVALIDARG;
header->height = static_cast<uint32_t>(metadata.height);
header->width = static_cast<uint32_t>(metadata.width);
header->depth = 1;
if (metadata.IsCubemap())
{
header->caps |= DDS_SURFACE_FLAGS_CUBEMAP;
header->caps2 |= DDS_CUBEMAP_ALLFACES;
}
break;
case TEX_DIMENSION_TEXTURE3D:
if (metadata.height > UINT32_MAX
|| metadata.width > UINT32_MAX
|| metadata.depth > UINT32_MAX)
return E_INVALIDARG;
header->flags |= DDS_HEADER_FLAGS_VOLUME;
header->caps2 |= DDS_FLAGS_VOLUME;
header->height = static_cast<uint32_t>(metadata.height);
header->width = static_cast<uint32_t>(metadata.width);
header->depth = static_cast<uint32_t>(metadata.depth);
break;
default:
return E_FAIL;
}
size_t rowPitch, slicePitch;
ComputePitch(metadata.format, metadata.width, metadata.height, rowPitch, slicePitch, CP_FLAGS_NONE);
if (slicePitch > UINT32_MAX
|| rowPitch > UINT32_MAX)
return E_FAIL;
if (IsCompressed(metadata.format))
{
header->flags |= DDS_HEADER_FLAGS_LINEARSIZE;
header->pitchOrLinearSize = static_cast<uint32_t>(slicePitch);
}
else
{
header->flags |= DDS_HEADER_FLAGS_PITCH;
header->pitchOrLinearSize = static_cast<uint32_t>(rowPitch);
}
memcpy_s(&header->ddspf, sizeof(header->ddspf), &DDSPF_XBOX, sizeof(DDS_PIXELFORMAT));
// Setup XBOX extended header
auto xboxext = reinterpret_cast<DDS_HEADER_XBOX*>(reinterpret_cast<uint8_t*>(header) + sizeof(DDS_HEADER));
memset(xboxext, 0, sizeof(DDS_HEADER_XBOX));
xboxext->dxgiFormat = metadata.format;
xboxext->resourceDimension = metadata.dimension;
if (metadata.arraySize > UINT32_MAX)
return E_INVALIDARG;
static_assert(static_cast<int>(TEX_MISC_TEXTURECUBE) == static_cast<int>(DDS_RESOURCE_MISC_TEXTURECUBE), "DDS header mismatch");
xboxext->miscFlag = metadata.miscFlags & ~static_cast<uint32_t>(TEX_MISC_TEXTURECUBE);
if (metadata.miscFlags & TEX_MISC_TEXTURECUBE)
{
xboxext->miscFlag |= TEX_MISC_TEXTURECUBE;
assert((metadata.arraySize % 6) == 0);
xboxext->arraySize = static_cast<UINT>(metadata.arraySize / 6);
}
else
{
xboxext->arraySize = static_cast<UINT>(metadata.arraySize);
}
static_assert(static_cast<int>(TEX_MISC2_ALPHA_MODE_MASK) == static_cast<int>(DDS_MISC_FLAGS2_ALPHA_MODE_MASK), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_UNKNOWN) == static_cast<int>(DDS_ALPHA_MODE_UNKNOWN), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_STRAIGHT) == static_cast<int>(DDS_ALPHA_MODE_STRAIGHT), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_PREMULTIPLIED) == static_cast<int>(DDS_ALPHA_MODE_PREMULTIPLIED), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_OPAQUE) == static_cast<int>(DDS_ALPHA_MODE_OPAQUE), "DDS header mismatch");
static_assert(static_cast<int>(TEX_ALPHA_MODE_CUSTOM) == static_cast<int>(DDS_ALPHA_MODE_CUSTOM), "DDS header mismatch");
xboxext->miscFlags2 = metadata.miscFlags2;
xboxext->tileMode = static_cast<uint32_t>(xbox.GetTileMode());
xboxext->baseAlignment = xbox.GetAlignment();
xboxext->dataSize = xbox.GetSize();
xboxext->xdkVer = _XDK_VER;
return S_OK;
}
}
//=====================================================================================
// Entry-points
//=====================================================================================
//-------------------------------------------------------------------------------------
// Obtain metadata from DDS file in memory/on disk
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT Xbox::GetMetadataFromDDSMemory(
const void* pSource,
size_t size,
TexMetadata& metadata,
bool& isXbox)
{
if (!pSource || !size)
return E_INVALIDARG;
isXbox = false;
HRESULT hr = DecodeDDSHeader(pSource, size, metadata, nullptr, nullptr, nullptr);
if (hr == S_FALSE)
{
hr = DirectX::GetMetadataFromDDSMemory(pSource, size, DirectX::DDS_FLAGS_NONE, metadata);
}
else if (SUCCEEDED(hr))
{
isXbox = true;
}
return hr;
}
_Use_decl_annotations_
HRESULT Xbox::GetMetadataFromDDSFile(
const wchar_t* szFile,
TexMetadata& metadata,
bool& isXbox)
{
if (!szFile)
return E_INVALIDARG;
isXbox = false;
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr)));
#else
ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, nullptr)));
#endif
if (!hFile)
{
return HRESULT_FROM_WIN32(GetLastError());
}
// Get the file size
FILE_STANDARD_INFO fileInfo;
if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo)))
{
return HRESULT_FROM_WIN32(GetLastError());
}
// File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid DDS file)
if (fileInfo.EndOfFile.HighPart > 0)
{
return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
}
// Need at least enough data to fill the standard header and magic number to be a valid DDS
if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t)))
{
return E_FAIL;
}
// Read the header in (including extended header if present)
uint8_t header[XBOX_HEADER_SIZE];
DWORD bytesRead = 0;
if (!ReadFile(hFile.get(), header, XBOX_HEADER_SIZE, &bytesRead, nullptr))
{
return HRESULT_FROM_WIN32(GetLastError());
}
HRESULT hr = DecodeDDSHeader(header, bytesRead, metadata, nullptr, nullptr, nullptr);
if (hr == S_FALSE)
{
hr = DirectX::GetMetadataFromDDSMemory(header, bytesRead, DirectX::DDS_FLAGS_NONE, metadata);
}
else if (SUCCEEDED(hr))
{
isXbox = true;
}
return hr;
}
//-------------------------------------------------------------------------------------
// Load a DDS file in memory
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT Xbox::LoadFromDDSMemory(
const void* pSource,
size_t size,
TexMetadata* metadata,
XboxImage& xbox)
{
if (!pSource || !size)
return E_INVALIDARG;
xbox.Release();
TexMetadata mdata;
uint32_t dataSize;
uint32_t baseAlignment;
XboxTileMode tmode;
HRESULT hr = DecodeDDSHeader(pSource, size, mdata, &tmode, &dataSize, &baseAlignment);
if (hr == S_FALSE)
{
// It's a DDS, but not an XBOX variant
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
if (FAILED(hr))
{
return hr;
}
if (!dataSize || !baseAlignment)
{
return E_FAIL;
}
if (size <= XBOX_HEADER_SIZE)
{
return E_FAIL;
}
// Copy tiled data
size_t remaining = size - XBOX_HEADER_SIZE;
if (remaining < dataSize)
{
return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
}
hr = xbox.Initialize(mdata, tmode, dataSize, baseAlignment);
if (FAILED(hr))
return hr;
assert(xbox.GetPointer() != nullptr);
memcpy(xbox.GetPointer(), reinterpret_cast<const uint8_t*>(pSource) + XBOX_HEADER_SIZE, dataSize);
if (metadata)
memcpy(metadata, &mdata, sizeof(TexMetadata));
return S_OK;
}
//-------------------------------------------------------------------------------------
// Load a DDS file from disk
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT Xbox::LoadFromDDSFile(
const wchar_t* szFile,
TexMetadata* metadata,
XboxImage& xbox)
{
if (!szFile)
return E_INVALIDARG;
xbox.Release();
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr)));
#else
ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, nullptr)));
#endif
if (!hFile)
{
return HRESULT_FROM_WIN32(GetLastError());
}
// Get the file size
FILE_STANDARD_INFO fileInfo;
if (!GetFileInformationByHandleEx(hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo)))
{
return HRESULT_FROM_WIN32(GetLastError());
}
// File is too big for 32-bit allocation, so reject read (4 GB should be plenty large enough for a valid DDS file)
if (fileInfo.EndOfFile.HighPart > 0)
{
return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
}
// Need at least enough data to fill the standard header and magic number to be a valid DDS
if (fileInfo.EndOfFile.LowPart < (sizeof(DDS_HEADER) + sizeof(uint32_t)))
{
return E_FAIL;
}
// Read the header in (including extended header if present)
uint8_t header[XBOX_HEADER_SIZE];
DWORD bytesRead = 0;
if (!ReadFile(hFile.get(), header, XBOX_HEADER_SIZE, &bytesRead, nullptr))
{
return HRESULT_FROM_WIN32(GetLastError());
}
TexMetadata mdata;
XboxTileMode tmode;
uint32_t dataSize;
uint32_t baseAlignment;
HRESULT hr = DecodeDDSHeader(header, bytesRead, mdata, &tmode, &dataSize, &baseAlignment);
if (hr == S_FALSE)
{
// It's a DDS, but not an XBOX variant
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
if (FAILED(hr))
return hr;
if (!dataSize || !baseAlignment)
{
return E_FAIL;
}
// Read tiled data
DWORD remaining = fileInfo.EndOfFile.LowPart - XBOX_HEADER_SIZE;
if (remaining == 0)
return E_FAIL;
if (remaining < dataSize)
{
return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
}
hr = xbox.Initialize(mdata, tmode, dataSize, baseAlignment);
if (FAILED(hr))
return hr;
assert(xbox.GetPointer() != nullptr);
if (!ReadFile(hFile.get(), xbox.GetPointer(), dataSize, &bytesRead, nullptr))
{
xbox.Release();
return HRESULT_FROM_WIN32(GetLastError());
}
if (metadata)
memcpy(metadata, &mdata, sizeof(TexMetadata));
return S_OK;
}
//-------------------------------------------------------------------------------------
// Save a DDS file to memory
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT Xbox::SaveToDDSMemory(const XboxImage& xbox, Blob& blob)
{
if (!xbox.GetPointer() || !xbox.GetSize() || !xbox.GetAlignment())
return E_INVALIDARG;
blob.Release();
HRESULT hr = blob.Initialize(XBOX_HEADER_SIZE + xbox.GetSize());
if (FAILED(hr))
return hr;
// Copy header
auto pDestination = reinterpret_cast<uint8_t*>(blob.GetBufferPointer());
assert(pDestination);
hr = EncodeDDSHeader(xbox, pDestination, XBOX_HEADER_SIZE);
if (FAILED(hr))
{
blob.Release();
return hr;
}
// Copy tiled data
size_t remaining = blob.GetBufferSize() - XBOX_HEADER_SIZE;
pDestination += XBOX_HEADER_SIZE;
if (!remaining)
{
blob.Release();
return E_FAIL;
}
if (remaining < xbox.GetSize())
{
blob.Release();
return E_UNEXPECTED;
}
memcpy(pDestination, xbox.GetPointer(), xbox.GetSize());
return S_OK;
}
//-------------------------------------------------------------------------------------
// Save a DDS file to disk
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT Xbox::SaveToDDSFile(const XboxImage& xbox, const wchar_t* szFile)
{
if (!szFile || !xbox.GetPointer() || !xbox.GetSize() || !xbox.GetAlignment())
return E_INVALIDARG;
// Create DDS Header
uint8_t header[XBOX_HEADER_SIZE];
HRESULT hr = EncodeDDSHeader(xbox, header, XBOX_HEADER_SIZE);
if (FAILED(hr))
return hr;
// Create file and write header
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
ScopedHandle hFile(safe_handle(CreateFile2(szFile, GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr)));
#else
ScopedHandle hFile(safe_handle(CreateFileW(szFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr)));
#endif
if (!hFile)
{
return HRESULT_FROM_WIN32(GetLastError());
}
DWORD bytesWritten;
if (!WriteFile(hFile.get(), header, static_cast<DWORD>(XBOX_HEADER_SIZE), &bytesWritten, nullptr))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (bytesWritten != XBOX_HEADER_SIZE)
{
return E_FAIL;
}
// Write tiled data
if (!WriteFile(hFile.get(), xbox.GetPointer(), static_cast<DWORD>(xbox.GetSize()), &bytesWritten, nullptr))
{
return HRESULT_FROM_WIN32(GetLastError());
}
if (bytesWritten != xbox.GetSize())
{
return E_FAIL;
}
return S_OK;
}
| 32.687675 | 144 | 0.575389 | dephora |
3e2fa44f3488ae27ac4ee5995bdff649c2d02b04 | 1,695 | cpp | C++ | UnsolvedTasks/Tasks/Task6.cpp | JustoSenka/CppAlgorithmsTutorial | 057afe24b5f44e923633a998b6059839942ec333 | [
"MIT"
] | null | null | null | UnsolvedTasks/Tasks/Task6.cpp | JustoSenka/CppAlgorithmsTutorial | 057afe24b5f44e923633a998b6059839942ec333 | [
"MIT"
] | null | null | null | UnsolvedTasks/Tasks/Task6.cpp | JustoSenka/CppAlgorithmsTutorial | 057afe24b5f44e923633a998b6059839942ec333 | [
"MIT"
] | null | null | null | /*
Multiple choice test has several multiple choice questions. Each question can have only one correct answer.
Additionally, timed multiple choice test can specify the time allowed for solving each question in the test.
The code below satisfies this specification, but the customer complained that the memory usage of the program constantly increases. Fix this problem.
*/
#include <iostream>
#include <string>
class MultipleChoiceTest
{
public:
MultipleChoiceTest(int questionsCount)
{
this->questionsCount = questionsCount;
answers = new int[questionsCount];
for (int i = 0; i < questionsCount; i++)
{
answers[i] = -1;
}
}
void setAnswer(int questionIndex, int answer)
{
answers[questionIndex] = answer;
}
int getAnswer(int questionIndex) const
{
return answers[questionIndex];
}
protected:
int questionsCount;
private:
int* answers;
};
class TimedMultipleChoiceTest : public MultipleChoiceTest
{
public:
TimedMultipleChoiceTest(int questionsCount)
: MultipleChoiceTest(questionsCount)
{
times = new int[questionsCount];
for (int i = 0; i < questionsCount; i++)
{
times[i] = 0;
}
}
void setTime(int questionIndex, int time)
{
times[questionIndex] = time;
}
int getTime(int questionIndex) const
{
return times[questionIndex];
}
private:
int* times;
};
#ifndef RunTests
void executeTest()
{
MultipleChoiceTest test(5);
for (int i = 0; i < 5; i++)
{
test.setAnswer(i, i);
}
for (int i = 0; i < 5; i++)
{
std::cout << "Question " << i + 1 << ", correct answer: " << test.getAnswer(i) << "\n";
}
}
void main_6()
{
for (int i = 0; i < 3; i++)
{
std::cout << "Test: " << i + 1 << "\n";
executeTest();
}
}
#endif
| 18.423913 | 149 | 0.679646 | JustoSenka |
3e31e16309b7ce2dbed57cf264c28432251c957d | 3,452 | cpp | C++ | sensing/pointcloud_preprocessor/src/outlier_filter/radius_search_2d_outlier_filter_nodelet.cpp | goktugyildirim/autoware.universe | b2f90a0952bf37969517f72ccd5a1ea86f253ce5 | [
"Apache-2.0"
] | 12 | 2020-09-25T08:52:59.000Z | 2020-10-05T02:39:31.000Z | sensing/pointcloud_preprocessor/src/outlier_filter/radius_search_2d_outlier_filter_nodelet.cpp | goktugyildirim/autoware.universe | b2f90a0952bf37969517f72ccd5a1ea86f253ce5 | [
"Apache-2.0"
] | 11 | 2022-01-24T10:26:37.000Z | 2022-03-22T08:19:01.000Z | sensing/preprocessor/pointcloud/pointcloud_preprocessor/src/outlier_filter/radius_search_2d_outlier_filter_nodelet.cpp | taikitanaka3/AutowareArchitectureProposal.iv | 0d47ea532118c98458516a8c83fbdab3d27c6231 | [
"Apache-2.0"
] | 9 | 2020-09-27T05:27:09.000Z | 2020-10-08T03:14:25.000Z | // Copyright 2020 Tier IV, 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.
#include "pointcloud_preprocessor/outlier_filter/radius_search_2d_outlier_filter_nodelet.hpp"
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/search/kdtree.h>
#include <pcl/segmentation/segment_differences.h>
#include <vector>
namespace pointcloud_preprocessor
{
RadiusSearch2DOutlierFilterComponent::RadiusSearch2DOutlierFilterComponent(
const rclcpp::NodeOptions & options)
: Filter("RadiusSearch2DOutlierFilter", options)
{
// set initial parameters
{
min_neighbors_ = static_cast<size_t>(declare_parameter("min_neighbors", 5));
search_radius_ = static_cast<double>(declare_parameter("search_radius", 0.2));
}
kd_tree_ = boost::make_shared<pcl::search::KdTree<pcl::PointXY>>(false);
using std::placeholders::_1;
set_param_res_ = this->add_on_set_parameters_callback(
std::bind(&RadiusSearch2DOutlierFilterComponent::paramCallback, this, _1));
}
void RadiusSearch2DOutlierFilterComponent::filter(
const PointCloud2ConstPtr & input, [[maybe_unused]] const IndicesPtr & indices,
PointCloud2 & output)
{
boost::mutex::scoped_lock lock(mutex_);
pcl::PointCloud<pcl::PointXYZ>::Ptr xyz_cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROSMsg(*input, *xyz_cloud);
pcl::PointCloud<pcl::PointXY>::Ptr xy_cloud(new pcl::PointCloud<pcl::PointXY>);
xy_cloud->points.resize(xyz_cloud->points.size());
for (size_t i = 0; i < xyz_cloud->points.size(); ++i) {
xy_cloud->points[i].x = xyz_cloud->points[i].x;
xy_cloud->points[i].y = xyz_cloud->points[i].y;
}
std::vector<int> k_indices(xy_cloud->points.size());
std::vector<float> k_sqr_distances(xy_cloud->points.size());
kd_tree_->setInputCloud(xy_cloud);
pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_output(new pcl::PointCloud<pcl::PointXYZ>);
for (size_t i = 0; i < xy_cloud->points.size(); ++i) {
size_t k = kd_tree_->radiusSearch(i, search_radius_, k_indices, k_sqr_distances);
if (k >= min_neighbors_) {
pcl_output->points.push_back(xyz_cloud->points.at(i));
}
}
pcl::toROSMsg(*pcl_output, output);
output.header = input->header;
}
rcl_interfaces::msg::SetParametersResult RadiusSearch2DOutlierFilterComponent::paramCallback(
const std::vector<rclcpp::Parameter> & p)
{
boost::mutex::scoped_lock lock(mutex_);
if (get_param(p, "min_neighbors", min_neighbors_)) {
RCLCPP_DEBUG(get_logger(), "Setting new min neighbors to: %zu.", min_neighbors_);
}
if (get_param(p, "search_radius", search_radius_)) {
RCLCPP_DEBUG(get_logger(), "Setting new search radius to: %f.", search_radius_);
}
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
result.reason = "success";
return result;
}
} // namespace pointcloud_preprocessor
#include <rclcpp_components/register_node_macro.hpp>
RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_preprocessor::RadiusSearch2DOutlierFilterComponent)
| 37.11828 | 94 | 0.745365 | goktugyildirim |
3e3b096a87bd34364779e8a945d7aee260badde7 | 714 | cpp | C++ | example/eagine/sudoku_tiling.cpp | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | 1 | 2022-01-25T10:31:51.000Z | 2022-01-25T10:31:51.000Z | example/eagine/sudoku_tiling.cpp | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | null | null | null | example/eagine/sudoku_tiling.cpp | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | null | null | null | /// @example eagine/sudoku_tiling.cpp
///
/// Copyright Matus Chochlik.
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
///
#include <eagine/program_args.hpp>
#include <eagine/sudoku.hpp>
#include <iostream>
#include <stack>
#include <map>
template <unsigned S>
void sudoku_tiling() {
using namespace eagine;
const basic_sudoku_board_traits<S> traits;
basic_sudoku_tile_patch<S> patch(32, 24);
basic_sudoku_tiling<S> bst{
traits, traits.make_generator().generate_medium()};
std::cout << bst.fill(0, 0, patch);
}
auto main() -> int {
sudoku_tiling<4>();
return 0;
}
| 23.032258 | 62 | 0.696078 | matus-chochlik |
3e3cba821843f72028d3ddc0cd99bbef8678e4c9 | 1,095 | cpp | C++ | leetcode/hard/1074. Number of Submatrices That Sum to Target.cpp | fpdjsns/Algorithm | 0128da7c333d0c065f6d266d9e6dce4a91842525 | [
"MIT"
] | 7 | 2019-08-05T14:49:41.000Z | 2022-03-13T07:10:51.000Z | leetcode/hard/1074. Number of Submatrices That Sum to Target.cpp | fpdjsns/Algorithm | 0128da7c333d0c065f6d266d9e6dce4a91842525 | [
"MIT"
] | null | null | null | leetcode/hard/1074. Number of Submatrices That Sum to Target.cpp | fpdjsns/Algorithm | 0128da7c333d0c065f6d266d9e6dce4a91842525 | [
"MIT"
] | 4 | 2021-01-04T03:45:22.000Z | 2021-10-06T06:11:00.000Z | /**
* problem : https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/
* time complexity : O(N^2 * M^2)
* algorithm : subSum, dp
*/
class Solution {
public:
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> subSum(n+1, vector<int>(m+1));
for(int i=0; i<n; i++){
int sum = 0;
for(int j=0; j<m; j++){
sum += matrix[i][j];
subSum[i+1][j+1] = subSum[i][j+1] + sum;
}
}
int answer = 0;
for(int x1=0; x1 < n; x1++){
for(int x2=x1+1; x2<=n;x2++){
for(int y1=0; y1 < m; y1++){
for(int y2=y1+1; y2<=m; y2++){
// (x1, x2] (y1, y2]
if(subSum[x2][y2] - subSum[x1][y2] - subSum[x2][y1] + subSum[x1][y1] == target)
answer++;
}
}
}
}
return answer;
}
};
| 29.594595 | 103 | 0.404566 | fpdjsns |
3e3f784bb6fb46e0a0bcb2c1311e05e032ad1617 | 1,296 | cpp | C++ | EvtGen1_06_00/src/EvtGenModels/EvtItgFunction.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | EvtGen1_06_00/src/EvtGenModels/EvtItgFunction.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | EvtGen1_06_00/src/EvtGenModels/EvtItgFunction.cpp | klendathu2k/StarGenerator | 7dd407c41d4eea059ca96ded80d30bda0bc014a4 | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: EvtItgFunction.cpp,v 1.1 2016/10/28 16:52:54 jwebb Exp $
//
// Description:
// Class EvtItgFunction
// Implementation for the EvtItgFunction class. Defines the bounds
// checked value() function and the non-bounds checked operator()
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author List:
// Phil Strother Originator
//
// Copyright Information: See EvtGen/COPYRIGHT
// Copyright (C) 1998 LBNL
//
//------------------------------------------------------------------------
#include "EvtGenBase/EvtPatches.hh"
//-----------------------
// This Class's Header --
//-----------------------
#include "EvtGenModels/EvtItgFunction.hh"
//-------------
// C Headers --
//-------------
extern "C" {
}
//----------------
// Constructors --
//----------------
EvtItgFunction::EvtItgFunction( double (*theFunction)(double), double lowerRange, double upperRange):
EvtItgAbsFunction(lowerRange, upperRange),
_myFunction(theFunction)
{}
//--------------
// Destructor --
//--------------
EvtItgFunction::~EvtItgFunction( )
{}
double
EvtItgFunction::myFunction(double x) const{
return _myFunction(x);
}
| 23.563636 | 101 | 0.542438 | klendathu2k |
3e3fd889d2e722c567b39c009b0ff35b2ea5cf90 | 1,060 | cpp | C++ | src/v3/AsyncTxnAction.cpp | siyuan0322/etcd-cpp-apiv3 | 1575c5b43a64f85f77897e9b5aad24e6523ea453 | [
"BSD-3-Clause"
] | 139 | 2016-09-20T00:28:04.000Z | 2020-09-27T15:05:11.000Z | src/v3/AsyncTxnAction.cpp | siyuan0322/etcd-cpp-apiv3 | 1575c5b43a64f85f77897e9b5aad24e6523ea453 | [
"BSD-3-Clause"
] | 85 | 2020-09-29T16:33:00.000Z | 2022-03-30T01:23:23.000Z | src/v3/AsyncTxnAction.cpp | siyuan0322/etcd-cpp-apiv3 | 1575c5b43a64f85f77897e9b5aad24e6523ea453 | [
"BSD-3-Clause"
] | 63 | 2016-12-06T11:42:29.000Z | 2020-09-24T06:15:49.000Z | #include "etcd/v3/action_constants.hpp"
#include "etcd/v3/AsyncTxnAction.hpp"
#include "etcd/v3/Transaction.hpp"
etcdv3::AsyncTxnAction::AsyncTxnAction(
etcdv3::ActionParameters const ¶m, etcdv3::Transaction const &tx)
: etcdv3::Action(param)
{
response_reader = parameters.kv_stub->AsyncTxn(&context, *tx.txn_request, &cq_);
response_reader->Finish(&reply, &status, (void *)this);
}
etcdv3::AsyncTxnResponse etcdv3::AsyncTxnAction::ParseResponse()
{
AsyncTxnResponse txn_resp;
txn_resp.set_action(etcdv3::TXN_ACTION);
if(!status.ok())
{
txn_resp.set_error_code(status.error_code());
txn_resp.set_error_message(status.error_message());
}
else
{
txn_resp.ParseResponse(parameters.key, parameters.withPrefix, reply);
//if there is an error code returned by parseResponse, we must
//not overwrite it.
if(!reply.succeeded() && !txn_resp.get_error_code())
{
txn_resp.set_error_code(ERROR_COMPARE_FAILED);
txn_resp.set_error_message("compare failed");
}
}
return txn_resp;
}
| 27.179487 | 82 | 0.718868 | siyuan0322 |
3e42e00ab24d231d1c84074f91b40c0e972d80cf | 1,648 | hpp | C++ | src/traderlib/core/bom/tradesparameters.hpp | AndreaCitrolo/Trader | 5ebaff6d5661471357cb827d3b0c61adafc24b50 | [
"MIT"
] | null | null | null | src/traderlib/core/bom/tradesparameters.hpp | AndreaCitrolo/Trader | 5ebaff6d5661471357cb827d3b0c61adafc24b50 | [
"MIT"
] | 1 | 2019-11-06T23:15:30.000Z | 2019-11-11T10:04:32.000Z | src/traderlib/core/bom/tradesparameters.hpp | AndreaCitrolo/Trader | 5ebaff6d5661471357cb827d3b0c61adafc24b50 | [
"MIT"
] | 1 | 2019-11-10T00:01:07.000Z | 2019-11-10T00:01:07.000Z | #ifndef TRADESREQUESTPARAMETERS_HPP
#define TRADESREQUESTPARAMETERS_HPP
#include <QVariant>
#include <QMetaType>
#include <boost/optional.hpp>
#include "basictypes.h"
namespace bitinvest {
namespace core {
namespace bom {
struct TradesParameters
{
TradesParameters():
mSymbol(boost::none),
mFilterSpecifier(boost::none),
mDataSpecifier(boost::none)
{}
TradesParameters(
const Symbol &iSymbol):
mSymbol(iSymbol), mFilterSpecifier(boost::none), mDataSpecifier(boost::none)
{}
TradesParameters(
const Symbol &iSymbol,
const DataSpecifier& iDataSpecifier):
mSymbol(iSymbol), mFilterSpecifier(boost::none), mDataSpecifier(iDataSpecifier)
{}
TradesParameters(
const Symbol &iSymbol,
const FilterSpecifier & iFilterSpecifier):
mSymbol(iSymbol), mFilterSpecifier(iFilterSpecifier), mDataSpecifier(boost::none)
{}
TradesParameters(
const Symbol & iSymbol,
const FilterSpecifier & iFilterSpecifier,
const DataSpecifier & iDataSpecifier):
mSymbol(iSymbol), mFilterSpecifier(iFilterSpecifier), mDataSpecifier(iDataSpecifier)
{}
TradesParameters(const TradesParameters & other):
mSymbol(other.mSymbol), mFilterSpecifier(other.mFilterSpecifier), mDataSpecifier(other.mDataSpecifier)
{}
boost::optional<Symbol> mSymbol;
boost::optional<FilterSpecifier> mFilterSpecifier;
boost::optional<DataSpecifier> mDataSpecifier;
};
}
}
}
Q_DECLARE_METATYPE(bitinvest::core::bom::TradesParameters)
#endif // TRADESREQUESTPARAMETERS_HPP
| 25.75 | 114 | 0.697816 | AndreaCitrolo |
3e44d48bffc61e289c391d80aa9d93dd9c86f172 | 5,709 | inl | C++ | src/Core/Asset/deprecated/FileManager.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | 1 | 2018-04-16T13:55:45.000Z | 2018-04-16T13:55:45.000Z | src/Core/Asset/deprecated/FileManager.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | src/Core/Asset/deprecated/FileManager.inl | sylvaindeker/Radium-Engine | 64164a258b3f7864c73a07c070e49b7138488d62 | [
"Apache-2.0"
] | null | null | null | #include <Core/Asset/deprecated/FileManager.hpp>
namespace Ra {
namespace Core {
namespace Asset {
namespace deprecated {
//////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////////
template <typename DATA, bool Binary>
inline FileManager<DATA, Binary>::FileManager() : m_log( "" ) {}
//////////////////////////////////////////////////////////////////////////////
// DESTRUCTOR
//////////////////////////////////////////////////////////////////////////////
template <typename DATA, bool Binary>
inline FileManager<DATA, Binary>::~FileManager() {}
//////////////////////////////////////////////////////////////////////////////
// INTERFACE
//////////////////////////////////////////////////////////////////////////////
template <typename DATA, bool Binary>
inline bool FileManager<DATA, Binary>::load( const std::string& filename, DATA& data,
const bool SAVE_LOG_FILE ) {
bool status = true;
resetLog();
addLogEntry( "Filename : " + filename );
addLogEntry( "Expected Format : " + fileExtension() );
addLogEntry( "File Type : " + std::string( Binary ? "Binary" : "Text" ) );
addLogEntry( "Loading start..." );
std::ifstream file( filename, std::ios_base::in |
( Binary ? std::ios_base::binary : std::ios_base::in ) );
if ( !( status = file.is_open() ) )
{
addLogWarningEntry(
"Error occurred while opening the file. Trying to see if extension is missing..." );
file.open( filename + "." + fileExtension(),
std::ios_base::in | ( Binary ? std::ios_base::binary : std::ios_base::in ) );
if ( !( status = file.is_open() ) )
{
addLogErrorEntry( "Error occured while opening the file. HINT: FILENAME IS WRONG." );
}
}
if ( status )
{
addLogEntry( "File opened successfully." );
addLogEntry( "Starting to import the data." );
status = importData( file, data );
addLogEntry( "Import " + ( ( status ) ? std::string( "DONE." ) : std::string( "FAILED." ) ),
( ( status ) ? LogEntry_Normal : LogEntry_Error ) );
file.close();
addLogEntry( "File closed." );
}
addLogEntry( "Loading " + filename + " ended." );
if ( SAVE_LOG_FILE )
{
saveLog( filename + "_load" );
}
return status;
}
template <typename DATA, bool Binary>
inline bool FileManager<DATA, Binary>::save( const std::string& filename, const DATA& data,
const bool SAVE_LOG_FILE ) {
bool status = true;
resetLog();
addLogEntry( "Filename : " + filename );
addLogEntry( "Exporting Format : " + fileExtension() );
addLogEntry( "File Type : " + std::string( Binary ? "Binary" : "Text" ) );
addLogEntry( "Saving start..." );
std::ofstream file( filename + "." + fileExtension(),
std::ios_base::out | std::ios_base::trunc |
( Binary ? std::ios_base::binary : std::ios_base::out ) );
if ( !( status = file.is_open() ) )
{
addLogErrorEntry( "Error occured while opening the file." );
}
if ( status )
{
addLogEntry( "File opened successfully." );
addLogEntry( "Starting to export the data..." );
status = exportData( file, data );
addLogEntry( "Export " + ( ( status ) ? std::string( "DONE." ) : std::string( "FAILED." ) ),
( ( status ) ? LogEntry_Normal : LogEntry_Error ) );
file.close();
addLogEntry( "File closed." );
}
addLogEntry( "Saving " + filename + " ended." );
if ( SAVE_LOG_FILE )
{
saveLog( filename + "_save" );
}
return status;
}
//////////////////////////////////////////////////////////////////////////////
// LOG
//////////////////////////////////////////////////////////////////////////////
template <typename DATA, bool Binary>
inline std::string FileManager<DATA, Binary>::log() const {
return m_log;
}
template <typename DATA, bool Binary>
inline void FileManager<DATA, Binary>::addLogEntry( const std::string& text ) {
addLogEntry( text, LogEntry_Normal );
}
template <typename DATA, bool Binary>
inline void FileManager<DATA, Binary>::addLogWarningEntry( const std::string& text ) {
addLogEntry( text, LogEntry_Warning );
}
template <typename DATA, bool Binary>
inline void FileManager<DATA, Binary>::addLogErrorEntry( const std::string& text ) {
addLogEntry( text, LogEntry_Error );
}
template <typename DATA, bool Binary>
inline void FileManager<DATA, Binary>::addLogEntry( const std::string& text,
const LogEntryType type ) {
switch ( type )
{
case LogEntry_Normal:
{ m_log += text; }
break;
case LogEntry_Warning:
{ m_log += "\n--- LogEntry_Warning : " + text + " ---\n"; }
break;
case LogEntry_Error:
{ m_log += "\n### LogEntry_Error : " + text + " ###\n"; }
break;
default:
break;
}
m_log += "\n";
}
template <typename DATA, bool Binary>
inline void FileManager<DATA, Binary>::resetLog() {
m_log = "====== FILE MANAGER LOG ======\n";
}
template <typename DATA, bool Binary>
inline void FileManager<DATA, Binary>::saveLog( const std::string& filename ) {
std::ofstream file( filename + ".log" );
if ( !file.is_open() )
{
return;
}
file << log();
file.close();
}
} // namespace deprecated
} // namespace Asset
} // namespace Core
} // namespace Ra
| 34.810976 | 100 | 0.51375 | sylvaindeker |
3e46ab2573f1313da6146302fd0b3465ed976a82 | 3,954 | cpp | C++ | cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/fdim_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/fdim_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/fdim_test.cpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/rev/scal.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/scal/fun/nan_util.hpp>
#include <test/unit/math/rev/scal/util.hpp>
TEST(AgradRev,fdim_vv) {
using stan::math::fdim;
AVAR a = 3.0;
AVAR b = 4.0;
AVAR f = fdim(a,b);
EXPECT_FLOAT_EQ(0.0,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
EXPECT_FLOAT_EQ(0.0,grad_f[1]);
a = std::numeric_limits<AVAR>::infinity();
EXPECT_FLOAT_EQ(0.0, fdim(a,a).val());
EXPECT_FLOAT_EQ(std::numeric_limits<double>::infinity(), fdim(a,b).val());
EXPECT_FLOAT_EQ(0.0, fdim(b,a).val());
}
TEST(AgradRev,fdim_vv_2) {
using stan::math::fdim;
AVAR a = 7.0;
AVAR b = 2.0;
AVAR f = fdim(a,b);
EXPECT_FLOAT_EQ(5.0,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
EXPECT_FLOAT_EQ(-1.0,grad_f[1]);
a = std::numeric_limits<AVAR>::infinity();
EXPECT_FLOAT_EQ(0.0, fdim(a,a).val());
EXPECT_FLOAT_EQ(std::numeric_limits<double>::infinity(), fdim(a,b).val());
EXPECT_FLOAT_EQ(0.0, fdim(b,a).val());
}
TEST(AgradRev,fdim_vd) {
using stan::math::fdim;
AVAR a = 3.0;
double b = 4.0;
AVAR f = fdim(a,b);
EXPECT_FLOAT_EQ(0.0,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
AVAR infinityavar = std::numeric_limits<AVAR>::infinity();
double infinitydouble = std::numeric_limits<double>::infinity();
EXPECT_FLOAT_EQ(0.0, fdim(infinityavar,infinitydouble).val());
EXPECT_FLOAT_EQ(std::numeric_limits<double>::infinity(), fdim(infinityavar,b).val());
EXPECT_FLOAT_EQ(0.0, fdim(a,infinitydouble).val());
}
TEST(AgradRev,fdim_vd_2) {
using stan::math::fdim;
AVAR a = 7.0;
double b = 2.0;
AVAR f = fdim(a,b);
EXPECT_FLOAT_EQ(5.0,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
AVAR infinityavar = std::numeric_limits<AVAR>::infinity();
double infinitydouble = std::numeric_limits<double>::infinity();
EXPECT_FLOAT_EQ(0.0, fdim(infinityavar,infinitydouble).val());
EXPECT_FLOAT_EQ(std::numeric_limits<double>::infinity(), fdim(infinityavar,b).val());
EXPECT_FLOAT_EQ(0.0, fdim(a,infinitydouble).val());
}
TEST(AgradRev,fdim_dv) {
using stan::math::fdim;
double a = 3.0;
AVAR b = 4.0;
AVAR f = fdim(a,b);
EXPECT_FLOAT_EQ(0.0,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
AVAR infinityavar = std::numeric_limits<AVAR>::infinity();
double infinitydouble = std::numeric_limits<double>::infinity();
EXPECT_FLOAT_EQ(0.0, fdim(infinitydouble,infinityavar).val());
EXPECT_FLOAT_EQ(std::numeric_limits<double>::infinity(), fdim(infinitydouble,b).val());
EXPECT_FLOAT_EQ(0.0, fdim(a,infinityavar).val());
}
TEST(AgradRev,fdim_dv_2) {
using stan::math::fdim;
double a = 7.0;
AVAR b = 2.0;
AVAR f = fdim(a,b);
EXPECT_FLOAT_EQ(5.0,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(-1.0,grad_f[0]);
AVAR infinityavar = std::numeric_limits<AVAR>::infinity();
double infinitydouble = std::numeric_limits<double>::infinity();
EXPECT_FLOAT_EQ(0.0, fdim(infinitydouble,infinityavar).val());
EXPECT_FLOAT_EQ(std::numeric_limits<double>::infinity(), fdim(infinitydouble,b).val());
EXPECT_FLOAT_EQ(0.0, fdim(a,infinityavar).val());
}
struct fdim_fun {
template <typename T0, typename T1>
inline
typename stan::return_type<T0,T1>::type
operator()(const T0& arg1,
const T1& arg2) const {
return fdim(arg1,arg2);
}
};
TEST(AgradRev, fdim_nan) {
fdim_fun fdim_;
test_nan(fdim_, 3.0, 5.0, false, true);
}
TEST(AgradRev, check_varis_on_stack) {
AVAR a = 3.0;
AVAR b = 4.0;
test::check_varis_on_stack(stan::math::fdim(a, b));
test::check_varis_on_stack(stan::math::fdim(a, 4.0));
test::check_varis_on_stack(stan::math::fdim(3.0, b));
}
| 28.652174 | 89 | 0.675013 | yizhang-cae |
3e4916d0e1def8d13a1e22a79406090440fb34f4 | 211 | cpp | C++ | Baekjoon/14913.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/14913.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | Baekjoon/14913.cpp | Twinparadox/AlgorithmProblem | 0190d17555306600cfd439ad5d02a77e663c9a4e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(void)
{
int a, d, k, n;
cin >> a >> d >> k;
k -= a;
if (k%d != 0)
cout << 'X';
else
{
if (k / d < 0)
cout << 'X';
else
cout << k / d + 1;
}
}
| 11.722222 | 21 | 0.440758 | Twinparadox |
3e492e5957689a19ab408048178ff1f3e4b42e50 | 325 | hpp | C++ | include/libcam/exception.hpp | luckybet100/libcam | c837e84769a75c83c518fcda9d7f12d6061e0110 | [
"MIT"
] | 4 | 2021-07-01T19:49:23.000Z | 2022-03-14T01:53:17.000Z | include/libcam/exception.hpp | luckybet100/libcam | c837e84769a75c83c518fcda9d7f12d6061e0110 | [
"MIT"
] | null | null | null | include/libcam/exception.hpp | luckybet100/libcam | c837e84769a75c83c518fcda9d7f12d6061e0110 | [
"MIT"
] | 1 | 2020-11-04T10:05:00.000Z | 2020-11-04T10:05:00.000Z | #pragma once
#include <string>
#include <stdexcept>
namespace libcam {
class Exception : public std::exception {
private:
std::string message;
public:
Exception(const std::string &message);
virtual ~Exception() noexcept = default;
const char *what() const noexcept;
};
}
| 16.25 | 48 | 0.621538 | luckybet100 |
3e49383e501e0a410cd3182c97489671069c6278 | 3,460 | cpp | C++ | CesiumUtility/src/Uri.cpp | zrkcode/cesium-native | 5265a65053542fe02928c272762c6b89fa2b29bb | [
"Apache-2.0"
] | null | null | null | CesiumUtility/src/Uri.cpp | zrkcode/cesium-native | 5265a65053542fe02928c272762c6b89fa2b29bb | [
"Apache-2.0"
] | null | null | null | CesiumUtility/src/Uri.cpp | zrkcode/cesium-native | 5265a65053542fe02928c272762c6b89fa2b29bb | [
"Apache-2.0"
] | null | null | null | #include "CesiumUtility/Uri.h"
#include "uriparser/Uri.h"
#include <stdexcept>
using namespace CesiumUtility;
std::string Uri::resolve(
const std::string& base,
const std::string& relative,
bool useBaseQuery) {
UriUriA baseUri;
if (uriParseSingleUriA(&baseUri, base.c_str(), nullptr) != URI_SUCCESS) {
// Could not parse the base, so just use the relative directly and hope for
// the best.
return relative;
}
UriUriA relativeUri;
if (uriParseSingleUriA(&relativeUri, relative.c_str(), nullptr) !=
URI_SUCCESS) {
// Could not parse one of the URLs, so just use the relative directly and
// hope for the best.
uriFreeUriMembersA(&baseUri);
return relative;
}
UriUriA resolvedUri;
if (uriAddBaseUriA(&resolvedUri, &relativeUri, &baseUri) != URI_SUCCESS) {
uriFreeUriMembersA(&resolvedUri);
uriFreeUriMembersA(&relativeUri);
uriFreeUriMembersA(&baseUri);
return relative;
}
if (uriNormalizeSyntaxA(&resolvedUri) != URI_SUCCESS) {
uriFreeUriMembersA(&resolvedUri);
uriFreeUriMembersA(&relativeUri);
uriFreeUriMembersA(&baseUri);
return relative;
}
int charsRequired;
if (uriToStringCharsRequiredA(&resolvedUri, &charsRequired) != URI_SUCCESS) {
uriFreeUriMembersA(&resolvedUri);
uriFreeUriMembersA(&relativeUri);
uriFreeUriMembersA(&baseUri);
return relative;
}
std::string result(static_cast<size_t>(charsRequired), ' ');
if (uriToStringA(
const_cast<char*>(result.c_str()),
&resolvedUri,
charsRequired + 1,
nullptr) != URI_SUCCESS) {
uriFreeUriMembersA(&resolvedUri);
uriFreeUriMembersA(&relativeUri);
uriFreeUriMembersA(&baseUri);
return relative;
}
if (useBaseQuery) {
std::string query(baseUri.query.first, baseUri.query.afterLast);
if (query.length() > 0) {
if (resolvedUri.query.first) {
result += "&" + query;
} else {
result += "?" + query;
}
}
}
uriFreeUriMembersA(&resolvedUri);
uriFreeUriMembersA(&relativeUri);
uriFreeUriMembersA(&baseUri);
return result;
}
std::string Uri::addQuery(
const std::string& uri,
const std::string& key,
const std::string& value) {
// TODO
if (uri.find('?') != std::string::npos) {
return uri + "&" + key + "=" + value;
}
return uri + "?" + key + "=" + value;
// UriUriA baseUri;
// if (uriParseSingleUriA(&baseUri, uri.c_str(), nullptr) != URI_SUCCESS)
//{
// // TODO: report error
// return uri;
//}
// uriFreeUriMembersA(&baseUri);
}
std::string Uri::substituteTemplateParameters(
const std::string& templateUri,
const std::function<SubstitutionCallbackSignature>& substitutionCallback) {
std::string result;
std::string placeholder;
size_t startPos = 0;
size_t nextPos;
// Find the start of a parameter
while ((nextPos = templateUri.find('{', startPos)) != std::string::npos) {
result.append(templateUri, startPos, nextPos - startPos);
// Find the end of this parameter
++nextPos;
size_t endPos = templateUri.find('}', nextPos);
if (endPos == std::string::npos) {
throw std::runtime_error("Unclosed template parameter");
}
placeholder = templateUri.substr(nextPos, endPos - nextPos);
result.append(substitutionCallback(placeholder));
startPos = endPos + 1;
}
result.append(templateUri, startPos, templateUri.length() - startPos);
return result;
}
| 26.212121 | 79 | 0.664451 | zrkcode |
3e4b718a16afc7c86a6ac7771ce692c1e75a888a | 446 | cpp | C++ | core/src/Util.cpp | BlurryRoots/hannelore | 28b54553ed3b7be6e1e9e29efe6d1d0473f19bf6 | [
"BSD-2-Clause"
] | 2 | 2015-03-30T15:17:07.000Z | 2016-07-31T04:57:23.000Z | core/src/Util.cpp | BlurryRoots/hannelore | 28b54553ed3b7be6e1e9e29efe6d1d0473f19bf6 | [
"BSD-2-Clause"
] | 5 | 2016-06-08T20:39:16.000Z | 2016-06-08T20:46:42.000Z | core/src/Util.cpp | BlurryRoots/hannelore | 28b54553ed3b7be6e1e9e29efe6d1d0473f19bf6 | [
"BSD-2-Clause"
] | 1 | 2020-06-08T08:07:53.000Z | 2020-06-08T08:07:53.000Z | #include <Util.h>
namespace blurryroots { namespace util {
DebugLogLevel blurryroots::util::log_level = DebugLogLevel::Error
| DebugLogLevel::Warn
| DebugLogLevel::Log
;
bool
has_only_spaces (const std::string& in) {
for (std::string::const_iterator it = in.begin (); it != in.end (); ++it) {
// return early if there is something other than a space
if (*it != ' ') {
return false;
}
}
return true;
}
}}
| 19.391304 | 77 | 0.630045 | BlurryRoots |
3e4dc6f50891f4452446e3c35fd003e5e13d94ee | 37,154 | cpp | C++ | XUXUCAM/CamDxf/campart.cpp | hananiahhsu/OpenCAD | d4ae08195411057cce182fe5a4c0a3d226279697 | [
"Apache-2.0"
] | 13 | 2018-11-06T12:37:42.000Z | 2021-07-22T11:49:35.000Z | XUXUCAM/CamDxf/campart.cpp | hananiahhsu/OpenCAD | d4ae08195411057cce182fe5a4c0a3d226279697 | [
"Apache-2.0"
] | 1 | 2020-05-15T07:21:06.000Z | 2020-05-28T05:10:35.000Z | XUXUCAM/CamDxf/campart.cpp | hananiahhsu/OpenCAD | d4ae08195411057cce182fe5a4c0a3d226279697 | [
"Apache-2.0"
] | 11 | 2018-11-06T12:37:52.000Z | 2021-09-25T08:02:27.000Z | #include "CamDxf/campart.h"
#include "CamDxf/camswap.h"
///used to manually set the loopNumber
#include <QInputDialog>
///@note:at() can be faster than operator[](), because it never causes a deep copy to occur.
/// The tolerance defines the disstance within it a loop is estimated to be closed
int tolerance=0.01;
/// @todo get from settings lead angle for circle loops
//int leadAngle=180;
bool plasmaMode=true;
///Automatically optize path on part previewing
bool optPath=true;
/** have to create an object lead point , a QGraphicsEllipseItem that is magneted to the endPoint parent
and which position will be used by the G code genrator**/
/** FIXME handle the case the part outline is a circle!! */
/** For the outline: We first check if the OutlinePoint intersects with the rectBounds, such point can be trivialy
chosen to be a good candidtae for lean in.In that case we draw a line, its lenght being specified by the user,and we
try with different angular positions till the lead-in point is no longer contained in the RectBound*/
/// @fixme: part ansi/6/14-299 is a total mess in leads!
///@note have to intialize outside the class
double Part::movePartVal=2;
void Part::setMovePartVal(double val){
movePartVal=val;
}
/**
*
* @param path
* @param pointsList
* @param partPathsList
* @param circlePointsList
* @param circlesPathsList
* @param file
*/
Part::Part(const QPainterPath path,QPFWPVector pointsList,QPPVector partPathsList,QPFWPVector circlePointsList,QPPVector circlesPathsList):
QGraphicsItem(){
partShape=path;
qtRect=partShape.boundingRect();
nbrClosedPath=0;
nbrCircles=0;
outlinePos=0;
tpLength=0;
partLoops.clear();
partLoopsOpt.clear();
ptsVector=pointsList;
pathsList=partPathsList;
cirPtsList=circlePointsList;
cirPathsList=circlesPathsList;
leadAngle=(settings.value("Leads/angle").toInt());
leadDist=settings.value("Leads/leadDist").toDouble();
leadRadius= settings.value("Leads/radius").toDouble();
optPath=settings.value("Options/optPath").toBool();
plasmaMode=settings.value("Options/plasmaMode").toBool();
gLoops.clear();
gLeadPoints.clear();
openLoopError=false;
preview=true;
///@note although unused in preview-mode we reset the matrix for proper intialisation
transform.reset();
///to keep track of the part Nbr @todo: get this from the scen and use it when deleting parts!!
///setData(0,partNumber);
//setFlag(ItemIsMovable);
//setFlag(ItemIsSelectable);
//LoopThread test(this);
/// For better image rendering use caching
//setCacheMode(DeviceCoordinateCache);
///everything is ready we can start processing the part
start();
}
void Part::hoverEnterEvent ( QGraphicsSceneHoverEvent * event ) {
selecPix->setVisible(true);
}
void Part::hoverLeaveEvent ( QGraphicsSceneHoverEvent * event ) {
/// @todo have to wait for 1 sec before hiding the cross
//timer.start(1000,scene());
selecPix->setVisible(false);
}
///Constructor used to add multiplie part to a sheet by copying the previewed part items
Part::Part(const Part &parentPart):QGraphicsItem(){
preview=false;
setFlag(ItemIsMovable);
setFlag(ItemIsSelectable);
setFlag(ItemIsFocusable);
partShape=parentPart.partShape;
qtRect=parentPart.qtRect;
tpLength=parentPart.tpLength;
/// @todo Before copying the shape have to take into account the outline leads
partOutShape=parentPart.partOutShape;
setAcceptHoverEvents(true);
///we start taking transformation into account from here
transform.reset();
/// @note To ensure that moving the selecPix moves the hole part
setHandlesChildEvents(true);
/// we add the circle that will be displayed to select the part (like KDE file selection model)
selecPix=new QGraphicsPixmapItem(QPixmap (":iconsB/32x32/list-add.png"),this);
selecPix->setPos(this->boundingRect().center()-QPointF(16,16));
//selecPix->setFlags(ItemIsSelectable | ItemIsMovable);
selecPix->setVisible(true);
//selecPix->setFlags(QGraphicsItem::ItemIsMovable |QGraphicsItem::ItemIsSelectable);
///NOw that the leads are cleaned we can copy them to gLoops that will be pocede by GCode
foreach (Loop* cLoop, parentPart.partLoops){
gLoops<<cLoop->getEntities();
///@todo: check for plasma mode to avoid copying unnessacry things
gLeadPoints<<cLoop->leadIn;
}
//qDebug()<<gLeadPoints;
/// Any change to preview part will affect the partLoops thus editiing one will edit the others
partLoops=parentPart.partLoops;
///@fixme as getting loops entities causes crashes we're going through gcodeEntities which is "static" by part
partName=parentPart.partName;
///to keep track of the part Nbr
setData(0,parentPart.data(0));
///NOTE:NO need to take the Trans part
}
Part* Part::copy(){
Part* newPart=new Part(*this);
return newPart;
}
void Part::paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget *) {
///part in preview scen are drawn loop by loop so we d'ont do any painting for them
if (preview) return;
///@note isSelected is provided by Qt
if (isSelected()) {
///@todo add an option to the config Dialogdesig
///@todo add pen width to the rectBound
painter->setPen(QPen(Qt::blue,0,Qt::DashLine));
painter->drawRect(qtRect);
}
///@fixme: read settings only once
painter->setPen( settings.value("Colors/pen").value<QColor>());
///If no color had been already set
if (settings.value("Options/colorizeInner").toInt()!=2){
painter->setBrush(Qt::NoBrush);
}
else{
painter->setBrush(settings.value("Colors/brush").value<QColor>());
}
painter->drawPath(partShape);
}
void Part::start(){
/// Start by parsing circular loops
if(cirPtsList.size()!=0){
filterCircles();
}
//Search for continous loops in part.
if(ptsVector.size()!=0){
generateLoops(ptsVector);
}
if (plasmaMode){
///Move the part outline to the List's end it has to be the last to be cut in plasma/laser cutting (if plasmaMode is enabled)
findOutline();
//if (partLoops.size()=>1){
//}
//@fixme outlineLead will be created within generateLead after cheking for is outline
//createOutlineLead();
///Now that all the graphical processing is done we "allow" loops to be drawn
generateLeads();
}
///@todo: add option : optimize auto
qDebug()<<"Starting optimization";
///We try to optimize only if there is at least an outline loop and an inner one
if ((partLoops.size()>1) && optPath){
optimizeRoute();
}
else {
partLoopsOpt=partLoops;
}
///now we can start drawing the loops
foreach (Loop* cLoop, partLoopsOpt){
cLoop->setReady(true);
//qDebug()<<"Loops order"<<cLoop->loopNumber;
}
}
void Part::filterCircles(){
/**As we have to return a QList of Qlist we create a temporary one (for now the temp dimension is one
But when introducing circles lead-in lead-out a circle loop will contain 2 points the center and the lead in**/
QPFWPVector temp;
QPointFWithParent currentPoint;
///creating a new circleLoop
Loop *tempLoop=new Loop(this);
///@note to avoid crash we append an element to temp and keep changing it
temp.append(cirPtsList[0]);
//qDebug()<<"Adding "<<cirPtsList.size()<<" circles";
///create a new lop for each encountered circle and set it's number and shape
for (int pos=0; pos <cirPtsList.size();pos++){
/**We take a point mark its parent loop umber (for later tsp processing) then
appeend it to the endPointslist and add the closedPath counter**/
currentPoint=cirPtsList.at(pos);
/// @fixme We need to save the parent loop in the original point for later use in optimize devise a more elegant way to do that
currentPoint.setLoopNbr(nbrClosedPath);
//temp[0]=cirPtsList.at(pos);
temp[0]=currentPoint;
tempLoop->addPath(cirPathsList.at(pos));
tempLoop->setStart(currentPoint);
tempLoop->setEnd(currentPoint);
tempLoop->setTypeCircle(true);
tempLoop->setEntities(temp);
///@note: have to call setNumber AFTER setEntitites!!
tempLoop->setNumber(nbrClosedPath);
partLoops<<tempLoop;
nbrClosedPath++;
tempLoop=new Loop(this);
}
///at this step we only have circles
nbrCircles=nbrClosedPath;
///@todo We don't need the path list anymore, free it
cirPathsList.clear();
cirPtsList.clear();
}
void Part::generateLoops(QPFWPVector ptsVector){
Loop *tempLoop=new Loop(this);
QPointFWithParent currentPoint;
QPFWPVector pointsVectorNew;
QPainterPath subLoop;
bool alreadyChecked=false;
int oldPos=0,found=1,pos=0;
///@fixme:have to change the algorithm I'm working with :sort the points tables and go from one to the one next to as they are QpWP it's all i need
qDebug() << "Dealing with "<<pathsList.size()<<" Entities represented by "<< ptsVector.size()<<"points";
while (ptsVector.size()>=2) {
currentPoint=ptsVector.at(pos);
//qDebug()<<"Working with"<<currentPoint<< " at "<<pos;
if (ptsVector.count(currentPoint)==1) {
oldPos=pos;
//qDebug()<<"No corresponding point.AlreadyChecked other coord:"<<alreadyChecked;
if ( alreadyChecked==false ) {
if (pos%2==0) pos++; else pos--;
alreadyChecked=true;
}
currentPoint=ptsVector.at(pos);
if (ptsVector.count(currentPoint)==1) {
//qDebug()<<"Swaped but still no corresponding point.";
if (oldPos==pos) {
if (pos%2==0) pos++; else pos--;
}
currentPoint=ptsVector.at(pos);
shrink (ptsVector,pointsVectorNew,pos,oldPos);
/** Will be useful later for TSP optimization*/
pointsVectorNew.first().setLoopNbr(nbrClosedPath);
pointsVectorNew.last().setLoopNbr(nbrClosedPath);
if (pointsVectorNew.last()==pointsVectorNew.first()){
tempLoop->setIsClosed(true);
}
else {
// have to inform the caller about error
openLoopError=true;
}
/// @todo as repainting parts is now done succefully we can remove the parts paths list after tests
subLoop=QPainterPath();
/// Repaint the shape point by point tobe used later for collision detection and selection, this only needed for the outline
subLoop.moveTo(pointsVectorNew.at(0));
subLoop.setFillRule(Qt::WindingFill);
for (int f=0; f<pointsVectorNew.size(); f=f+2){
if (pointsVectorNew.at(f).parentType==QPointFWithParent::Arc) {
if (subLoop.currentPosition()!=pointsVectorNew.at(f)) {
//qDebug()<<"1connecting the start point of arc";
subLoop.moveTo(pointsVectorNew.at(f));
}
drawArc(pointsVectorNew.at(f),subLoop);
// qDebug()<<"ended drawin the arc at"<<subLoop.currentPosition();
}
else {
// qDebug()<<"started drawin the line at"<<subLoop.currentPosition();
subLoop.lineTo(pointsVectorNew.at(f+1));
// qDebug()<<"ended drawin the line at"<<subLoop.currentPosition();
}
}
tempLoop=new Loop(this);
tempLoop->addPath(subLoop);
///have now to close the path @todo redraw th path correctly
///@fixme if arc entity have to move back to arc end!
//tempLoop->loopShape.closeSubpath();
///@note:We have to remove the path for the algo to properly work (not just for memory opt)
pathsList.remove(pos/2);
tempLoop->setStart(pointsVectorNew.first());
tempLoop->setEnd(pointsVectorNew.last());
/// @todo: have to add a functionthat count and display differently open loops
tempLoop->setEntities(pointsVectorNew);
///@note: have to call setNumber after setEntitites!!
tempLoop->setNumber(nbrClosedPath);
/** Now the Loop contains all the necessary parameters to define it:
-start point.
-end point.
-Everypoint between the start and end point.
NOte:
- lead-in / lead-out points will be added further if needed.
*/
partLoops<<tempLoop;
/// increment only if it's composed of at least one intersection (not neceraly!!!)
// if (found==1)
nbrClosedPath ++;
pointsVectorNew.clear();
///@todo:differ painting after optimization...
/// tempLoop->nowReady();
tempLoop=new Loop(this);
found=1;
alreadyChecked=false;
pos=newPos(ptsVector);
continue;
}
/// After swapping Points Have found that this point do have a correponding point in another entity
else {
found++;
if (found==2) {
/// to keep the lines order we have to put currentPoint after oldPoint
if (pos%2==0) {oldPos=pos++;} else {oldPos=pos--;}
shrink (ptsVector,pointsVectorNew,pos,oldPos);
tempLoop->addPath(pathsList.at(pos/2));
pathsList.remove(pos/2);
found=1;
}
/// get the corresponding point location and store the caller one to avoid infinte loop
if (ptsVector.indexOf(currentPoint)==pos ) {
pos=ptsVector.lastIndexOf(currentPoint);
}
else {
pos=ptsVector.indexOf(currentPoint);
}
/// change to the other the point definfig the line
if (pos%2==0) pos++; else pos--;
continue;
}
}
/// Found a corresponding point in another entity
else {
found++;
/// It's time to remove the points and their corresponding entities
if (found==2) {
if (pos%2==0) {oldPos=pos++;} else {oldPos=pos--;}
shrink (ptsVector,pointsVectorNew,pos,oldPos);
tempLoop->addPath(pathsList.at(pos/2));
pathsList.remove(pos/2);
found=1;/// we still have one point to work with
}
if (ptsVector.indexOf(currentPoint)==pos ) {
pos=ptsVector.lastIndexOf(currentPoint);
}
else {
pos=ptsVector.indexOf(currentPoint);
}
if (pos%2==0) pos++; else pos--;
alreadyChecked=true;
continue;
}
}
}
void Part::findOutline(){
///@note: we should use controlPointRect which is faster to calculate than boundRect but we already have the boundRect
QRectF outerBound=partLoops[0]->loopShape.boundingRect ();
QRectF outer=partLoops[0]->loopShape.boundingRect ();
for (int pos=0;pos<partLoops.size();pos++){
outer=partLoops[pos]->loopShape.boundingRect ();
if (outerBound.height()* outerBound.width()< outer.height()*outer.width()) {
outerBound=outer;
outlinePos=pos;
}
}
///Remove the outline from the TSp optimization points list
outlinePoint=partLoops.at(outlinePos)->startPoint;
///Move the outline shape to the last position
outLinePath=partLoops.at(outlinePos)->loopShape;
/// partLoops<<partLoops.at(outlinePos);
///partLoops.remove(outlinePos);
///Now the outline is the last element but it kept its loopNumber
///partLoops.last()->setIsOutline(true);
partLoops.at(outlinePos)->setIsOutline(true);
/// To ensu that the outline lead will always stay on top (see bug in lead)
partLoops.last()->setZValue(3);
qDebug()<<"The outline is the " <<outlinePos+1 <<"th element:"<<outlinePoint;
}
// FIXME: Openloops have to be taken into consdideration!
/// When encountering an endPointwhose parentLoop hadalready been assigned a leadwe simplyskip it.(It becomes a leadout).
//We have to deal with two case:
//if the loop is the outline in that case we have to place the lead-in out of it,whereas if
//the loop is an inner one we plae the lead inside it!
/// @todo: have to check not only for the point but for the hole circle!
void Part::generateLeads(){
QPointFWithParent leadPoint;
int myleadDist=leadDist;
QPointFWithParent touchPoint;
QPointFWithParent temp;
bool sucess=false;
errorsFound=false;
Loop *currentLoop;
Lead *templead;
// used to case switch between outiline and inline loops
bool condition=true;
for (int i=0; i<partLoops.size(); i++) {
currentLoop=partLoops.at(i);
temp=currentLoop->startPoint;
qDebug() << "****Searching lead for loop:"<<i<<"starting at "<<temp;
/// @todo: check for circular outline the same as for other shapes!!
// Have to check first for the outline loop
if (!currentLoop->isOutline) {
condition=true;
}
else {
condition=false;
/// When we found the outline we assign it's shape to the part shape!
partOutShape=currentLoop->loopShape;
qDebug()<<"Dealing with the outline";
}
if (currentLoop->isCircle) {
myleadDist=leadDist;
if (temp.parentRadius< leadDist) {
myleadDist=temp.parentRadius/2;
/// @todo Have to mit an alert in status bar and check that supplied minimal radius constarint is met
qDebug() << "the radius is too small!!";
errorsFound= true;
}
///@fixme: replace the startsPoint by leadPoint and see if it influences Optimization
// FOR circle touchPoint become the loop startPoint
touchPoint=temp;
touchPoint.setX(temp.x()+temp.parentRadius*cos((double)leadAngle));
touchPoint.setY(temp.y()+temp.parentRadius*sin((double)leadAngle));
//if the circle is the outline loop
if ( !condition ) {
// The lead point param are user specified
leadPoint.setX(touchPoint.x()+myleadDist*cos((double)leadAngle));
leadPoint.setY(touchPoint.y()+myleadDist*sin((double)leadAngle));
}
else {
leadPoint.setX(temp.x()+myleadDist*cos((double)leadAngle));
leadPoint.setY(temp.y()+myleadDist*sin((double)leadAngle));
}
leadPoint.setParentType(QPointFWithParent::LeadCertain);
currentLoop->setLeadIn(leadPoint);
currentLoop->setTouchPoint(touchPoint);
currentLoop->entities[0].setLeadTouch(touchPoint);
templead=new Lead(currentLoop);
qDebug()<<"Placing a circle lead point N°"<<i;
}
/**maybe an arc or a ruglar line: this is how it works . first we draw a line from rectBound center to
start point. If the line intersect with part shape we reduce the line length (cheking that it's endpoint
is contained in the rectbound.
*/
else{
for (int j=1; j<=10; j++){
/// try to find a valid lead-in point within constrains
leadPoint.setX(temp.x()+leadDist*cos(36*j*M_PI/180));
leadPoint.setY(temp.y()+leadDist*sin(36*j*M_PI/180));
/// @bug loopshape is more precise but it doesn't work =>falling back to boundingrect
//qDebug()<<(currentLoop->loopShape.contains(QPointF(-266.359, 206.586)));
QRectF leadRectapprox=QRectF(leadPoint+QPointF(leadRadius,leadRadius),QSize(2*leadRadius,2*leadRadius));
//if (currentLoop->boundingRect().contains(leadPoint)==condition ){ /// Put intersect here&& !outLinePath.contains(leadPoint)){
if (currentLoop->boundingRect().contains(leadRectapprox)==condition ){
qDebug()<<leadPoint<<j<<"try is a valid lead-in point";
/// if the lead is on an arc it greatly simplifies our job as we simply put the lead on its center
if(temp.parentType==QPointFWithParent::Arc){
// qDebug()<<"The lead is on an arc";
}
leadPoint.setParentType(QPointFWithParent::LeadCertain);
sucess=true;
break;
}
else {
// qDebug()<<j<<"try:"<<leadPoint<<"not a valid point";
}
}
///If we havn't found a valid lead we place a random one with a revelant COLOR
if (!sucess) {
///HAVe to use the parentloop reference to avoid crach when having open loops
///QPointF center= partLoopsListFinal.at(temp.parentLoop).controlPointRect().center();
QPointF center= currentLoop->qtRect.center();
leadPoint.setX(center.x());
leadPoint.setY(center.y());
leadPoint.setParentType(QPointFWithParent::LeadUncertain);
qDebug()<<"placing an uncertain lead point at coor: "<<center;
}
currentLoop->setLeadIn(leadPoint);
///@todo put this from loop filtering by default
currentLoop->setTouchPoint(temp);
templead=new Lead(currentLoop);
}
}
}
/// @ Todo include the outline point and find a way to keep it the last point int he GA cause route length vary greatly
/// with and without it!
void Part::optimizeRoute(){
QPFWPVector bestRoute;
qDebug()<<"Plasma mode="<<plasmaMode<<"With outline loop pos="<<outlinePoint.parentLoop;
/// replaces the points list with the previously created one (inspired from genetic algo)
partLoopsOpt.clear();
QList<int> procededLoops;
/// Prepare the list of points that will be optimized by the GA
for (int i=0;i<partLoops.size();i++){
///If we encounter the outline we skip it (only in plamsa mode) (it should be the last element in partloop
if (partLoops[i]->isOutline && plasmaMode) {qDebug()<<"encountered outline i="<<i;continue;}
bestRoute<<partLoops[i]->startPoint;
/// If the loop is open we need to get the 2 points in the GA
if (partLoops[i]->startPoint!=partLoops[i]->endPoint){
bestRoute<<partLoops[i]->endPoint;
}
}
int j=0;
//while (j<bestRoute.size()) {qDebug()<<bestRoute.at(j).parentLoop<<j;j++;}
//bestRoute.clear();
//bestRoute <<QPointFWithParent(38.24,20.42)<<QPointFWithParent(39.57,26.15)<<QPointFWithParent(40.56,25.32)<<QPointFWithParent(36.26,23.12)<<QPointFWithParent(33.48,10.54)<<QPointFWithParent(37.56,12.19)<<QPointFWithParent(38.42,13.11)<<QPointFWithParent(37.52,20.44)<<QPointFWithParent(41.23,9.10)<<QPointFWithParent(41.17,13.05)<<QPointFWithParent(36.08,-5.21)<<QPointFWithParent(38.47,15.13)<<QPointFWithParent(38.15,15.35)<<QPointFWithParent(37.51,15.17)<<QPointFWithParent(35.49,14.32)<<QPointFWithParent(39.36,19.56);
/// once we have removed the outline, we have to check that we have at least --2-- points to dela with in the GA
if (bestRoute.size()>2) {
if (bestRoute.size()>10) {
QPFWPVector bestRouteP1,bestRouteP2,bestRouteP3,bestRouteP4;
for (int i=0; i<bestRoute.size()/4;i++){
bestRouteP1<<bestRoute.at(i);
}
for (int i=bestRoute.size()/4; i<bestRoute.size()/2;i++){
bestRouteP2<<bestRoute.at(i);
}
for (int i=bestRoute.size()/2; i<bestRoute.size()*3/4;i++){
bestRouteP3<<bestRoute.at(i);
}
for (int i=bestRoute.size()*3/4; i<bestRoute.size();i++){
bestRouteP4<<bestRoute.at(i);
}
qDebug()<<"taille avant"<<bestRoute.size();
Popu *popu=new Popu();
bestRouteP1=popu->init(bestRouteP1,false);
popu=new Popu();
bestRouteP2=popu->init(bestRouteP2,false);
popu=new Popu();
bestRouteP3=popu->init(bestRouteP3,false);
popu=new Popu();
bestRouteP4=popu->init(bestRouteP4,false);
delete popu;
bestRoute.clear();
bestRoute<<bestRouteP1<<bestRouteP2<<bestRouteP3<<bestRouteP4;
}
Popu *popu=new Popu();
/// Fixme work with refenrece to bestRoute
bestRoute=popu->init(bestRoute,false);
tpLength=popu->totalRoute;
qDebug()<<"After GA:"<<tpLength;
delete popu; ///isn't this done automatically as popu is in the if scope ?
}
/// @todo separte this part as an indepandant function
int i=0;
procededLoops.clear();
///TIEME to reorder the Paths the same order as the returned list fromo ptimization
while (i<bestRoute.size()) {
///FIXME: merge before Circles and Points into gcode
if (!procededLoops.contains(bestRoute.at(i).parentLoop)) {
//qDebug()<<"Changing point from pos "<<bestRoute.at(i).parentLoop<<"to position"<<i;
partLoops.at(bestRoute.at(i).parentLoop)->setNumber(i);
partLoopsOpt.append(partLoops.at(bestRoute.at(i).parentLoop));
procededLoops.append(bestRoute.at(i).parentLoop);
}
else {
qDebug()<<"loop"<<i<<" already proceded";
}
i++;
}
/// needed to count the correct toolpath route length in plsams mode
double lastDist=0;
if (plasmaMode){
// HOW could this be possible as we havn't included it ?
if (!procededLoops.contains(outlinePoint.parentLoop)) {
qDebug()<<"Finally the outline "<<outlinePoint.parentLoop<<partLoops.last()->loopNumber;
partLoopsOpt.append(partLoops.at(outlinePos));
// partLoopsOpt.append(partLoops.last());
///HAve to stay the same
//partLoopsOpt.last()->setNumber(
partLoopsOpt.last()->setNumber(partLoopsOpt.size()-1);
lastDist=QLineF(bestRoute.last(),outlinePoint).length();
bestRoute.append(outlinePoint);
}
}
tpLength+=lastDist;
partLoops=partLoopsOpt;
}
Part::~Part(){
}
QVariant Part::itemChange(GraphicsItemChange change, const QVariant &value) {
//qDebug()<<change;
switch (change) {
case ItemPositionHasChanged:
///@todo:We only need to update the matrix when we release the mouse buton check for this before!
transform=sceneTransform();
// qDebug()<<transform.type();
//applyTransform();
qDebug()<<"pos changed"<<partName;
update();
break;
case ItemSelectedHasChanged :
qDebug()<<"Part selected"<<partName;
if (isSelected())
grabKeyboard ();
else
ungrabKeyboard ();
break;
case ItemTransformHasChanged:
transform=sceneTransform();
qDebug()<<transform<<transform.type()<<partName;;
//applyTransform();
///We chnage our matrix
break;
default:
break;
};
return QGraphicsItem::itemChange(change, value);
}
void Part::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
/// When mouse button is released we get the transform matrix
//transform=sceneTransform();
// qDebug()<<"transfor matrix updated"<<transform;
///@todo: see if update() isn't called automatically??
QGraphicsItem::mouseReleaseEvent(event);
}
void Part::moveMeBy(qreal dx, qreal dy){
/// leave the actual move to Qt
qDebug()<<dx<<dy;
moveBy(dx-pos().x(),dy-pos().y());
//setPartPos();
}
void Part::mousePressEvent(QGraphicsSceneMouseEvent *event) {
/// each time update is called the paint function is called
//event->ignore();
//qDebug()<<"mouse pressed piece";
///@todo: see if update() isn't called automatically??
update();//
QGraphicsItem::mousePressEvent(event);
}
void Part::mouseMoveEvent(QGraphicsSceneMouseEvent *event){
//update();
///@todo: see if update() isn't called automatically??
QGraphicsItem::mouseMoveEvent(event);
}
///@todo: have to give the scene the focus on mouse over
void Part::keyPressEvent ( QKeyEvent * keyEvent ){
if (preview) {
keyEvent->ignore();
return;
}
switch (keyEvent->key()) {
case (Qt::Key_Left) :
moveBy(-movePartVal,0);
keyEvent->accept();
break;
case (Qt::Key_Right) :
moveBy(movePartVal,0);
keyEvent->accept();
break;
case (Qt::Key_Down) :
moveBy(0,movePartVal);
keyEvent->accept();
break;
case (Qt::Key_Up) :
moveBy(0,-movePartVal);
keyEvent->accept();
break;
default:
keyEvent->ignore();
return;
}
transform=sceneTransform();
}
///@todo show possible start poits (the user may want to change the lead point for route/space optimization)
Loop::Loop(QGraphicsItem * parent):QGraphicsItem(parent){
loopShape=QPainterPath();
originalShape=QPainterPath();
//addPath(loopText);
selectedPen=QPen(Qt::blue);
unSelectedPen=QPen(settings.value("Colors/pen").value<QColor>());
outlinePen=QPen(Qt::red,Qt::DashLine);
loopNumber=0;
/// @todo: offer the user the possibilty to weither select the outline or the lead ( \n if in plasma mode we only have one choice)
if (plasmaMode) {
//setFlag(ItemIsSelectable);
}
else{
setFlag(ItemIsSelectable);
}
//setCacheMode(DeviceCoordinateCache);
isOutline=false;
isCircle=false;
isClosed=false;
entities.clear();
//loops have to stay under leads
setZValue(1);
ready=false;
///@todo proper intialisationof all valuesstartPoint=
}
void Loop::paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget *){
///start drawing only when the painterPath is defined and all parametres set
if (!ready) {return;}
if (isSelected()) {
myPen=selectedPen;
}
else {
myPen=unSelectedPen;
}
if (isOutline) {
myPen.setStyle(Qt::DashLine);
}
painter->setPen(myPen);
///If no color had been already set
if (settings.value("Options/colorizeInner").toInt()!=2){
painter->setBrush(Qt::NoBrush);
}
else{
painter->setBrush(settings.value("Colors/brush").value<QColor>());
}
//painter->setBrush(Qt::red);
///@note setting the text color won't work as the textpath is merged into the part path
//painter->setBrush(settings.value("Colors/text").value<QColor>());
painter->setFont(settings.value("Fonts/font").value<QFont>());
///@fixme: fonts size are not taken into consideration
painter->drawPath(loopShape);
//painter->fillPath(loopShape,Qt::red);
}
void Loop::addPath(QPainterPath pathToAdd){
loopShape.addPath(pathToAdd);
/// @todo use connect path the correct way !
//loopShape.connectPath(pathToAdd);
prepareGeometryChange();
qtRect=loopShape.boundingRect();
}
void Loop::setEntities(QPFWPVector ts){
entities=ts;
///we save the original shape to avoid alteration when adding text path
originalShape=loopShape;
}
///To avoid adding again and again textpath
void Loop::addTextPath(QPainterPath pathToAdd){
///restore thge original shape
loopShape=originalShape;
prepareGeometryChange();///don't need to updtae rectBound
loopShape.addPath(pathToAdd);
}
/// @Todo: swap the loops numbers
/// @note;as we're using windFilling method the text is granted to be visible over the loop's shape
void Loop::setNumber(int nbr){
loopNumber=nbr;
///shows the loop number @todo:add optioon from gui config
QPainterPath loopText;
///first we erease the previous nuber if any @todo: check for it
///@todo have to devise a way to updta loo number after deleting the old one
//loopText=QPainterPath();
if (isOutline){
loopText.addText(startPoint,QFont("Times", 6),(QString("%1").arg(loopNumber)));
}
else{
///to ensure that selection highlight the loop number we put the number in rect Center
loopText.addText(qtRect.center(),QFont("Times", 6),(QString("%1").arg(loopNumber)));
}
///now we add the loopNumber to the shape to be able to sleect the loop from its number
addTextPath(loopText);
}
QVariant Loop::itemChange(GraphicsItemChange change, const QVariant &value){
switch (change) {
case ItemSelectedHasChanged:
//if (value.toInt()==1)
qDebug()<<"selecting loop n°"<<loopNumber;
update();
break;
default:
break;
}
return QGraphicsItem::itemChange(change, value);
}
/// Setting loop number is achived through swapping values
void Loop::mouseDoubleClickEvent ( QGraphicsSceneMouseEvent * event ){
bool ok;
/// @fixme use QObject::tr-2017-05-31
int i=QInputDialog::getInt(0,QString( "set loop Number"),QString("Loop Number :"), loopNumber, 0, 100, 1, &ok);
if (ok) setNumber(i);
}
QPointFWithParent Part::translateEntity(QPointFWithParent oldPoint, QPointF offset){
QPointFWithParent temp(oldPoint);
temp+=offset;
return temp;
}
void Part::shrink(QPFWPVector &pointsList,QPFWPVector &pointsListNew,int &pos,int &oldPos){
/// push the Two current points into the Qlist of the current path
/// The translation has to be relative not absolute therfor it had to be done
///when the part is inserted in the sheetMetal not before
///pointsListNew <<translateEntity(pointsList.at(pos),offsets.at(currentPart));
///pointsListNew <<translateEntity(pointsList.at(oldPos),offsets.at(currentPart));
pointsListNew<<pointsList.at(pos);
pointsListNew<<pointsList.at(oldPos);
if (oldPos<pos) {
pointsList.remove(oldPos);
pointsList.remove(oldPos);
}
else {
pointsList.remove(pos);
pointsList.remove(pos);
}
return;
}
void Part::drawArc(QPointFWithParent point,QPainterPath &pathToModify) {
QRectF rect(point.centerX-point.parentRadius,point.centerY-point.parentRadius,2*point.parentRadius,2*point.parentRadius);
if (!point.cWise)
pathToModify.arcTo(rect,-(point.angle2),fabs( point.angle1- point.angle2));
else
pathToModify.arcTo(rect,-(point.angle1),-fabs( point.angle1- point.angle2));
//pathToModify.arcMoveTo(rect,-fabs( point.angle1- point.angle2));
}
int Part::newPos(QPFWPVector &pointsList){
int k=0,occurence=0;
while ((k<pointsList.size()) &&(occurence!=1)){
occurence=pointsList.count(pointsList.at(k));
k++;
}
return k-1;
}
LoopThread::LoopThread(Part *piece){
//qDebug()<<"parsing"<<piece->ptsList.size()<<"elements";
currentPiece=piece;
}
void LoopThread::run(){
//currentPiece->optimize();
///isn't there any more elegant way to do this
// filterLoop<<currentPiece->filterLoops();
}
///startJob()
/** @note: Someparts with redendant entities cause the filter loops algo to crash! see 2-0.dxf and 12-0.dxf
Have to wrap that issue*/
| 37.989775 | 529 | 0.603084 | hananiahhsu |
3e513fe8ed2bec4de465f366ba3cebf794f12d86 | 6,056 | cpp | C++ | src/data/cross_sections/collapsed_one_group_cross_sections.cpp | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 12 | 2018-03-14T12:30:53.000Z | 2022-01-23T14:46:44.000Z | src/data/cross_sections/collapsed_one_group_cross_sections.cpp | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 194 | 2017-07-07T01:38:15.000Z | 2021-05-19T18:21:19.000Z | src/data/cross_sections/collapsed_one_group_cross_sections.cpp | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 10 | 2017-07-06T22:58:59.000Z | 2021-03-15T07:01:21.000Z | #include "data/cross_sections/collapsed_one_group_cross_sections.hpp"
#include <numeric>
namespace bart::data::cross_sections {
namespace {
template <typename MappedType> using MaterialIDMappedTo = std::unordered_map<int, MappedType>;
using FullMatrix = dealii::FullMatrix<double>;
auto ScaleVector = [](MaterialIDMappedTo<std::vector<double>> to_scale, MaterialIDMappedTo<std::vector<double>> scaling) {
for (auto& [id, vector] : to_scale) {
for (std::vector<double>::size_type group = 0; group < vector.size(); ++group) {
vector.at(group) *= scaling.at(id).at(group);
}
}
return to_scale;
};
auto collapse_vector = [](MaterialIDMappedTo<std::vector<double>> to_collapse) {
MaterialIDMappedTo<std::vector<double>> return_map;
for (auto& [id, vector] : to_collapse)
return_map[id] = std::vector<double>(1, std::accumulate(vector.cbegin(), vector.cend(), 0.0));
return return_map;
};
auto ScaleMatrix = [](MaterialIDMappedTo<FullMatrix> to_scale, MaterialIDMappedTo<std::vector<double>> scaling) {
for (auto& [id, matrix] : to_scale) {
for (FullMatrix::size_type group = 0; group < matrix.m(); ++group) {
for (FullMatrix::size_type group_in = 0; group_in < matrix.n(); ++group_in) {
matrix(group, group_in) *= scaling.at(id).at(group_in);
}
}
}
return to_scale;
};
auto collapse_matrix = [](MaterialIDMappedTo<FullMatrix> to_collapse) {
MaterialIDMappedTo<FullMatrix> return_map;
for (auto& [id, matrix] : to_collapse) {
return_map[id] = FullMatrix(1, 1);
for (const auto val : matrix)
return_map[id](0, 0) += val;
}
return return_map;
};
} // namespace
CollapsedOneGroupCrossSections::CollapsedOneGroupCrossSections(const CrossSectionsI &to_collapse) {
const auto sigma_s{ to_collapse.sigma_s() };
diffusion_coef_ = collapse_vector(to_collapse.diffusion_coef());
sigma_t_ = collapse_vector(to_collapse.sigma_t());
inverse_sigma_t_ = collapse_vector(to_collapse.inverse_sigma_t());
sigma_s_ = collapse_matrix(sigma_s);
sigma_s_per_ster_ = collapse_matrix(to_collapse.sigma_s_per_ster());
q_ = collapse_vector(to_collapse.q());
q_per_ster_ = collapse_vector(to_collapse.q_per_ster());
is_material_fissile_ = to_collapse.is_material_fissile();
nu_sigma_f_ = collapse_vector(to_collapse.nu_sigma_f());
fiss_transfer_ = collapse_matrix(to_collapse.fiss_transfer());
fiss_transfer_per_ster_ = collapse_matrix(to_collapse.fiss_transfer_per_ster());
const int total_groups = sigma_s.begin()->second.m();
for (const auto& [material_id, sigma_t_vector] : sigma_t_) {
double sigma_absorption{ sigma_t_vector.at(0) };
double sigma_removal{ sigma_absorption };
for (int group = 0; group < total_groups; ++group) {
sigma_removal -= sigma_s.at(material_id)(group, group);
for (int group_in = 0; group_in < total_groups; ++group_in) {
sigma_absorption -= sigma_s.at(material_id)(group, group_in);
}
}
sigma_absorption_[material_id] = sigma_absorption;
sigma_removal_[material_id] = sigma_removal;
}
}
CollapsedOneGroupCrossSections::CollapsedOneGroupCrossSections(
const CrossSectionsI &to_collapse,
const MaterialIDMappedTo<std::vector<double>>& scaling_factor_by_group) {
const auto sigma_s{ to_collapse.sigma_s() };
diffusion_coef_ = collapse_vector(ScaleVector(to_collapse.diffusion_coef(), scaling_factor_by_group));
sigma_t_ = collapse_vector(ScaleVector(to_collapse.sigma_t(), scaling_factor_by_group));
auto inverse_scaling_factor_by_group{ scaling_factor_by_group };
for (auto& pair : inverse_scaling_factor_by_group) {
for (auto& value : pair.second)
value = 1.0/value;
}
//diffusion_coef_ = collapse_vector(ScaleVector(to_collapse.diffusion_coef(), inverse_scaling_factor_by_group));
inverse_sigma_t_ = collapse_vector(ScaleVector(to_collapse.inverse_sigma_t(), inverse_scaling_factor_by_group));
sigma_s_ = collapse_matrix(ScaleMatrix(sigma_s, scaling_factor_by_group));
sigma_s_per_ster_ = collapse_matrix(ScaleMatrix(to_collapse.sigma_s_per_ster(), scaling_factor_by_group));
q_ = collapse_vector(ScaleVector(to_collapse.q(), scaling_factor_by_group));
q_per_ster_ = collapse_vector(ScaleVector(to_collapse.q_per_ster(), scaling_factor_by_group));
is_material_fissile_ = to_collapse.is_material_fissile();
nu_sigma_f_ = collapse_vector(ScaleVector(to_collapse.nu_sigma_f(), scaling_factor_by_group));
MaterialIDMappedTo<FullMatrix> transposed_fiss_transfer;
MaterialIDMappedTo<FullMatrix> transposed_fiss_transfer_per_ster;
const auto fission_transfer = to_collapse.fiss_transfer();
const auto fission_transfer_per_ster = to_collapse.fiss_transfer_per_ster();
for (const auto& [id, matrix] : fission_transfer) {
transposed_fiss_transfer[id] = FullMatrix();
transposed_fiss_transfer.at(id).copy_transposed(matrix);
transposed_fiss_transfer_per_ster[id] = FullMatrix();
transposed_fiss_transfer_per_ster.at(id).copy_transposed(fission_transfer_per_ster.at(id));
}
fiss_transfer_ = collapse_matrix(ScaleMatrix(transposed_fiss_transfer, scaling_factor_by_group));
fiss_transfer_per_ster_ = collapse_matrix(ScaleMatrix(transposed_fiss_transfer_per_ster, scaling_factor_by_group));
const int total_groups = sigma_s.begin()->second.m();
for (const auto& [material_id, sigma_t_vector] : sigma_t_) {
double sigma_absorption{ sigma_t_vector.at(0) };
double sigma_removal{ sigma_absorption };
for (int group = 0; group < total_groups; ++group) {
const double within_group_scattering_{ sigma_s.at(material_id)(group, group) * scaling_factor_by_group.at(material_id).at(group) };
sigma_removal -= within_group_scattering_;
for (int group_in = 0; group_in < total_groups; ++group_in) {
sigma_absorption -= sigma_s.at(material_id)(group, group_in) * scaling_factor_by_group.at(material_id).at(group_in);
}
}
sigma_absorption_[material_id] = sigma_absorption;
sigma_removal_[material_id] = sigma_removal;
}
}
} // namespace bart::data::cross_sections
| 46.229008 | 137 | 0.755614 | SlaybaughLab |
3e531624f296fdd91df69086f4e077ed95c9c4a1 | 62 | cpp | C++ | src/kmer-extern-template.in.cpp | mgawan/mhm2_staging | 0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/kmer-extern-template.in.cpp | mgawan/mhm2_staging | 0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/kmer-extern-template.in.cpp | mgawan/mhm2_staging | 0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "kmer.hpp"
__MACRO_KMER__(@KMER_LENGTH@, template);
| 15.5 | 40 | 0.758065 | mgawan |
3e5e62c2001940be60cf67248c6398755183e760 | 777 | cpp | C++ | Plugins/Tweaks/DisablePause.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 111 | 2018-01-16T18:49:19.000Z | 2022-03-13T12:33:54.000Z | Plugins/Tweaks/DisablePause.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 636 | 2018-01-17T10:05:31.000Z | 2022-03-28T20:06:03.000Z | Plugins/Tweaks/DisablePause.cpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 110 | 2018-01-16T19:05:54.000Z | 2022-03-28T03:44:16.000Z | #include "nwnx.hpp"
#include "API/CServerExoAppInternal.hpp"
namespace Tweaks {
using namespace NWNXLib;
using namespace NWNXLib::API;
void DisablePause() __attribute__((constructor));
void DisablePause()
{
if (!Config::Get<bool>("DISABLE_PAUSE", false))
return;
LOG_INFO("Disabling pausing of the server");
static Hooks::Hook s_SetPauseState_hook = Hooks::HookFunction(Functions::_ZN21CServerExoAppInternal13SetPauseStateEhi,
(void*)+[](CServerExoAppInternal* thisPtr, uint8_t nState, int32_t bPause) -> void
{
// nState=1 - timestop
// nState=2 - DM pause
if (nState != 2)
s_SetPauseState_hook->CallOriginal<void>(thisPtr, nState, bPause);
}, Hooks::Order::Latest);
}
}
| 25.064516 | 122 | 0.661519 | summonFox |
3e63b75ae5ca396efdd052b7976721b0c8b56bce | 1,596 | hpp | C++ | src/seman/analyser.hpp | chirp-language/chirpc | 75657cc99455dd84f01efd3c308e5676dd0c415f | [
"MIT"
] | 10 | 2021-04-04T21:32:32.000Z | 2021-12-11T21:03:35.000Z | src/seman/analyser.hpp | chirp-language/chirpc | 75657cc99455dd84f01efd3c308e5676dd0c415f | [
"MIT"
] | 6 | 2021-04-05T15:19:19.000Z | 2022-02-21T02:15:35.000Z | src/seman/analyser.hpp | chirp-language/chirpc | 75657cc99455dd84f01efd3c308e5676dd0c415f | [
"MIT"
] | 2 | 2021-04-05T17:24:06.000Z | 2021-04-27T21:20:34.000Z | /// \file Semantic analyser and AST walker
#pragma once
#include "../ast/ast.hpp"
#include "tracker.hpp"
class analyser
{
public:
analyser(ast_root& root, diagnostic_manager& diag)
: root(root), sym_tracker(diag), diagnostics(diag)
{
sym_tracker.set_root(&root);
}
void analyse();
protected:
ast_root& root;
tracker sym_tracker;
diagnostic_manager& diagnostics;
void visit_expr(expr& node);
void visit_decl(decl& node);
void visit_stmt(stmt& node);
// Expressions
void visit_basic_type(basic_type&) = delete;
void visit_binop(binop&);
void visit_unop(unop&);
void visit_arguments(arguments&);
void visit_func_call(func_call&);
void visit_id_ref_expr(id_ref_expr&);
void visit_loperand(loperand&) = delete;
void visit_string_literal(string_literal&);
void visit_integral_literal(integral_literal&);
void visit_nullptr_literal(nullptr_literal&);
void visit_cast_expr(cast_expr&);
// Declarations
void visit_var_decl(var_decl&);
void visit_entry_decl(entry_decl&);
void visit_import_decl(import_decl&);
void visit_extern_decl(extern_decl&);
void visit_namespace_decl(namespace_decl&);
void visit_parameters(parameters&);
void visit_func_decl(func_decl&);
void visit_func_def(func_def&);
// Statements
void visit_decl_stmt(decl_stmt&);
void visit_assign_stmt(assign_stmt&);
void visit_compound_stmt(compound_stmt&);
void visit_ret_stmt(ret_stmt&);
void visit_conditional_stmt(conditional_stmt&);
void visit_iteration_stmt(iteration_stmt&);
void visit_expr_stmt(expr_stmt&);
void visit_null_stmt(stmt&); // null_stmt contains no further members
};
| 27.050847 | 70 | 0.780075 | chirp-language |
3e6aa27a36b4bfdd872bc7f8c74226ea4aebf095 | 4,361 | cpp | C++ | ClassicShellSrc/ClassicIE/ClassicIEDLL/dllmain.cpp | coddec/Classic-Shell | e3f6602abbca4b7d7c147171c5c280f1740270d0 | [
"MIT"
] | 664 | 2017-12-04T15:01:44.000Z | 2022-03-27T13:07:37.000Z | ClassicShellSrc/ClassicIE/ClassicIEDLL/dllmain.cpp | Open343/Classic-Shell | e3f6602abbca4b7d7c147171c5c280f1740270d0 | [
"MIT"
] | 36 | 2017-12-05T02:40:34.000Z | 2022-02-09T23:53:16.000Z | ClassicShellSrc/ClassicIE/ClassicIEDLL/dllmain.cpp | Open343/Classic-Shell | e3f6602abbca4b7d7c147171c5c280f1740270d0 | [
"MIT"
] | 217 | 2017-12-04T14:01:07.000Z | 2022-03-26T10:25:39.000Z | // Classic Shell (c) 2009-2016, Ivo Beltchev
// Confidential information of Ivo Beltchev. Not for disclosure or distribution without prior written consent from the author
#include "stdafx.h"
#include "resource.h"
#include "..\..\ClassicShellLib\resource.h"
#include "Settings.h"
#include "SettingsUI.h"
#include "SettingsUIHelper.h"
#include "DownloadHelper.h"
#include "Translations.h"
#include "ResourceHelper.h"
#include "dllmain.h"
#include "ClassicIEDLL.h"
#pragma comment(linker, \
"\"/manifestdependency:type='Win32' "\
"name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' "\
"processorArchitecture='*' "\
"publicKeyToken='6595b64144ccf1df' "\
"language='*'\"")
CClassicIEDLLModule _AtlModule;
static int g_LoadDialogs[]=
{
IDD_SETTINGS,0x04000000,
IDD_SETTINGSTREE,0x04000000,
IDD_LANGUAGE,0x04000000,
IDD_PROGRESS,0x04000004,
0
};
const wchar_t *GetDocRelativePath( void )
{
return DOC_PATH;
}
static void NewVersionCallback( VersionData &data )
{
wchar_t path[_MAX_PATH];
GetModuleFileName(g_Instance,path,_countof(path));
PathRemoveFileSpec(path);
PathAppend(path,L"ClassicShellUpdate.exe");
wchar_t cmdLine[1024];
Sprintf(cmdLine,_countof(cmdLine),L"\"%s\" -popup",path);
STARTUPINFO startupInfo={sizeof(startupInfo)};
PROCESS_INFORMATION processInfo;
memset(&processInfo,0,sizeof(processInfo));
if (CreateProcess(path,cmdLine,NULL,NULL,TRUE,0,NULL,NULL,&startupInfo,&processInfo))
{
CloseHandle(processInfo.hThread);
CloseHandle(processInfo.hProcess);
}
}
CSIEAPI void CheckForNewVersionIE( void )
{
CheckForNewVersion(NULL,COMPONENT_IE,CHECK_AUTO_WAIT,NewVersionCallback);
}
static HANDLE g_DllInitThread;
static DWORD CALLBACK DllInitThread( void* )
{
InitSettings();
CString language=GetSettingString(L"Language");
ParseTranslations(NULL,language);
HINSTANCE resInstance=LoadTranslationDll(language);
LoadTranslationResources(resInstance,g_LoadDialogs);
if (resInstance)
FreeLibrary(resInstance);
InitClassicIE(g_Instance);
return 0;
}
CSIEAPI void WaitDllInitThread( void )
{
ATLASSERT(g_DllInitThread);
WaitForSingleObject(g_DllInitThread,INFINITE);
}
CSIEAPI void DllLogToFile( const wchar_t *location, const wchar_t *message, ... )
{
va_list args;
va_start(args,message);
VLogToFile(location,message,args);
va_end(args);
}
#ifndef _WIN64
CSIEAPI bool DllSaveAdmx( const char *admxFile, const char *admlFile, const char *docFile, const wchar_t *language )
{
WaitDllInitThread();
HMODULE dll=NULL;
if (language[0])
{
wchar_t path[_MAX_PATH];
GetCurrentDirectory(_countof(path),path);
PathAppend(path,language);
PathAddExtension(path,L".dll");
dll=LoadLibraryEx(path,NULL,LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE);
}
LoadTranslationResources(dll,NULL);
return SaveAdmx(COMPONENT_IE,admxFile,admlFile,docFile);
}
#endif
CSIEAPI bool DllImportSettingsXml( const wchar_t *fname )
{
return ImportSettingsXml(fname);
}
CSIEAPI bool DllExportSettingsXml( const wchar_t *fname )
{
return ExportSettingsXml(fname);
}
// DLL Entry Point
extern "C" BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved )
{
if (dwReason==DLL_PROCESS_ATTACH)
{
wchar_t path[_MAX_PATH];
GetModuleFileName(NULL,path,_countof(path));
const wchar_t *exe=PathFindFileName(path);
if (_wcsicmp(exe,L"explorer.exe")==0) return FALSE;
if (_wcsicmp(exe,L"iexplore.exe")==0)
{
DWORD version=GetVersionEx(GetModuleHandle(NULL));
if (version<0x09000000) return FALSE;
CRegKey regSettings, regSettingsUser, regPolicy, regPolicyUser;
bool bUpgrade=OpenSettingsKeys(COMPONENT_EXPLORER,regSettings,regSettingsUser,regPolicy,regPolicyUser);
CSetting settings[]={
{L"ShowCaption",CSetting::TYPE_BOOL,0,0,1},
{L"ShowProgress",CSetting::TYPE_BOOL,0,0,1},
{L"ShowZone",CSetting::TYPE_BOOL,0,0,1},
{NULL}
};
settings[0].LoadValue(regSettings,regSettingsUser,regPolicy,regPolicyUser);
settings[1].LoadValue(regSettings,regSettingsUser,regPolicy,regPolicyUser);
settings[2].LoadValue(regSettings,regSettingsUser,regPolicy,regPolicyUser);
if (!GetSettingBool(settings[0]) && !GetSettingBool(settings[1]) && !GetSettingBool(settings[2])) return FALSE;
}
g_Instance=hInstance;
g_DllInitThread=CreateThread(NULL,0,DllInitThread,NULL,0,NULL);
}
return _AtlModule.DllMain(dwReason, lpReserved);
}
| 27.086957 | 125 | 0.766797 | coddec |
3e6b529b1e6db4a29ea2fc01a9441545cc368ae5 | 2,717 | cpp | C++ | AEngine/src/Application/Application.cpp | alife1029/AEngine | ecf181948fc90690c7fe2fba7792f29441b445d7 | [
"MIT"
] | 1 | 2022-01-17T19:01:14.000Z | 2022-01-17T19:01:14.000Z | AEngine/src/Application/Application.cpp | alife1029/AEngine | ecf181948fc90690c7fe2fba7792f29441b445d7 | [
"MIT"
] | null | null | null | AEngine/src/Application/Application.cpp | alife1029/AEngine | ecf181948fc90690c7fe2fba7792f29441b445d7 | [
"MIT"
] | null | null | null | #include "AEngine/Application/Application.hpp"
#include "AEngine/Application/FileDialogs.hpp"
#include "AEngine/Input/Input.hpp"
#include "AEngine/Graphics/Renderer2D.hpp"
#include "AEngine/Exception/OpenGLException.hpp"
#include "AEngine/Utils/Time.hpp"
#include "AEngine/Utils/Logger.hpp"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <thread>
#include <chrono>
namespace aengine
{
Application::Application(const AppConfig& config)
{
m_MainCamera = nullptr;
m_Window = new Window(config.scrWidth, config.scrHeight, config.title, config.fullScreen);
if (config.vSync) glfwSwapInterval(1);
FileDialog::window = m_Window->m_GlfwWindow;
SetEventListener(this);
Input::mEventSystem = &mEventSystem;
Renderer2D::Init();
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
Application::~Application()
{
Renderer2D::Shutdown();
Window::TerminateGLFW();
}
void Application::Run()
{
// Run start method before first frame
Start();
// Main loop
while(m_Window->IsOpen())
{
mEventSystem.Flush();
m_Window->PollEvents();
m_Window->Clear();
Renderer2D::Begin(m_MainCamera != nullptr ? m_MainCamera->Combined() : glm::mat4(1.0f));
Update();
if (m_MainCamera != nullptr) m_MainCamera->Update();
Renderer2D::End();
Renderer2D::Flush();
Renderer2D::ResetStats();
m_Window->SwapBuffers();
// Check OpenGL errors
GLenum errCode = glGetError();
if (errCode && focused)
ThrowOpenGLException(errCode);
Time::Update();
}
Dispose();
}
void Application::BindMainCamera(OrthographicCamera* camera) noexcept
{
m_MainCamera = camera;
}
OrthographicCamera* Application::GetMainCamera() const noexcept
{
return m_MainCamera;
}
void Application::Start() { }
void Application::Update() { }
void Application::Dispose() { }
// Updates viewport on window resized
void Application::OnResize(int width, int height)
{
glViewport(0, 0, width, height);
}
void Application::OnFocus(bool focused)
{
this->focused = focused;
}
GLFWwindow* Application::GetGLFWwindow()
{
return m_Window->m_GlfwWindow;
}
bool Application::IsFocused()
{
return focused;
}
}
| 24.926606 | 101 | 0.576739 | alife1029 |
3e7433af3c52925501585f4517369d8b0847664d | 7,622 | cpp | C++ | source/tests/liblocate-test/liblocate_test.cpp | ekilmer/cpplocate | cea23645a43ee3222a34efa2bf972e08638e97bd | [
"MIT"
] | null | null | null | source/tests/liblocate-test/liblocate_test.cpp | ekilmer/cpplocate | cea23645a43ee3222a34efa2bf972e08638e97bd | [
"MIT"
] | null | null | null | source/tests/liblocate-test/liblocate_test.cpp | ekilmer/cpplocate | cea23645a43ee3222a34efa2bf972e08638e97bd | [
"MIT"
] | null | null | null |
#include <gmock/gmock.h>
#include <liblocate/liblocate.h>
class liblocate_test : public testing::Test
{
public:
liblocate_test()
{
}
};
TEST_F(liblocate_test, getExecutablePath_NoReturn)
{
getExecutablePath(nullptr, nullptr);
SUCCEED();
}
TEST_F(liblocate_test, getExecutablePath_Return)
{
char * executablePath = 0x0;
unsigned int length = 0;
getExecutablePath(&executablePath, &length);
EXPECT_LT(0, length);
ASSERT_FALSE(executablePath == 0x0);
EXPECT_EQ(0, executablePath[length]);
EXPECT_EQ(length, strlen(executablePath));
free(executablePath);
}
TEST_F(liblocate_test, getBundlePath_NoReturn)
{
getBundlePath(nullptr, nullptr);
SUCCEED();
}
TEST_F(liblocate_test, getBundlePath_Return)
{
#ifdef SYSTEM_DARWIN
char * bundlePath = 0x0;
unsigned int length = 0;
getBundlePath(&bundlePath, &length);
EXPECT_LT(0, length);
ASSERT_FALSE(bundlePath == 0x0);
EXPECT_EQ(0, bundlePath[length]);
EXPECT_EQ(length, strlen(bundlePath));
free(bundlePath);
#else
SUCCEED();
#endif
}
TEST_F(liblocate_test, getModulePath_NoReturn)
{
getModulePath(nullptr, nullptr);
SUCCEED();
}
TEST_F(liblocate_test, getModulePath_Return)
{
char * modulePath = 0x0;
unsigned int length = 0;
getModulePath(&modulePath, &length);
EXPECT_LT(0, length);
ASSERT_FALSE(modulePath == 0x0);
EXPECT_EQ(0, modulePath[length]);
EXPECT_EQ(length, strlen(modulePath));
free(modulePath);
}
TEST_F(liblocate_test, getLibraryPath_NoReturn)
{
getLibraryPath(reinterpret_cast<void*>(getExecutablePath), nullptr, nullptr);
SUCCEED();
}
TEST_F(liblocate_test, getLibraryPath_Return)
{
char * libraryPath = 0x0;
unsigned int length = 0;
getLibraryPath(reinterpret_cast<void*>(getExecutablePath), &libraryPath, &length);
EXPECT_LT(0, length);
ASSERT_FALSE(libraryPath == 0x0);
EXPECT_EQ(0, libraryPath[length]);
EXPECT_EQ(length, strlen(libraryPath));
free(libraryPath);
}
TEST_F(liblocate_test, locatePath_NoReturn)
{
const char * relPath = "source/version.h.in";
const char * systemPath = "share/liblocate";
locatePath(nullptr, nullptr, relPath, strlen(relPath), systemPath, strlen(systemPath), reinterpret_cast<void*>(getExecutablePath)); // 111
locatePath(nullptr, nullptr, relPath, strlen(relPath), systemPath, strlen(systemPath), nullptr); // 110
locatePath(nullptr, nullptr, relPath, strlen(relPath), nullptr, 0, reinterpret_cast<void*>(getExecutablePath)); // 101
locatePath(nullptr, nullptr, relPath, strlen(relPath), nullptr, 0, nullptr); // 100
locatePath(nullptr, nullptr, nullptr, 0, systemPath, strlen(systemPath), reinterpret_cast<void*>(getExecutablePath)); // 011
locatePath(nullptr, nullptr, nullptr, 0, systemPath, strlen(systemPath), nullptr); // 010
locatePath(nullptr, nullptr, nullptr, 0, nullptr, 0, reinterpret_cast<void*>(getExecutablePath)); // 001
locatePath(nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr); // 000
SUCCEED();
}
TEST_F(liblocate_test, locatePath_Return)
{
char * path = 0x0;
unsigned int length = 0;
const char * relPath = "source/version.h.in";
const char * systemPath = "share/liblocate";
locatePath(&path, &length, relPath, strlen(relPath), systemPath, strlen(systemPath), reinterpret_cast<void*>(getExecutablePath));
EXPECT_LT(0, length);
ASSERT_FALSE(path == 0x0);
EXPECT_EQ(0, path[length]);
EXPECT_EQ(length, strlen(path));
free(path);
}
TEST_F(liblocate_test, locatePath_ReturnNoSymbol)
{
char * path = 0x0;
unsigned int length = 0;
const char * relPath = "source/version.h.in";
const char * systemPath = "share/liblocate";
locatePath(&path, &length, relPath, strlen(relPath), systemPath, strlen(systemPath), nullptr);
EXPECT_LT(0, length);
ASSERT_FALSE(path == 0x0);
EXPECT_EQ(0, path[length]);
EXPECT_EQ(length, strlen(path));
free(path);
}
TEST_F(liblocate_test, locatePath_ReturnNoSystemDir)
{
char * path = 0x0;
unsigned int length = 0;
const char * relPath = "source/version.h.in";
locatePath(&path, &length, relPath, strlen(relPath), nullptr, 0, reinterpret_cast<void*>(getExecutablePath));
EXPECT_LT(0, length);
ASSERT_FALSE(path == 0x0);
EXPECT_EQ(0, path[length]);
EXPECT_EQ(length, strlen(path));
free(path);
}
TEST_F(liblocate_test, pathSeparator_NoReturn)
{
pathSeparator(nullptr);
SUCCEED();
}
TEST_F(liblocate_test, pathSeparator_Return)
{
char sep = 0;
pathSeparator(&sep);
#ifdef WIN32
ASSERT_EQ('\\', sep);
#elif __APPLE__
ASSERT_EQ('/', sep);
#else
ASSERT_EQ('/', sep);
#endif
}
TEST_F(liblocate_test, libPrefix_NoReturn)
{
libPrefix(nullptr, nullptr);
SUCCEED();
}
TEST_F(liblocate_test, libPrefix_Return)
{
char * prefix;
unsigned int length;
libPrefix(&prefix, &length);
#ifdef WIN32
EXPECT_EQ(0, length);
ASSERT_NE(nullptr, prefix);
EXPECT_STREQ("", prefix);
#elif __APPLE__
EXPECT_EQ(0, length);
ASSERT_NE(nullptr, prefix);
EXPECT_STREQ("", prefix);
#else
EXPECT_EQ(3, length);
ASSERT_NE(nullptr, prefix);
EXPECT_STREQ("lib", prefix);
#endif
free(prefix);
}
TEST_F(liblocate_test, libExtension_NoReturn)
{
libExtension(nullptr, nullptr);
SUCCEED();
}
TEST_F(liblocate_test, libExtension_Return)
{
char * extension;
unsigned int length;
libExtension(&extension, &length);
#ifdef WIN32
EXPECT_EQ(3, length);
ASSERT_NE(nullptr, extension);
EXPECT_STREQ("dll", extension);
#elif __APPLE__
EXPECT_EQ(5, length);
ASSERT_NE(nullptr, extension);
EXPECT_STREQ("dylib", extension);
#else
EXPECT_EQ(2, length);
ASSERT_NE(nullptr, extension);
EXPECT_STREQ("so", extension);
#endif
free(extension);
}
TEST_F(liblocate_test, libExtensions_NoReturn)
{
libExtensions(nullptr, nullptr, nullptr);
SUCCEED();
}
TEST_F(liblocate_test, libExtensions_Return)
{
char ** extensions;
unsigned int * lengths;
unsigned int count;
unsigned int i;
libExtensions(&extensions, &lengths, &count);
#ifdef WIN32
EXPECT_EQ(1, count);
ASSERT_NE(nullptr, lengths);
EXPECT_EQ(3, lengths[0]);
ASSERT_NE(nullptr, extensions);
ASSERT_NE(nullptr, extensions[0]);
EXPECT_STREQ("dll", extensions[0]);
#elif __APPLE__
EXPECT_EQ(2, count);
ASSERT_NE(nullptr, lengths);
EXPECT_EQ(5, lengths[0]);
ASSERT_NE(nullptr, extensions);
ASSERT_NE(nullptr, extensions[0]);
EXPECT_STREQ("dylib", extensions[0]);
#else
EXPECT_EQ(1, count);
ASSERT_NE(nullptr, lengths);
EXPECT_EQ(2, lengths[0]);
ASSERT_NE(nullptr, extensions);
ASSERT_NE(nullptr, extensions[0]);
EXPECT_STREQ("so", extensions[0]);
#endif
for (i = 0; i < count; ++i)
{
free(extensions[i]);
}
free(lengths);
free(extensions);
}
TEST_F(liblocate_test, homeDir)
{
char * dir;
unsigned int length;
homeDir(&dir, &length);
EXPECT_NE(nullptr, dir);
EXPECT_LE(0, length);
free(dir);
}
| 23.81875 | 142 | 0.639596 | ekilmer |
3e7481889a22e921314be87377388e0fdbd0d3c6 | 633 | cpp | C++ | app/flite_main/flite_lang_list.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | 7 | 2017-12-10T23:02:22.000Z | 2021-08-05T21:12:11.000Z | app/flite_main/flite_lang_list.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | null | null | null | app/flite_main/flite_lang_list.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | 3 | 2018-10-28T03:47:09.000Z | 2020-06-04T08:54:23.000Z | /* Generated automatically from make_lang_list */
#include "flite/flite.hpp"
void usenglish_init(cst_voice* v);
cst_lexicon* cmulex_init(void);
void cmu_indic_lang_init(cst_voice* v);
cst_lexicon* cmu_indic_lex_init(void);
void cmu_grapheme_lang_init(cst_voice* v);
cst_lexicon* cmu_grapheme_lex_init(void);
void flite_set_lang_list(void)
{
flite_add_lang("eng", usenglish_init, cmulex_init);
flite_add_lang("usenglish", usenglish_init, cmulex_init);
flite_add_lang("cmu_indic_lang", cmu_indic_lang_init, cmu_indic_lex_init);
flite_add_lang("cmu_grapheme_lang", cmu_grapheme_lang_init, cmu_grapheme_lex_init);
}
| 30.142857 | 87 | 0.802528 | Barath-Kannan |
3e76addaf7ec86435435700adc7913da1a86b384 | 1,342 | cpp | C++ | src/PointwiseFunctions/AnalyticData/Burgers/Sinusoid.cpp | kidder/spectre | 97ae95f72320f9f67895d3303824e64de6fd9077 | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/PointwiseFunctions/AnalyticData/Burgers/Sinusoid.cpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/PointwiseFunctions/AnalyticData/Burgers/Sinusoid.cpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "PointwiseFunctions/AnalyticData/Burgers/Sinusoid.hpp"
#include <array>
#include <cmath>
#include "DataStructures/DataVector.hpp" // IWYU pragma: keep
#include "DataStructures/Tensor/Tensor.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Math.hpp" // IWYU pragma: keep
// IWYU pragma: no_forward_declare Tensor
namespace Burgers::AnalyticData {
template <typename T>
Scalar<T> Sinusoid::u(const tnsr::I<T, 1>& x) const {
return Scalar<T>{sin(get<0>(x))};
}
tuples::TaggedTuple<Tags::U> Sinusoid::variables(
const tnsr::I<DataVector, 1>& x, tmpl::list<Tags::U> /*meta*/) const {
return {u(x)};
}
void Sinusoid::pup(PUP::er& /*p*/) {}
bool operator==(const Sinusoid& /*lhs*/, const Sinusoid& /*rhs*/) {
return true;
}
bool operator!=(const Sinusoid& lhs, const Sinusoid& rhs) {
return not(lhs == rhs);
}
} // namespace Burgers::AnalyticData
#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)
#define INSTANTIATE(_, data) \
template Scalar<DTYPE(data)> Burgers::AnalyticData::Sinusoid::u( \
const tnsr::I<DTYPE(data), 1>& x) const;
GENERATE_INSTANTIATIONS(INSTANTIATE, (double, DataVector))
#undef DTYPE
#undef INSTANTIATE
| 27.387755 | 74 | 0.694486 | kidder |
3e77c850f0c8469c442df61295e3224ee303e0ac | 5,407 | cpp | C++ | source/typecheck/traits.cpp | requimrar/corescript | 9c46e51d898337df2e7f88250f314c177401d154 | [
"Apache-2.0"
] | 168 | 2015-01-27T15:22:08.000Z | 2021-12-03T15:07:04.000Z | source/typecheck/traits.cpp | requimrar/corescript | 9c46e51d898337df2e7f88250f314c177401d154 | [
"Apache-2.0"
] | 32 | 2015-01-28T14:53:09.000Z | 2020-12-02T10:37:04.000Z | source/typecheck/traits.cpp | requimrar/corescript | 9c46e51d898337df2e7f88250f314c177401d154 | [
"Apache-2.0"
] | 18 | 2015-06-08T20:45:32.000Z | 2021-12-19T14:07:32.000Z | // traits.cpp
// Copyright (c) 2019, zhiayang
// Licensed under the Apache License Version 2.0.
#include "ast.h"
#include "errors.h"
#include "typecheck.h"
#include "polymorph.h"
#include "memorypool.h"
#include "ir/type.h"
TCResult ast::TraitDefn::generateDeclaration(sst::TypecheckState* fs, fir::Type* infer, const TypeParamMap_t& gmaps)
{
fs->pushLoc(this);
defer(fs->popLoc());
auto [ success, ret ] = this->checkForExistingDeclaration(fs, gmaps);
if(!success) return TCResult::getParametric();
else if(ret) return TCResult(ret);
auto defnname = util::typeParamMapToString(this->name, gmaps);
auto defn = util::pool<sst::TraitDefn>(this->loc);
defn->bareName = this->name;
defn->attrs = this->attrs;
defn->id = Identifier(defnname, IdKind::Type);
defn->id.scope = this->enclosingScope;
defn->visibility = this->visibility;
defn->original = this;
defn->enclosingScope = this->enclosingScope;
defn->innerScope = this->enclosingScope.appending(defnname);
// make all our methods be methods
for(auto m : this->methods)
{
m->parentType = this;
m->enclosingScope = defn->innerScope;
}
auto str = fir::TraitType::create(defn->id.convertToName());
defn->type = str;
if(auto err = fs->checkForShadowingOrConflictingDefinition(defn, [](auto, auto) -> bool { return true; }))
return TCResult(err);
// add it first so we can use it in the method bodies,
// and make pointers to it
{
defn->enclosingScope.stree->addDefinition(defnname, defn, gmaps);
fs->typeDefnMap[str] = defn;
}
this->genericVersions.push_back({ defn, fs->getGenericContextStack() });
return TCResult(defn);
}
TCResult ast::TraitDefn::typecheck(sst::TypecheckState* fs, fir::Type* infer, const TypeParamMap_t& gmaps)
{
fs->pushLoc(this);
defer(fs->popLoc());
auto tcr = this->generateDeclaration(fs, infer, gmaps);
if(tcr.isParametric()) return tcr;
auto defn = dcast(sst::TraitDefn, tcr.defn());
iceAssert(defn);
if(this->finishedTypechecking.find(defn) != this->finishedTypechecking.end())
return TCResult(defn);
auto trt = defn->type->toTraitType();
iceAssert(trt);
fs->teleportInto(defn->innerScope);
fs->pushSelfContext(trt);
std::vector<std::pair<std::string, fir::FunctionType*>> meths;
for(auto m : this->methods)
{
// make sure we don't have bodies -- for now!
iceAssert(m->body == 0);
auto res = m->generateDeclaration(fs, 0, { });
if(res.isParametric())
continue;
auto decl = dcast(sst::FunctionDecl, res.defn());
iceAssert(decl);
defn->methods.push_back(decl);
meths.push_back({ m->name, decl->type->toFunctionType() });
}
trt->setMethods(meths);
fs->popSelfContext();
fs->teleportOut();
this->finishedTypechecking.insert(defn);
return TCResult(defn);
}
// used by typecheck/structs.cpp and typecheck/classes.cpp
static bool _checkFunctionTypesMatch(fir::Type* trait, fir::Type* type, fir::FunctionType* required, fir::FunctionType* candidate)
{
auto as = required->getArgumentTypes() + required->getReturnType();
auto bs = candidate->getArgumentTypes() + candidate->getReturnType();
// all candidates must have a self!!
iceAssert(as.size() > 0 && bs.size() > 0);
if(as.size() != bs.size())
return false;
for(size_t i = 0; i < as.size(); i++)
{
auto ax = as[i];
auto bx = bs[i];
// TODO: wtf is this doing?!
if(ax != bx)
{
auto [ abase, atrfs ] = sst::poly::internal::decomposeIntoTransforms(ax, SIZE_MAX);
auto [ bbase, btrfs ] = sst::poly::internal::decomposeIntoTransforms(bx, SIZE_MAX);
if(atrfs != btrfs)
return false;
if(abase != trait || bbase != type)
return false;
}
}
return true;
}
// TODO: needs to handle extensions!!!
void checkTraitConformity(sst::TypecheckState* fs, sst::TypeDefn* defn)
{
std::vector<sst::TraitDefn*> traits;
util::hash_map<std::string, std::vector<sst::FunctionDecl*>> methods;
if(auto cls = dcast(sst::ClassDefn, defn))
{
for(auto m : cls->methods)
methods[m->id.name].push_back(m);
error("wait a bit");
}
else if(auto str = dcast(sst::StructDefn, defn))
{
for(auto m : str->methods)
methods[m->id.name].push_back(m);
traits = str->traits;
}
else
{
return;
}
// make this a little less annoying: report errors by trait, so all the missing methods for a trait are given at once
for(auto trait : traits)
{
std::vector<std::tuple<Location, std::string, fir::FunctionType*>> missings;
for(auto meth : trait->methods)
{
auto cands = methods[meth->id.name];
bool found = false;
for(auto cand : cands)
{
// c++ really fucking needs named arguments!!
if(_checkFunctionTypesMatch(trait->type, defn->type,
/* required: */ meth->type->toFunctionType(),
/* candidate: */ cand->type->toFunctionType()
))
{
found = true;
break;
}
}
if(!found)
missings.push_back({ meth->loc, meth->id.name, meth->type->toFunctionType() });
}
if(missings.size() > 0)
{
auto err = SimpleError::make(defn->loc, "type '%s' does not conform to trait '%s'",
defn->id.name, trait->id.name);
for(const auto& m : missings)
{
err->append(SimpleError::make(MsgType::Note, std::get<0>(m), "missing implementation for method '%s': %s:",
std::get<1>(m), std::get<2>(m)));
}
err->append(
SimpleError::make(MsgType::Note, trait->loc, "trait '%s' was defined here:", trait->id.name)
)->postAndQuit();
}
}
}
| 23.206009 | 130 | 0.664509 | requimrar |
3e7c1f90cd6271fbb503b4359b80505d8fe18f93 | 2,875 | cpp | C++ | shared/Packet.cpp | RamseyK/jkchat | 72b7b93655850d9e72d600ef185eda779aa9ba82 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | shared/Packet.cpp | RamseyK/jkchat | 72b7b93655850d9e72d600ef185eda779aa9ba82 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | shared/Packet.cpp | RamseyK/jkchat | 72b7b93655850d9e72d600ef185eda779aa9ba82 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /**
jkchat
Packet.cpp
Copyright 2011 Ramsey Kant, Keilan Jackson
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 "Packet.h"
/**
* Packet Constructor (size)
* Accepts an initial size to preallocate in the backing ByteBuffer.
* This constructor is used when a new packet needs to be created and built
*
* @param size Size to pass to the backing ByteBuffer. Memory of size will be preallocated
*/
Packet::Packet(unsigned int size) : ByteBuffer(size) {
opCode = 0;
createData = NULL;
}
/**
* Packet Constructor (data, size)
* Accepts an initial byte array and size to populate the backing ByteBuffer of the packet. Reads in the opcode from the byte array
* This constructor is used when a new PROTOCOL packet is recieved over the wire and must be consumed by the Packet class for further manipulation
*
* @param data byte Array of packet to consume in the packet structure
* @param size Size of the byte array
*/
Packet::Packet(byte *data, unsigned int size) : ByteBuffer(data, size) {
opCode = get();
createData = NULL;
}
/**
* Packet Deconstructor
*/
Packet::~Packet() {
if(createData != NULL) {
delete createData;
createData = NULL;
}
}
/**
* Get Opcode
* Return's the opcode of the packet
*/
byte Packet::getOpcode() {
return opCode;
}
/**
* Check Create
* Checks if cached data from previous create() calls is available
*
* @param force If force is true, createData should be destroyed and the buffer cleared for an upcoming rebuild in create().
* @return Return true if cached data is available, false if otherwise
*/
bool Packet::checkCreate(bool force) {
// If force is true, packet is required to flush and rebuilt itself (cannot use cached data)
if(force) {
if(createData != NULL) {
delete createData;
createData = NULL;
}
clear();
} else { // If cached data from a previous create() call exists
if(createData != NULL)
return true;
}
return false;
}
/**
* Save Create
* Cache's the current contents of the byte buffer in createData for future calls of create()
*/
void Packet::saveCreate() {
// Create a byte array to return
createData = new byte[size()];
// Set read position to beginning of ByteBuffer
setReadPos(0);
// Fill the byte array with the usable data in the ByteBuffer (position 0 to size())
getBytes(createData, size());
}
| 29.040404 | 146 | 0.70887 | RamseyK |
3e7e6c0ece5aca64475ada894ec0da9cbecd7238 | 762 | cpp | C++ | src/VoxerEngine/Math/ChunkPosition.cpp | cLazyZombie/wasmgl | 68f7cab5bab01d8f00a73c5d32d2d2f9ba6185a9 | [
"MIT"
] | null | null | null | src/VoxerEngine/Math/ChunkPosition.cpp | cLazyZombie/wasmgl | 68f7cab5bab01d8f00a73c5d32d2d2f9ba6185a9 | [
"MIT"
] | null | null | null | src/VoxerEngine/Math/ChunkPosition.cpp | cLazyZombie/wasmgl | 68f7cab5bab01d8f00a73c5d32d2d2f9ba6185a9 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "ChunkPosition.h"
namespace VoxerEngine
{
ChunkPosition::ChunkPosition() : X(0), Y(0), Z(0)
{
}
ChunkPosition::ChunkPosition(int32_t x, int32_t y, int32_t z) : X(x), Y(y), Z(z)
{
}
VoxerEngine::ChunkPosition ChunkPosition::GetNeighborPos(Direction dir) const
{
switch (dir)
{
case Direction::Front:
return ChunkPosition{ X + 1, Y, Z };
case Direction::Back:
return ChunkPosition{ X - 1, Y, Z };
case Direction::Left:
return ChunkPosition{ X, Y - 1, Z };
case Direction::Right:
return ChunkPosition{ X, Y + 1, Z };
case Direction::Up:
return ChunkPosition{ X, Y , Z + 1};
case Direction::Down:
return ChunkPosition{ X, Y , Z - 1 };
default:
assert(0);
return *this;
}
}
} | 18.142857 | 81 | 0.635171 | cLazyZombie |
3e83e2fb9e996bb8528a34bd45f084bcaba19dbf | 1,251 | cpp | C++ | Code/Libraries/Rodin/src/Actions/wbactionrodinblackboardwrite.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Libraries/Rodin/src/Actions/wbactionrodinblackboardwrite.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | Code/Libraries/Rodin/src/Actions/wbactionrodinblackboardwrite.cpp | kas1e/Eldritch | 032b4ac52f7508c89efa407d6fe60f40c6281fd9 | [
"Zlib"
] | null | null | null | #include "core.h"
#include "wbactionrodinblackboardwrite.h"
#include "configmanager.h"
#include "Components/wbcomprodinblackboard.h"
#include "wbactionstack.h"
WBActionRodinBlackboardWrite::WBActionRodinBlackboardWrite()
: m_BlackboardKey(), m_ValuePE() {}
WBActionRodinBlackboardWrite::~WBActionRodinBlackboardWrite() {}
/*virtual*/ void WBActionRodinBlackboardWrite::InitializeFromDefinition(
const SimpleString& DefinitionName) {
WBAction::InitializeFromDefinition(DefinitionName);
MAKEHASH(DefinitionName);
STATICHASH(BlackboardKey);
m_BlackboardKey = ConfigManager::GetHash(
sBlackboardKey, HashedString::NullString, sDefinitionName);
STATICHASH(ValuePE);
m_ValuePE.InitializeFromDefinition(
ConfigManager::GetString(sValuePE, "", sDefinitionName));
}
/*virtual*/ void WBActionRodinBlackboardWrite::Execute() {
STATIC_HASHED_STRING(EventOwner);
WBEntity* const pEntity = WBActionStack::Top().GetEntity(sEventOwner);
DEVASSERT(pEntity);
WBCompRodinBlackboard* const pBlackboard =
GET_WBCOMP(pEntity, RodinBlackboard);
ASSERT(pBlackboard);
WBParamEvaluator::SPEContext Context;
Context.m_Entity = pEntity;
m_ValuePE.Evaluate(Context);
pBlackboard->Set(m_BlackboardKey, m_ValuePE);
} | 30.512195 | 72 | 0.784972 | kas1e |
3e9508c05fed7d576f9de8c44ec0b0f33035e5af | 2,037 | hpp | C++ | raintk/RainTkTransformSystem.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | 4 | 2016-05-03T20:47:51.000Z | 2021-04-15T09:33:34.000Z | raintk/RainTkTransformSystem.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | null | null | null | raintk/RainTkTransformSystem.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | 1 | 2017-07-26T07:31:35.000Z | 2017-07-26T07:31:35.000Z | /*
Copyright (C) 2015-2016 Preet Desai (preet.desai@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 RAINTK_TRANSFORM_SYSTEM_HPP
#define RAINTK_TRANSFORM_SYSTEM_HPP
#include <ks/draw/KsDrawSystem.hpp>
#include <raintk/RainTkGlobal.hpp>
#include <raintk/RainTkComponents.hpp>
namespace raintk
{
class Scene;
class DrawableWidget;
class TransformSystem : public ks::draw::System
{
public:
TransformSystem(Scene* scene);
~TransformSystem();
std::string GetDesc() const override;
TransformDataComponentList*
GetTransformDataComponentList() const;
void Update(TimePoint const &prev_time,
TimePoint const &curr_time) override;
private:
void updateLayout();
void updateTransforms();
void updateAnimations();
static void updateWidgetTransforms(
Widget* widget,
UpdateDataComponentList* cmlist_upd_data,
TransformDataComponentList* cmlist_xf_data);
static void updateWidgetClips(
Widget* widget,
UpdateDataComponentList* cmlist_upd_data,
TransformDataComponentList* cmlist_xf_data);
static void updateWidgetOpacities(
Widget* widget,
float opacity);
Scene* const m_scene;
UpdateDataComponentList* m_cmlist_upd_data;
TransformDataComponentList* m_cmlist_xf_data;
};
}
#endif // RAINTK_TRANSFORM_SYSTEM_HPP
| 27.90411 | 75 | 0.679921 | preet |
3e95390f2876475d320b1fde9702cd5bdce52dea | 67,901 | hpp | C++ | src/win_socks/include/unifex_IOCP_sockets.hpp | grishavanika/win_io | 29a7bb5ae5974754662207992627c1d0dfc9e865 | [
"MIT"
] | 1 | 2021-05-04T18:39:17.000Z | 2021-05-04T18:39:17.000Z | src/win_socks/include/unifex_IOCP_sockets.hpp | grishavanika/win_io | 29a7bb5ae5974754662207992627c1d0dfc9e865 | [
"MIT"
] | null | null | null | src/win_socks/include/unifex_IOCP_sockets.hpp | grishavanika/win_io | 29a7bb5ae5974754662207992627c1d0dfc9e865 | [
"MIT"
] | null | null | null | #include <WinSock2.h>
#include <WS2tcpip.h>
#if !defined(WIN32_LEAN_AND_MEAN)
# define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#if !defined(_WINSOCKAPI_)
# define _WINSOCKAPI_
#endif
#include <MSWSock.h>
#include <win_io/detail/io_completion_port.h>
#include <unifex/sender_concepts.hpp>
#include <unifex/sync_wait.hpp>
#include <unifex/then.hpp>
#include <unifex/sequence.hpp>
#include <unifex/repeat_effect_until.hpp>
#include <unifex/defer.hpp>
#include <unifex/let_value.hpp>
#include <unifex/let_value_with.hpp>
#include <unifex/just_done.hpp>
#include <unifex/inline_scheduler.hpp>
#include <unifex/on.hpp>
#include <unifex/when_all.hpp>
#include <unifex/inplace_stop_token.hpp>
#include <unifex/with_query_value.hpp>
#include <unifex/manual_lifetime.hpp>
#include <system_error>
#include <optional>
#include <utility>
#include <type_traits>
#include <span>
#include <limits>
#include <variant>
#include <string_view>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#if defined(NDEBUG)
# undef NDEBUG
#endif
#include <cassert>
// Few helpers to simplify "standard" definitions of Senders
// (one overload of set_value() and set_error()) and
// Operation states (e.g., no copies are allowed). Mostly
// to ensure this is true for learning purpose.
template<typename Sender>
using XX_Values = unifex::sender_value_types_t<Sender, std::variant, std::tuple>;
template<typename Sender>
using XX_Errors = unifex::sender_error_types_t<Sender, std::variant>;
template<typename Unknown>
struct XX_Show;
struct MoveOnly
{
MoveOnly() noexcept = default;
~MoveOnly() noexcept = default;
MoveOnly(const MoveOnly&) = delete;
MoveOnly& operator=(const MoveOnly&) = delete;
MoveOnly& operator=(MoveOnly&&) = delete;
// Needed.
MoveOnly(MoveOnly&&) noexcept = default;
};
struct Operation_Base : MoveOnly
{
// Let say this is unmovable. See when this may be needed.
// (E.g. move *before* operation's start()).
Operation_Base(Operation_Base&&) = delete;
Operation_Base() noexcept = default;
};
template<typename V, typename E>
struct Sender_LogSimple : MoveOnly
{
template<template <typename...> class Variant, template <typename...> class Tuple>
using value_types = Variant<Tuple<V>>;
template <template <typename...> class Variant>
using error_types = Variant<E>;
static constexpr bool sends_done = true;
};
template<typename E>
struct Sender_LogSimple<void, E> : MoveOnly
{
template<template <typename...> class Variant, template <typename...> class Tuple>
using value_types = Variant<Tuple<>>;
// ^^^^^^^ void
template <template <typename...> class Variant>
using error_types = Variant<E>;
static constexpr bool sends_done = true;
};
template<typename V>
struct Sender_LogSimple<V, void> : MoveOnly
{
template<template <typename...> class Variant, template <typename...> class Tuple>
using value_types = Variant<Tuple<V>>;
template <template <typename...> class Variant>
using error_types = Variant<>;
// ^^^^^^^ void
static constexpr bool sends_done = true;
};
template<>
struct Sender_LogSimple<void, void> : MoveOnly
{
template<template <typename...> class Variant, template <typename...> class Tuple>
using value_types = Variant<Tuple<>>;
// ^^^^^^^ void
template <template <typename...> class Variant>
using error_types = Variant<>;
// ^^^^^^^ void
static constexpr bool sends_done = true;
};
// WSA.
struct Initialize_WSA
{
explicit Initialize_WSA()
{
WSADATA wsa_data{};
const int error = ::WSAStartup(MAKEWORD(2, 2), &wsa_data);
assert(error == 0);
}
~Initialize_WSA() noexcept
{
const int error = ::WSACleanup();
assert(error == 0);
}
Initialize_WSA(const Initialize_WSA&) = delete;
Initialize_WSA& operator=(const Initialize_WSA&) = delete;
Initialize_WSA(Initialize_WSA&&) = delete;
Initialize_WSA& operator=(Initialize_WSA&&) = delete;
};
static constexpr wi::WinULONG_PTR kClientKeyIOCP = 1;
struct IOCP_Overlapped : OVERLAPPED
{
LPOVERLAPPED ptr() { return this; }
using Handle = void (*)(void* user_data, const wi::PortEntry& /*entry*/, std::error_code /*ec*/);
Handle _callback = nullptr;
void* _user_data = nullptr;
};
struct Endpoint_IPv4
{
std::uint16_t _port_network = 0;
std::uint32_t _ip_network = 0;
// https://man7.org/linux/man-pages/man3/inet_pton.3.html
// `src` is in dotted-decimal format, "ddd.ddd.ddd.ddd".
static std::optional<Endpoint_IPv4> from_string(const char* src, std::uint16_t port_host)
{
struct in_addr ipv4{};
static_assert(sizeof(ipv4.s_addr) == sizeof(std::uint32_t));
const int ok = ::inet_pton(AF_INET, src, &ipv4);
if (ok == 1)
{
Endpoint_IPv4 endpoint;
endpoint._port_network = ::htons(port_host);
endpoint._ip_network = ipv4.s_addr;
return endpoint;
}
return std::nullopt;
}
static Endpoint_IPv4 any(std::uint16_t port_host)
{
Endpoint_IPv4 endpoint;
endpoint._port_network = ::htons(port_host);
endpoint._ip_network = INADDR_ANY;
return endpoint;
}
};
template<typename Receiver, typename Op>
struct Helper_HandleStopToken
{
struct Callback_Stop
{
Op* _op = nullptr;
void operator()() noexcept { _op->try_stop(); }
};
using StopToken = unifex::stop_token_type_t<Receiver>;
using StopCallback = typename StopToken::template callback_type<Callback_Stop>;
unifex::manual_lifetime<StopCallback> _stop_callback{};
bool try_construct(const Receiver& receiver, Op& op) noexcept
{
if constexpr (!unifex::is_stop_never_possible_v<StopToken>)
{
auto stop_token = unifex::get_stop_token(receiver);
_stop_callback.construct(stop_token, Callback_Stop{&op});
return stop_token.stop_possible();
}
else
{
return false;
}
}
bool try_finalize(const Receiver& receiver) noexcept
{
if constexpr (!unifex::is_stop_never_possible_v<StopToken>)
{
_stop_callback.destruct();
auto stop_token = unifex::get_stop_token(receiver);
return stop_token.stop_requested();
}
else
{
return false;
}
}
};
inline void Helper_CancelIoEx(SOCKET socket, OVERLAPPED* ov)
{
HANDLE handle = reinterpret_cast<HANDLE>(socket);
const BOOL ok = ::CancelIoEx(handle, ov);
if (!ok)
{
const DWORD error = GetLastError();
// No request to cancel. Finished?
assert(error == ERROR_NOT_FOUND);
}
}
template<typename Receiver>
struct Operation_Connect : Operation_Base
{
Receiver _receiver;
SOCKET _socket = INVALID_SOCKET;
Endpoint_IPv4 _endpoint;
IOCP_Overlapped _ov{{}, &Operation_Connect::on_connected, this};
Helper_HandleStopToken<Receiver, Operation_Connect> _cancel_impl{};
void try_stop() noexcept { Helper_CancelIoEx(_socket, _ov.ptr()); }
static void on_connected(void* user_data, const wi::PortEntry& entry, std::error_code ec) noexcept
{
assert(user_data);
Operation_Connect& self = *static_cast<Operation_Connect*>(user_data);
assert(entry.bytes_transferred == 0);
assert(entry.completion_key == kClientKeyIOCP);
assert(entry.overlapped == self._ov.ptr());
if (self._cancel_impl.try_finalize(self._receiver))
{
unifex::set_done(std::move(self._receiver));
return;
}
if (ec)
{
unifex::set_error(std::move(self._receiver), ec);
return;
}
const int ok = ::setsockopt(self._socket, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, nullptr, 0);
if (ok != 0)
{
const int wsa_error = ::WSAGetLastError();
unifex::set_error(std::move(self._receiver)
, std::error_code(wsa_error, std::system_category()));
return;
}
unifex::set_value(std::move(self._receiver));
}
void start() & noexcept
{
LPFN_CONNECTEX ConnectEx = nullptr;
{
GUID GuidConnectEx = WSAID_CONNECTEX;
DWORD bytes = 0;
const int error = ::WSAIoctl(_socket
, SIO_GET_EXTENSION_FUNCTION_POINTER
, &GuidConnectEx, sizeof(GuidConnectEx)
, &ConnectEx, sizeof(ConnectEx)
, &bytes, nullptr, nullptr);
assert(error == 0);
assert(ConnectEx);
}
{ // Required by ConnectEx().
struct sockaddr_in local_address {};
local_address.sin_family = AF_INET;
local_address.sin_addr.s_addr = INADDR_ANY;
local_address.sin_port = 0;
int ok = ::bind(_socket
, reinterpret_cast<SOCKADDR*>(&local_address)
, sizeof(local_address));
const int wsa_error = ::WSAGetLastError();
assert((ok == 0)
// WSAEINVAL - when binding a socked 2nd or more time :(
|| (wsa_error == WSAEINVAL));
}
_cancel_impl.try_construct(_receiver, *this);
struct sockaddr_in connect_to {};
connect_to.sin_family = AF_INET;
connect_to.sin_port = _endpoint._port_network;
connect_to.sin_addr.s_addr = _endpoint._ip_network;
const BOOL finished = ConnectEx(_socket
, (sockaddr*)&connect_to
, sizeof(connect_to)
, nullptr
, 0
, nullptr
, _ov.ptr());
if (finished)
{
wi::PortEntry entry;
entry.bytes_transferred = 0;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_connected(this, entry, std::error_code());
return;
}
const int wsa_error = ::WSAGetLastError();
if (wsa_error != ERROR_IO_PENDING)
{
wi::PortEntry entry;
entry.bytes_transferred = 0;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_connected(this, entry
, std::error_code(wsa_error, std::system_category()));
return;
}
}
};
struct Sender_Connect : Sender_LogSimple<void, std::error_code>
{
SOCKET _socket = INVALID_SOCKET;
Endpoint_IPv4 _endpoint;
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_Connect<Receiver_>{{}
, std::move(receiver), _socket, _endpoint};
}
};
struct BufferRef : WSABUF
{
explicit BufferRef()
: WSABUF{0, nullptr} {}
explicit BufferRef(void* data, std::uint32_t size)
: WSABUF{ULONG(size), static_cast<CHAR*>(data)} {}
};
// Helper to support passing only single std::span<bytes> buffer
// OR multiple std::span<BufferRef> buffers.
// std::span<bytes> needs to be converted to std::span<BufferRef>
// (with buffers count = 1) and that temporary buffer needs to be
// alive until connect() - or ::WSASend() - call.
//
// Logically, same as std::variant<std::span<char>, std::span<BufferRef>>,
// but simpler - better for compile times & codegen.
struct OneBufferOwnerOrManyRef
{
BufferRef _single_buffer;
std::optional<std::span<BufferRef>> _buffers;
std::optional<std::size_t> _total_size;
explicit OneBufferOwnerOrManyRef(BufferRef single_buffer)
: _single_buffer(single_buffer)
, _buffers(std::nullopt)
, _total_size(std::in_place, single_buffer.len) {}
explicit OneBufferOwnerOrManyRef(std::span<BufferRef> buffers)
: _single_buffer()
, _buffers(std::in_place, buffers)
, _total_size(std::nullopt) {}
// Pre-calculated total size of all buffers.
explicit OneBufferOwnerOrManyRef(std::span<BufferRef> buffers, std::size_t total_size)
: _single_buffer()
, _buffers(std::in_place, buffers)
, _total_size(std::in_place, total_size) {}
std::span<BufferRef> as_ref()
{
return _buffers.value_or(std::span<BufferRef>(&_single_buffer, 1));
}
bool has_data() const
{
if (_total_size.has_value())
{
return (*_total_size > 0);
}
assert(_buffers.has_value());
for (const BufferRef& buffer : *_buffers)
{
if (buffer.len > 0)
{
return true;
}
}
return false;
}
std::size_t total_size()
{
if (!_total_size.has_value())
{
assert(_buffers.has_value());
std::size_t value = 0;
for (const BufferRef& buffer : *_buffers)
{
value += buffer.len;
}
_total_size.emplace(value);
}
return *_total_size;
}
};
template<typename Receiver>
struct Operation_WriteSome : Operation_Base
{
Receiver _receiver;
SOCKET _socket = INVALID_SOCKET;
OneBufferOwnerOrManyRef _buffers;
IOCP_Overlapped _ov{{}, &Operation_WriteSome::on_sent, this};
Helper_HandleStopToken<Receiver, Operation_WriteSome> _cancel_impl{};
void try_stop() noexcept { Helper_CancelIoEx(_socket, _ov.ptr()); }
static void on_sent(void* user_data, const wi::PortEntry& entry, std::error_code ec) noexcept
{
assert(user_data);
Operation_WriteSome& self = *static_cast<Operation_WriteSome*>(user_data);
assert(entry.completion_key == kClientKeyIOCP);
assert(entry.overlapped == self._ov.ptr());
if (self._cancel_impl.try_finalize(self._receiver))
{
unifex::set_done(std::move(self._receiver));
return;
}
if (ec)
{
unifex::set_error(std::move(self._receiver), ec);
return;
}
unifex::set_value(std::move(self._receiver)
, std::size_t(entry.bytes_transferred));
}
void start() & noexcept
{
_cancel_impl.try_construct(_receiver, *this);
auto buffers = _buffers.as_ref();
DWORD bytes_sent = 0;
const int error = ::WSASend(_socket
, buffers.data(), DWORD(buffers.size())
, &bytes_sent
, 0/*flags*/
, _ov.ptr()
, nullptr);
if (error == 0)
{
// Completed synchronously.
wi::PortEntry entry;
entry.bytes_transferred = bytes_sent;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_sent(this, entry, std::error_code());
return;
}
const int wsa_error = ::WSAGetLastError();
if (wsa_error != ERROR_IO_PENDING)
{
wi::PortEntry entry;
entry.bytes_transferred = 0;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_sent(this, entry
, std::error_code(wsa_error, std::system_category()));
return;
}
}
};
struct Sender_WriteSome : Sender_LogSimple<std::size_t, std::error_code>
{
SOCKET _socket = INVALID_SOCKET;
OneBufferOwnerOrManyRef _buffers;
template <typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_WriteSome<Receiver_>{{}, std::move(receiver), _socket, _buffers};
}
};
template<typename Receiver>
struct Operation_SendTo : Operation_Base
{
Receiver _receiver;
SOCKET _socket = INVALID_SOCKET;
OneBufferOwnerOrManyRef _buffers;
Endpoint_IPv4 _destination;
IOCP_Overlapped _ov{{}, &Operation_SendTo::on_sent_to, this};
Helper_HandleStopToken<Receiver, Operation_SendTo> _cancel_impl{};
void try_stop() noexcept { Helper_CancelIoEx(_socket, _ov.ptr()); }
static void on_sent_to(void* user_data, const wi::PortEntry& entry, std::error_code ec) noexcept
{
assert(user_data);
Operation_SendTo& self = *static_cast<Operation_SendTo*>(user_data);
assert(entry.completion_key == kClientKeyIOCP);
assert(entry.overlapped == self._ov.ptr());
if (self._cancel_impl.try_finalize(self._receiver))
{
unifex::set_done(std::move(self._receiver));
return;
}
if (ec)
{
unifex::set_error(std::move(self._receiver), ec);
return;
}
unifex::set_value(std::move(self._receiver)
, std::size_t(entry.bytes_transferred));
}
void start() & noexcept
{
_cancel_impl.try_construct(_receiver, *this);
auto buffers = _buffers.as_ref();
struct sockaddr_in send_to{};
send_to.sin_family = AF_INET;
send_to.sin_port = _destination._port_network;
send_to.sin_addr.s_addr = _destination._ip_network;
DWORD bytes_sent = 0;
const int error = ::WSASendTo(_socket
, buffers.data(), DWORD(buffers.size())
, &bytes_sent
, 0/*flags*/
, reinterpret_cast<struct sockaddr*>(&send_to), sizeof(send_to)
, _ov.ptr()
, nullptr);
if (error == 0)
{
// Completed synchronously.
wi::PortEntry entry;
entry.bytes_transferred = bytes_sent;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_sent_to(this, entry, std::error_code());
return;
}
const int wsa_error = ::WSAGetLastError();
if (wsa_error != ERROR_IO_PENDING)
{
wi::PortEntry entry;
entry.bytes_transferred = 0;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_sent_to(this, entry
, std::error_code(wsa_error, std::system_category()));
return;
}
}
};
struct Sender_SendTo : Sender_LogSimple<std::size_t, std::error_code>
{
SOCKET _socket = INVALID_SOCKET;
OneBufferOwnerOrManyRef _buffers;
Endpoint_IPv4 _destination;
template <typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_SendTo<Receiver_>{{}, std::move(receiver), _socket, _buffers, _destination};
}
};
template<typename Receiver>
struct Operation_ReadSome : Operation_Base
{
Receiver _receiver;
SOCKET _socket = INVALID_SOCKET;
OneBufferOwnerOrManyRef _buffers;
IOCP_Overlapped _ov{{}, &Operation_ReadSome::on_received, this};
DWORD _flags = 0;
WSABUF _wsa_buf{};
Helper_HandleStopToken<Receiver, Operation_ReadSome> _cancel_impl{};
void try_stop() noexcept { Helper_CancelIoEx(_socket, _ov.ptr()); }
static void on_received(void* user_data, const wi::PortEntry& entry, std::error_code ec) noexcept
{
assert(user_data);
Operation_ReadSome& self = *static_cast<Operation_ReadSome*>(user_data);
assert(entry.completion_key == kClientKeyIOCP);
assert(entry.overlapped == self._ov.ptr());
if (self._cancel_impl.try_finalize(self._receiver))
{
unifex::set_done(std::move(self._receiver));
return;
}
if (ec)
{
unifex::set_error(std::move(self._receiver), ec);
return;
}
// Match to Asio behavior, complete_iocp_recv(), socket_ops.ipp.
if ((entry.bytes_transferred == 0)
&& self._buffers.has_data())
{
unifex::set_error(std::move(self._receiver)
, std::error_code(-1, std::system_category()));
return;
}
unifex::set_value(std::move(self._receiver)
, std::size_t(entry.bytes_transferred));
}
void start() & noexcept
{
_cancel_impl.try_construct(_receiver, *this);
auto buffers = _buffers.as_ref();
_flags = MSG_PARTIAL;
DWORD received = 0;
const int error = ::WSARecv(_socket
, buffers.data(), DWORD(buffers.size())
, &received
, &_flags
, _ov.ptr()
, nullptr);
if (error == 0)
{
// Completed synchronously.
wi::PortEntry entry;
entry.bytes_transferred = received;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_received(this, entry, std::error_code());
return;
}
const int wsa_error = ::WSAGetLastError();
if (wsa_error != ERROR_IO_PENDING)
{
wi::PortEntry entry;
entry.bytes_transferred = 0;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_received(this, entry
, std::error_code(wsa_error, std::system_category()));
return;
}
}
};
struct Sender_ReadSome : Sender_LogSimple<std::size_t, std::error_code>
{
SOCKET _socket;
OneBufferOwnerOrManyRef _buffers;
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_ReadSome<Receiver_>{{}, std::move(receiver), _socket, _buffers};
}
};
template<typename Receiver>
struct Operation_ReceiveFrom : Operation_Base
{
Receiver _receiver;
SOCKET _socket = INVALID_SOCKET;
OneBufferOwnerOrManyRef _buffers;
Endpoint_IPv4* _sender = nullptr;
IOCP_Overlapped _ov{{}, &Operation_ReceiveFrom::on_received_from, this};
DWORD _flags = 0;
struct sockaddr_in _received_from{};
INT _endpoint_length = 0;
WSABUF _wsa_buf{};
Helper_HandleStopToken<Receiver, Operation_ReceiveFrom> _cancel_impl{};
void try_stop() noexcept { Helper_CancelIoEx(_socket, _ov.ptr()); }
static void on_received_from(void* user_data, const wi::PortEntry& entry, std::error_code ec) noexcept
{
assert(user_data);
Operation_ReceiveFrom& self = *static_cast<Operation_ReceiveFrom*>(user_data);
assert(entry.completion_key == kClientKeyIOCP);
assert(entry.overlapped == self._ov.ptr());
if (self._cancel_impl.try_finalize(self._receiver))
{
unifex::set_done(std::move(self._receiver));
return;
}
if (ec)
{
unifex::set_error(std::move(self._receiver), ec);
return;
}
assert(self._endpoint_length == sizeof(struct sockaddr_in));
self._sender->_port_network = self._received_from.sin_port;
self._sender->_ip_network = self._received_from.sin_addr.s_addr;
unifex::set_value(std::move(self._receiver)
, std::size_t(entry.bytes_transferred));
}
void start() & noexcept
{
_cancel_impl.try_construct(_receiver, *this);
auto buffers = _buffers.as_ref();
_flags = MSG_PARTIAL;
DWORD received = 0;
_endpoint_length = sizeof(struct sockaddr_in);
const int error = ::WSARecvFrom(_socket
, buffers.data(), DWORD(buffers.size())
, &received
, &_flags
, reinterpret_cast<struct sockaddr*>(&_received_from), &_endpoint_length
, _ov.ptr()
, nullptr);
if (error == 0)
{
// Completed synchronously.
wi::PortEntry entry;
entry.bytes_transferred = received;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_received_from(this, entry, std::error_code());
return;
}
const int wsa_error = ::WSAGetLastError();
if (wsa_error != ERROR_IO_PENDING)
{
wi::PortEntry entry;
entry.bytes_transferred = 0;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_received_from(this, entry
, std::error_code(wsa_error, std::system_category()));
return;
}
}
};
struct Sender_ReceiveFrom : Sender_LogSimple<std::size_t, std::error_code>
{
SOCKET _socket;
OneBufferOwnerOrManyRef _buffers;
Endpoint_IPv4* _sender = nullptr;
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_ReceiveFrom<Receiver_>{{}, std::move(receiver), _socket, _buffers, _sender};
}
};
template<typename Receiver
, typename _Async_TCPSocket /*= Async_TCPSocket*/>
struct Operation_Accept : Operation_Base
{
// As per AcceptEx() and GetAcceptExSockaddrs():
// https://docs.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex
// https://docs.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-getacceptexsockaddrs.
static constexpr std::size_t kAddressLength = (sizeof(struct sockaddr) + 16);
Receiver _receiver;
SOCKET _listen_socket = INVALID_SOCKET;
wi::IoCompletionPort* _iocp = nullptr;
IOCP_Overlapped _ov{{}, &Operation_Accept::on_accepted, this};
char _buffer[2 * kAddressLength]{};
_Async_TCPSocket _client{};
static void on_accepted(void* user_data, const wi::PortEntry& entry, std::error_code ec) noexcept
{
assert(user_data);
Operation_Accept& self = *static_cast<Operation_Accept*>(user_data);
assert(entry.bytes_transferred == 0);
assert(entry.completion_key == kClientKeyIOCP);
assert(entry.overlapped == self._ov.ptr());
if (ec)
{
unifex::set_error(std::move(self._receiver), ec);
return;
}
#if (0)
::GetAcceptExSockaddrs(self._buffer
, 0
, Operation_Accept::kAddressLength
, Operation_Accept::kAddressLength
, )
#endif
const int error = ::setsockopt(self._client._socket, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT
, reinterpret_cast<char*>(&self._listen_socket)
, sizeof(self._listen_socket));
assert(error == 0);
// Close socket on error.
unifex::set_value(std::move(self._receiver), std::move(self._client));
}
void start() & noexcept
{
std::error_code ec;
auto client = _Async_TCPSocket::make(*_iocp, ec);
if (ec)
{
unifex::set_error(std::move(_receiver), ec);
return;
}
assert(client);
_client = std::move(*client);
using Self = Operation_Accept<Receiver, _Async_TCPSocket>;
const DWORD address_length = DWORD(Self::kAddressLength);
DWORD bytes_received = 0;
const BOOL ok = ::AcceptEx(_listen_socket, _client._socket
, _buffer
, 0
, address_length
, address_length
, &bytes_received
, _ov.ptr());
if (ok == TRUE)
{
// Completed synchronously.
wi::PortEntry entry;
entry.bytes_transferred = bytes_received;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_accepted(this, entry, std::error_code());
return;
}
const int wsa_error = ::WSAGetLastError();
if (wsa_error != ERROR_IO_PENDING)
{
wi::PortEntry entry;
entry.bytes_transferred = 0;
entry.completion_key = kClientKeyIOCP;
entry.overlapped = _ov.ptr();
on_accepted(this, entry
, std::error_code(wsa_error, std::system_category()));
return;
}
}
};
template<typename _Async_TCPSocket /*= Async_TCPSocket*/>
struct Sender_Accept : Sender_LogSimple<_Async_TCPSocket, std::error_code>
{
SOCKET _listen_socket = INVALID_SOCKET;
wi::IoCompletionPort* _iocp = nullptr;
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_Accept<Receiver_, _Async_TCPSocket>{{}, std::move(receiver), _listen_socket, _iocp};
}
};
struct Async_TCPSocket
{
SOCKET _socket = INVALID_SOCKET;
wi::IoCompletionPort* _iocp = nullptr;
explicit Async_TCPSocket() noexcept = default;
static std::optional<Async_TCPSocket> make(wi::IoCompletionPort& iocp, std::error_code& ec) noexcept
{
ec = std::error_code();
WSAPROTOCOL_INFOW* default_protocol = nullptr;
GROUP no_group = 0;
SOCKET handle = ::WSASocketW(AF_INET
, SOCK_STREAM
, IPPROTO_TCP
, default_protocol
, no_group
, WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
Async_TCPSocket socket(handle, iocp);
if (handle == INVALID_SOCKET)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return std::nullopt;
}
const BOOL ok = ::SetFileCompletionNotificationModes(HANDLE(handle)
, FILE_SKIP_SET_EVENT_ON_HANDLE
| FILE_SKIP_COMPLETION_PORT_ON_SUCCESS);
if (!ok)
{
ec = std::error_code(::GetLastError(), std::system_category());
return std::nullopt;
}
u_long flags = 1; // non-blocking, enable.
const int error = ::ioctlsocket(handle, FIONBIO, &flags);
if (error)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return std::nullopt;
}
iocp.associate_socket(wi::WinSOCKET(handle), kClientKeyIOCP, ec);
if (ec)
{
return std::nullopt;
}
return std::make_optional(std::move(socket));
}
void bind_and_listen(Endpoint_IPv4 bind_on // Endpoint_IPv4::from_port(...)
, std::error_code& ec, int backlog = SOMAXCONN, bool reuse = true)
{
if (reuse)
{
int enable_reuse = 1;
const int error = ::setsockopt(_socket
, SOL_SOCKET
, SO_REUSEADDR
, reinterpret_cast<char*>(&enable_reuse), sizeof(enable_reuse));
if (error != 0)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return;
}
}
struct sockaddr_in address {};
address.sin_family = AF_INET;
address.sin_addr.s_addr = bind_on._ip_network;
address.sin_port = bind_on._port_network;
int error = ::bind(_socket
, reinterpret_cast<SOCKADDR*>(&address)
, sizeof(address));
if (error != 0)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return;
}
error = ::listen(_socket, backlog);
if (error != 0)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return;
}
}
Sender_Connect async_connect(Endpoint_IPv4 endpoint) noexcept
{
return Sender_Connect{{}, _socket, endpoint};
}
// https://www.boost.org/doc/libs/1_77_0/doc/html/boost_asio/reference/basic_socket_acceptor/async_accept/overload3.html.
Sender_Accept<Async_TCPSocket> async_accept() noexcept
{
return Sender_Accept<Async_TCPSocket>{{}, _socket, _iocp};
}
// https://www.boost.org/doc/libs/1_77_0/doc/html/boost_asio/reference/basic_stream_socket/async_write_some.html.
// See also async_write().
Sender_WriteSome async_write_some(std::span<char> data) noexcept
{
assert(data.size() <= (std::numeric_limits<std::uint32_t>::max)());
OneBufferOwnerOrManyRef buffer(BufferRef(data.data(), std::uint32_t(data.size())));
return Sender_WriteSome{{}, _socket, buffer};
}
Sender_WriteSome async_write_some(std::span<BufferRef> many_buffers) noexcept
{
OneBufferOwnerOrManyRef buffers(many_buffers);
return Sender_WriteSome{{}, _socket, buffers};
}
// https://www.boost.org/doc/libs/1_77_0/doc/html/boost_asio/reference/basic_stream_socket/async_read_some.html.
// See also async_read().
Sender_ReadSome async_read_some(std::span<char> data) noexcept
{
assert(data.size() <= (std::numeric_limits<std::uint32_t>::max)());
OneBufferOwnerOrManyRef buffer(BufferRef(data.data(), std::uint32_t(data.size())));
return Sender_ReadSome{{}, _socket, buffer};
}
Sender_ReadSome async_read_some(std::span<BufferRef> many_buffers) noexcept
{
OneBufferOwnerOrManyRef buffers(many_buffers);
return Sender_ReadSome{{}, _socket, buffers};
}
~Async_TCPSocket() noexcept
{
disconnect();
}
void disconnect() noexcept
{
SOCKET socket = std::exchange(_socket, INVALID_SOCKET);
if (socket == INVALID_SOCKET)
{
return;
}
int error = ::shutdown(socket, SD_BOTH);
(void)error;
error = ::closesocket(socket);
(void)error;
_iocp = nullptr;
}
Async_TCPSocket(const Async_TCPSocket&) = delete;
Async_TCPSocket& operator=(const Async_TCPSocket&) = delete;
Async_TCPSocket(Async_TCPSocket&& rhs) noexcept
: _socket(std::exchange(rhs._socket, INVALID_SOCKET))
, _iocp(std::exchange(rhs._iocp, nullptr))
{
}
Async_TCPSocket& operator=(Async_TCPSocket&& rhs) noexcept
{
if (this != &rhs)
{
disconnect();
_socket = std::exchange(rhs._socket, INVALID_SOCKET);
_iocp = std::exchange(rhs._iocp, nullptr);
}
return *this;
}
private:
explicit Async_TCPSocket(SOCKET socket, wi::IoCompletionPort& iocp) noexcept
: _socket(socket)
, _iocp(&iocp)
{
}
};
struct Async_UDPSocket
{
SOCKET _socket = INVALID_SOCKET;
wi::IoCompletionPort* _iocp = nullptr;
explicit Async_UDPSocket() noexcept = default;
static std::optional<Async_UDPSocket> make(wi::IoCompletionPort& iocp, std::error_code& ec) noexcept
{
ec = std::error_code();
WSAPROTOCOL_INFOW* default_protocol = nullptr;
GROUP no_group = 0;
SOCKET handle = ::WSASocketW(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
, default_protocol
, no_group
, WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
Async_UDPSocket socket(handle, iocp);
if (handle == INVALID_SOCKET)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return std::nullopt;
}
const BOOL ok = ::SetFileCompletionNotificationModes(HANDLE(handle)
, FILE_SKIP_SET_EVENT_ON_HANDLE
| FILE_SKIP_COMPLETION_PORT_ON_SUCCESS);
if (!ok)
{
ec = std::error_code(::GetLastError(), std::system_category());
return std::nullopt;
}
u_long flags = 1; // non-blocking, enable.
const int error = ::ioctlsocket(handle, FIONBIO, &flags);
if (error)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return std::nullopt;
}
iocp.associate_socket(wi::WinSOCKET(handle), kClientKeyIOCP, ec);
if (ec)
{
return std::nullopt;
}
return std::make_optional(std::move(socket));
}
void bind(Endpoint_IPv4 bind_on // Endpoint_IPv4::from_port(...)
, std::error_code& ec, bool reuse = true)
{
if (reuse)
{
int enable_reuse = 1;
const int error = ::setsockopt(_socket
, SOL_SOCKET
, SO_REUSEADDR
, reinterpret_cast<char*>(&enable_reuse), sizeof(enable_reuse));
if (error != 0)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return;
}
}
struct sockaddr_in address {};
address.sin_family = AF_INET;
address.sin_addr.s_addr = bind_on._ip_network;
address.sin_port = bind_on._port_network;
int error = ::bind(_socket
, reinterpret_cast<SOCKADDR*>(&address)
, sizeof(address));
if (error != 0)
{
ec = std::error_code(::WSAGetLastError(), std::system_category());
return;
}
}
Sender_SendTo async_send_to(std::span<char> data, const Endpoint_IPv4& destination) noexcept
{
assert(data.size() <= (std::numeric_limits<std::uint32_t>::max)());
OneBufferOwnerOrManyRef buffer(BufferRef(data.data(), std::uint32_t(data.size())));
return Sender_SendTo{{}, _socket, buffer, destination};
}
Sender_SendTo async_send_to(std::span<BufferRef> many_buffers, const Endpoint_IPv4& destination) noexcept
{
OneBufferOwnerOrManyRef buffers(many_buffers);
return Sender_SendTo{{}, _socket, buffers, destination};
}
Sender_ReceiveFrom async_receive_from(std::span<char> data, Endpoint_IPv4& sender) noexcept
{
assert(data.size() <= (std::numeric_limits<std::uint32_t>::max)());
OneBufferOwnerOrManyRef buffer(BufferRef(data.data(), std::uint32_t(data.size())));
return Sender_ReceiveFrom{{}, _socket, buffer, &sender};
}
Sender_ReceiveFrom async_receive_from(std::span<BufferRef> many_buffers, Endpoint_IPv4& sender) noexcept
{
OneBufferOwnerOrManyRef buffers(many_buffers);
return Sender_ReceiveFrom{{}, _socket, buffers, &sender};
}
~Async_UDPSocket() noexcept
{
close();
}
void close() noexcept
{
SOCKET socket = std::exchange(_socket, INVALID_SOCKET);
if (socket == INVALID_SOCKET)
{
return;
}
const int error = ::closesocket(socket);
(void)error;
_iocp = nullptr;
}
Async_UDPSocket(const Async_UDPSocket&) = delete;
Async_UDPSocket& operator=(const Async_UDPSocket&) = delete;
Async_UDPSocket(Async_UDPSocket&& rhs) noexcept
: _socket(std::exchange(rhs._socket, INVALID_SOCKET))
, _iocp(std::exchange(rhs._iocp, nullptr))
{
}
Async_UDPSocket& operator=(Async_UDPSocket&& rhs) noexcept
{
if (this != &rhs)
{
close();
_socket = std::exchange(rhs._socket, INVALID_SOCKET);
_iocp = std::exchange(rhs._iocp, nullptr);
}
return *this;
}
private:
explicit Async_UDPSocket(SOCKET socket, wi::IoCompletionPort& iocp) noexcept
: _socket(socket)
, _iocp(&iocp)
{
}
};
template<typename Receiver>
struct Operation_IOCP_Schedule : Operation_Base
{
static constexpr wi::WinULONG_PTR kScheduleKeyIOCP = 2;
Receiver _receiver;
wi::IoCompletionPort* _iocp = nullptr;
IOCP_Overlapped _ov{{}, &Operation_IOCP_Schedule::on_scheduled, this};
static void on_scheduled(void* user_data, const wi::PortEntry& entry, std::error_code ec) noexcept
{
assert(user_data);
Operation_IOCP_Schedule& self = *static_cast<Operation_IOCP_Schedule*>(user_data);
assert(entry.bytes_transferred == 0);
assert(entry.completion_key == kScheduleKeyIOCP);
assert(entry.overlapped == self._ov.ptr());
if (ec)
{
unifex::set_error(std::move(self._receiver), ec);
return;
}
unifex::set_value(std::move(self._receiver));
}
void start() & noexcept
{
wi::PortEntry entry{};
entry.bytes_transferred = 0;
entry.completion_key = kScheduleKeyIOCP;
entry.overlapped = _ov.ptr();
std::error_code ec;
_iocp->post(entry, ec);
if (ec)
{
on_scheduled(this, entry, ec);
return;
}
}
};
struct Sender_IOCP_Schedule : Sender_LogSimple<void, std::error_code>
{
wi::IoCompletionPort* _iocp;
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_IOCP_Schedule<Receiver_>{{}, std::move(receiver), _iocp};
}
};
static Sender_IOCP_Schedule IOCP_schedule(wi::IoCompletionPort& iocp)
{
return Sender_IOCP_Schedule{{}, &iocp};
}
struct IOCP_Scheduler
{
wi::IoCompletionPort* _iocp = nullptr;
Sender_IOCP_Schedule schedule() noexcept { return IOCP_schedule(*_iocp); }
bool operator==(const IOCP_Scheduler& rhs) const { return (_iocp == rhs._iocp); }
bool operator!=(const IOCP_Scheduler& rhs) const { return (_iocp != rhs._iocp); }
};
static_assert(unifex::scheduler<IOCP_Scheduler>);
template<typename Receiver, typename Scheduler, typename Fallback>
struct Operation_SelectOnceInN : Operation_Base
{
struct Receiver_OnScheduled
{
Operation_SelectOnceInN* _self = nullptr;
void set_value() && noexcept
{
_self->destroy_state();
unifex::set_value(std::move(_self->_receiver));
}
template<typename E>
void set_error(E&& arg) && noexcept
{
_self->destroy_state();
unifex::set_error(std::move(_self->_receiver), std::forward<E>(arg));
}
void set_done() && noexcept
{
_self->destroy_state();
unifex::set_done(std::move(_self->_receiver));
}
};
using Op_Scheduler = decltype(unifex::connect(
std::declval<Scheduler&>().schedule()
, std::declval<Receiver_OnScheduled>()));
using Op_Fallback = decltype(unifex::connect(
std::declval<Fallback&>().schedule()
, std::declval<Receiver_OnScheduled>()));
using Op_State = std::variant<std::monostate
, unifex::manual_lifetime<Op_Scheduler>
, unifex::manual_lifetime<Op_Fallback>>;
Receiver _receiver;
unsigned* _counter = nullptr;
unsigned _N = 0;
Scheduler _scheduler; // no_unique_address
Fallback _fallback; // no_unique_address
Op_State _op{};
void destroy_state()
{
if (auto* scheduler = std::get_if<1>(&_op))
{
scheduler->destruct();
}
else if (auto* fallback = std::get_if<2>(&_op))
{
fallback->destruct();
}
else
{
assert(false);
}
}
void start() & noexcept
{
assert(_counter);
assert(_N > 0);
const unsigned counter = ++(*_counter);
if ((counter % _N) == 0)
{
// Select & run Scheduler.
auto& storage = _op.template emplace<1>();
storage.construct_with([&]()
{
return unifex::connect(
_scheduler.schedule()
, Receiver_OnScheduled{this});
});
unifex::start(storage.get());
}
else
{
// Select & run Fallback Scheduler.
auto& storage = _op.template emplace<2>();
storage.construct_with([&]()
{
return unifex::connect(
_fallback.schedule()
, Receiver_OnScheduled{this});
});
unifex::start(storage.get());
}
}
};
// #XXX: error should be variant<> from both schedulers.
template<typename Scheduler, typename Fallback>
struct Sender_SelectOnceInN : Sender_LogSimple<void, void>
{
unsigned* _counter = nullptr;
unsigned _N = 0;
Scheduler _scheduler; // no_unique_address
Fallback _fallback; // no_unique_address
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_SelectOnceInN<Receiver_, Scheduler, Fallback>{{}
, std::move(receiver), _counter, _N, _scheduler, _fallback};
}
};
template<typename Scheduler, typename Fallback = unifex::inline_scheduler>
struct SelectOnceInN_Scheduler
{
Scheduler _scheduler; // no_unique_address
unsigned* _counter;
unsigned _N = 128;
Fallback _fallback{}; // no_unique_address
bool operator==(const SelectOnceInN_Scheduler& rhs) const
{
return (_counter == rhs._counter)
&& (_N == rhs._N)
&& (_scheduler == rhs._scheduler)
&& (_fallback == rhs._fallback);
}
bool operator!=(const SelectOnceInN_Scheduler& rhs) const { return !(*this == rhs); }
Sender_SelectOnceInN<Scheduler, Fallback> schedule() noexcept
{
return Sender_SelectOnceInN<Scheduler, Fallback>{{}, _counter, _N, _scheduler, _fallback};
}
};
static_assert(unifex::scheduler<SelectOnceInN_Scheduler<unifex::inline_scheduler>>);
static_assert(unifex::scheduler<SelectOnceInN_Scheduler<IOCP_Scheduler>>);
struct State_AsyncReadWrite
{
Async_TCPSocket* _socket;
OneBufferOwnerOrManyRef _buffers_impl;
std::span<BufferRef> _buffers;
std::size_t _processed_bytes;
BufferRef* _current_buffer;
unsigned _calls_count;
explicit State_AsyncReadWrite(Async_TCPSocket& socket, OneBufferOwnerOrManyRef buffers_impl)
: _socket(&socket)
, _buffers_impl(buffers_impl)
, _buffers(_buffers_impl.as_ref())
, _processed_bytes(0)
, _current_buffer(_buffers.data())
, _calls_count(0) { }
// Needed for unifex::let_value(). Fix self-referencing pointers.
State_AsyncReadWrite(State_AsyncReadWrite&& rhs)
: _socket(rhs._socket)
, _buffers_impl(rhs._buffers_impl)
, _buffers(_buffers_impl.as_ref())
, _processed_bytes(0)
, _current_buffer(_buffers.data())
, _calls_count(0) { }
State_AsyncReadWrite(const State_AsyncReadWrite&) = delete;
State_AsyncReadWrite& operator=(const State_AsyncReadWrite&) = delete;
State_AsyncReadWrite& operator=(State_AsyncReadWrite&&) = delete;
auto scheduler()
{
return SelectOnceInN_Scheduler<IOCP_Scheduler>{
IOCP_Scheduler{_socket->_iocp}, & _calls_count, 128};
}
std::span<BufferRef> remaining() const
{
BufferRef* const end = (_buffers.data() + _buffers.size());
return std::span<BufferRef>(_current_buffer, end);
}
void consume(std::size_t bytes_transferred)
{
_processed_bytes += bytes_transferred;
if (_processed_bytes >= _buffers_impl.total_size())
{
// Done.
BufferRef* const end = (_buffers.data() + _buffers.size());
_current_buffer = end;
return;
}
BufferRef* const end = (_buffers.data() + _buffers.size());
for (; _current_buffer != end; ++_current_buffer)
{
if (_current_buffer->len <= bytes_transferred)
{
// Consumed this buffer.
bytes_transferred -= _current_buffer->len;
continue;
}
// else: buffer->len > bytes_transferred
// Consumed part of this buffer.
_current_buffer->buf = (static_cast<CHAR*>(_current_buffer->buf) + bytes_transferred);
_current_buffer->len -= ULONG(bytes_transferred);
break;
}
assert(_current_buffer != end);
}
bool is_completed()
{
return (_processed_bytes >= _buffers_impl.total_size());
}
static auto do_write(Async_TCPSocket& tcp_socket, std::span<BufferRef> many_buffers)
{
return tcp_socket.async_write_some(many_buffers);
}
static auto do_read(Async_TCPSocket& tcp_socket, std::span<BufferRef> many_buffers)
{
return tcp_socket.async_read_some(many_buffers);
}
};
template<typename ReadOrWriteSome>
inline auto async_read_write_impl(Async_TCPSocket& tcp_socket
, OneBufferOwnerOrManyRef buffers_impl
, ReadOrWriteSome callback) noexcept
{
return unifex::let_value(unifex::just(State_AsyncReadWrite{tcp_socket, buffers_impl})
, [callback = std::move(callback)](State_AsyncReadWrite& state) mutable
{
return unifex::repeat_effect_until(unifex::defer([&state, callback = std::move(callback)]()
{
return unifex::on(state.scheduler(),
callback(*state._socket, state.remaining())
| unifex::then([&state](std::size_t bytes_transferred)
{
state.consume(bytes_transferred);
}));
})
, [&state]()
{
return state.is_completed();
})
| unifex::then([&state]()
{
return state._processed_bytes;
});
});
}
inline auto async_write(Async_TCPSocket& tcp_socket, std::span<char> data) noexcept
{
assert(data.size() <= (std::numeric_limits<std::uint32_t>::max)());
OneBufferOwnerOrManyRef buffer(BufferRef(data.data(), std::uint32_t(data.size())));
return async_read_write_impl(tcp_socket, buffer, &State_AsyncReadWrite::do_write);
}
inline auto async_write(Async_TCPSocket& tcp_socket
// `many_buffers` must be alive for a duration of the call.
, std::span<BufferRef> many_buffers)
{
OneBufferOwnerOrManyRef buffers(many_buffers);
return async_read_write_impl(tcp_socket, buffers, &State_AsyncReadWrite::do_write);
}
inline auto async_write(Async_TCPSocket& tcp_socket
// `many_buffers` must be alive for a duration of the call.
, std::span<BufferRef> many_buffers
// pre-calculated total size of `many_buffers`.
, std::size_t total_size)
{
OneBufferOwnerOrManyRef buffers(many_buffers, total_size);
return async_read_write_impl(tcp_socket, buffers, &State_AsyncReadWrite::do_write);
}
inline auto async_read(Async_TCPSocket& tcp_socket, std::span<char> data) noexcept
{
assert(data.size() <= (std::numeric_limits<std::uint32_t>::max)());
OneBufferOwnerOrManyRef buffer(BufferRef(data.data(), std::uint32_t(data.size())));
return async_read_write_impl(tcp_socket, buffer, &State_AsyncReadWrite::do_read);
}
inline auto async_read(Async_TCPSocket& tcp_socket
// `many_buffers` must be alive for a duration of the call.
, std::span<BufferRef> many_buffers)
{
OneBufferOwnerOrManyRef buffers(many_buffers);
return async_read_write_impl(tcp_socket, buffers, &State_AsyncReadWrite::do_read);
}
inline auto async_read(Async_TCPSocket& tcp_socket
// `many_buffers` must be alive for a duration of the call.
, std::span<BufferRef> many_buffers
// pre-calculated total size of `many_buffers`.
, std::size_t total_size)
{
OneBufferOwnerOrManyRef buffers(many_buffers, total_size);
return async_read_write_impl(tcp_socket, buffers, &State_AsyncReadWrite::do_read);
}
struct EndpointsList_IPv4
{
PADDRINFOEXW _address_list = nullptr;
explicit EndpointsList_IPv4(PADDRINFOEXW list) noexcept
: _address_list{list} {}
~EndpointsList_IPv4() { destroy(); }
EndpointsList_IPv4(const EndpointsList_IPv4&) = delete;
EndpointsList_IPv4& operator=(const EndpointsList_IPv4&) = delete;
EndpointsList_IPv4(EndpointsList_IPv4&& rhs) noexcept
: _address_list(std::exchange(rhs._address_list, nullptr)) { }
EndpointsList_IPv4& operator=(EndpointsList_IPv4&& rhs) noexcept
{
if (this != &rhs)
{
destroy();
_address_list = std::exchange(rhs._address_list, nullptr);
}
return *this;
}
struct iterator
{
PADDRINFOEXW _address_list = nullptr;
template<class Reference>
struct arrow_proxy
{
Reference _ref;
Reference* operator->()
{
return &_ref;
}
};
using iterator_category = std::forward_iterator_tag;
using value_type = const Endpoint_IPv4;
using reference = const Endpoint_IPv4;
using pointer = arrow_proxy<const Endpoint_IPv4>;
using difference_type = std::ptrdiff_t;
reference operator*() const { return get(); }
pointer operator->() const { return pointer{get()}; }
bool operator==(const iterator& rhs) const { return (_address_list == rhs._address_list); }
bool operator!=(const iterator& rhs) const { return (_address_list != rhs._address_list); }
Endpoint_IPv4 get() const
{
assert(_address_list);
assert(_address_list->ai_addrlen == sizeof(sockaddr_in));
const struct sockaddr_in* ipv4 =
reinterpret_cast<const struct sockaddr_in*>(_address_list->ai_addr);
Endpoint_IPv4 endpoint;
endpoint._ip_network = ipv4->sin_addr.s_addr;
endpoint._port_network = ipv4->sin_port;
return endpoint;
}
iterator operator++()
{
assert(_address_list);
_address_list = _address_list->ai_next;
return iterator{_address_list};
}
iterator operator++(int)
{
assert(_address_list);
PADDRINFOEXW current = _address_list;
_address_list = _address_list->ai_next;
return iterator{current};
}
};
iterator begin() { return iterator{_address_list}; }
iterator begin() const { return iterator{_address_list}; }
iterator end() { return iterator{}; }
iterator end() const { return iterator{}; }
private:
void destroy()
{
PADDRINFOEXW ptr = std::exchange(_address_list, nullptr);
if (ptr)
{
::FreeAddrInfoExW(ptr);
}
}
};
struct Resolve_Hint
{
int _type = 0;
int _protocol = 0;
static Resolve_Hint TCP()
{
Resolve_Hint hint;
hint._type = SOCK_STREAM;
hint._protocol = IPPROTO_TCP;
return hint;
}
static Resolve_Hint UDP()
{
Resolve_Hint hint;
hint._type = SOCK_DGRAM;
hint._protocol = IPPROTO_UDP;
return hint;
}
};
template<typename Receiver>
struct Operation_Resolve : Operation_Base
{
struct AddrInfo_Overlapped : WSAOVERLAPPED
{
using Callback = void (Operation_Resolve::*)(DWORD /*error*/, DWORD /*bytes*/);
Callback _callback = nullptr;
Operation_Resolve* _self = nullptr;
};
Receiver _receiver;
wi::IoCompletionPort* _iocp = nullptr;
Resolve_Hint _hint;
std::string_view _host_name;
std::string_view _service_name_or_port;
// Output.
wchar_t _whost_name[256]{};
wchar_t _wservice_name[256]{};
PADDRINFOEXW _results = nullptr;
AddrInfo_Overlapped _ov{{}, &Operation_Resolve::on_complete_WindowsThread, this};
IOCP_Overlapped _iocp_ov{{}, &Operation_Resolve::on_addrinfo_finish, this};
Helper_HandleStopToken<Receiver, Operation_Resolve> _cancel_impl{};
HANDLE _cancel_handle = INVALID_HANDLE_VALUE;
// Points to `_cancel_handle` when cancel is available.
std::atomic<HANDLE*> _atomic_stop{};
static void on_addrinfo_finish(void* user_data, const wi::PortEntry& entry, std::error_code ec)
{
Operation_Resolve* self = static_cast<Operation_Resolve*>(user_data);
if (self->_cancel_impl.try_finalize(self->_receiver))
{
// #XXX: There is race if someone asks to stop now.
self->_cancel_handle = nullptr; // Invalid now.
self->_atomic_stop = nullptr;
unifex::set_done(std::move(self->_receiver));
return;
}
if (ec)
{
unifex::set_error(std::move(self->_receiver), ec);
return;
}
// error, see on_complete_WindowsThread().
const DWORD error = DWORD(entry.completion_key);
if (error != 0)
{
unifex::set_error(std::move(self->_receiver)
, std::error_code(int(error), std::system_category()));
return;
}
unifex::set_value(std::move(self->_receiver)
, EndpointsList_IPv4{self->_results});
}
void on_complete_WindowsThread(DWORD error, DWORD bytes)
{
// #XXX: need to invalidate _cancel_handle/_atomic_stop there.
wi::PortEntry entry{};
entry.overlapped = _iocp_ov.ptr();
entry.completion_key = error;
entry.bytes_transferred = bytes;
std::error_code ec;
_iocp->post(entry, ec);
if (ec) // Bad. Invoking user code on external ws2_32.dll, TppWorkerThread.
{
on_addrinfo_finish(this, entry, ec);
}
}
static void CALLBACK OnAddrInfoEx_CompleteCallback(DWORD dwError, DWORD dwBytes, LPWSAOVERLAPPED lpOverlapped)
{
AddrInfo_Overlapped* ov = static_cast<AddrInfo_Overlapped*>(lpOverlapped);
Operation_Resolve& self = *ov->_self;
auto callback = ov->_callback;
(self.*callback)(dwError, dwBytes);
}
void try_stop() noexcept
{
HANDLE* cancel_handle = _atomic_stop.exchange(nullptr);
if (!cancel_handle)
{
// Operation is not yet started or is in finish callback.
return;
}
const INT error = ::GetAddrInfoExCancel(cancel_handle);
(void)error; // Not much can be done.
}
void start() & noexcept
{
// See also "Internationalized Domain Names":
// https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfoexw#internationalized-domain-names.
if (_host_name.size() > 0)
{
const int error = ::MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, _host_name.data()
, int(_host_name.size())
, _whost_name
, int(std::size(_whost_name)));
if (error == 0)
{
assert(false);
return;
}
}
if (_service_name_or_port.size() > 0)
{
const int error = ::MultiByteToWideChar(CP_ACP
, MB_PRECOMPOSED
, _service_name_or_port.data()
, int(_service_name_or_port.size())
, _wservice_name
, int(std::size(_wservice_name)));
if (error == 0)
{
assert(false);
return;
}
}
HANDLE* cancel_ptr = nullptr;
if (_cancel_impl.try_construct(_receiver, *this))
{
cancel_ptr = &_cancel_handle;
}
ADDRINFOEXW hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = _hint._type;
hints.ai_protocol = _hint._protocol;
const INT error = ::GetAddrInfoExW(_whost_name, _wservice_name
, NS_ALL
, nullptr // lpNspId
, &hints
, &_results
, nullptr // timeout
, &_ov
, &OnAddrInfoEx_CompleteCallback
, cancel_ptr);
if (error == 0)
{
wi::PortEntry entry{};
entry.overlapped = _iocp_ov.ptr();
entry.completion_key = 0;
entry.bytes_transferred = 0;
// Handles concurrent stop request if any.
on_addrinfo_finish(this, entry, std::error_code());
return;
}
if (error != WSA_IO_PENDING)
{
wi::PortEntry entry{};
entry.overlapped = _iocp_ov.ptr();
entry.completion_key = error;
entry.bytes_transferred = 0;
// Handles concurrent stop request if any.
on_addrinfo_finish(this, entry, std::error_code());
return;
}
// #XXX: there is race between doing a call to ::GetAddrInfoExW()
// - creating `_cancel_handle` - and stop request from
// stop source. In this case we have to way to actually interrupt
// ::GetAddrInfoExW() and will simply fail to stop.
if (cancel_ptr)
{
_atomic_stop = cancel_ptr;
}
}
};
struct Sender_Resolve : Sender_LogSimple<EndpointsList_IPv4, std::error_code>
{
wi::IoCompletionPort* _iocp;
Resolve_Hint _hint;
std::string_view _host_name;
std::string_view _service_name_or_port;
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_Resolve<Receiver_>{{}
, std::move(receiver), _iocp, _hint, _host_name, _service_name_or_port};
}
};
// IPv4.
inline Sender_Resolve async_resolve(wi::IoCompletionPort& iocp
, Resolve_Hint hint
, std::string_view host_name
// Either service name, like "http", see "%WINDIR%\system32\drivers\etc\services" on Windows
// OR port, like "80".
, std::string_view service_name_or_port = {})
{
return Sender_Resolve{{}, &iocp, hint, host_name, service_name_or_port};
}
// #XXX: seems like this can be implemented in terms of existing algos.
template<typename Receiver, typename EndpointsRange>
struct Operation_RangeConnect : Operation_Base
{
struct Receiver_Connect
{
Operation_RangeConnect* _self;
void set_value() && noexcept { _self->on_connect_success(); }
void set_error(std::error_code ec) && noexcept { _self->on_connect_error(ec); }
void set_error(std::exception_ptr) && noexcept { _self->on_connect_error(std::error_code(-1, std::system_category())); }
void set_done() && noexcept { assert(false); }
};
using Op = Operation_Connect<Receiver_Connect>;
using Iterator = typename EndpointsRange::iterator;
Receiver _receiver;
Async_TCPSocket* _socket = nullptr;
EndpointsRange _endpoints;
// Output.
Iterator _current_endpoint{};
std::error_code _last_error{};
unifex::manual_lifetime<Op> _op{};
void on_connect_success() noexcept
{
destroy_storage();
unifex::set_value(std::move(_receiver), *_current_endpoint);
}
void on_connect_error(std::error_code ec) noexcept
{
destroy_storage();
_last_error = ec;
++_current_endpoint;
start_next_connect();
}
void destroy_storage() noexcept
{
_op.destruct();
}
void start_next_connect()
{
if (_current_endpoint == std::end(_endpoints))
{
unifex::set_error(std::move(_receiver), _last_error);
return;
}
_op.construct_with([&]()
{
return unifex::connect(
_socket->async_connect(*_current_endpoint)
, Receiver_Connect{this});
});
unifex::start(_op.get());
}
void start() & noexcept
{
_last_error = std::error_code(-1, std::system_category()); // Empty.
_current_endpoint = std::begin(_endpoints);
start_next_connect();
}
};
template<typename EndpointsRange>
struct Sender_RangeConnect : Sender_LogSimple<Endpoint_IPv4, std::error_code>
{
Async_TCPSocket* _socket;
EndpointsRange _endpoints;
template<typename Receiver>
auto connect(Receiver&& receiver) && noexcept
{
using Receiver_ = std::remove_cvref_t<Receiver>;
return Operation_RangeConnect<Receiver_, EndpointsRange>{{}
, std::move(receiver), _socket, std::move(_endpoints)};
}
};
template<typename EndpointsRange>
inline auto async_connect(Async_TCPSocket& socket, EndpointsRange&& endpoints)
{
// #XXX: implement when_first() algorithm.
using EndpointsRange_ = std::remove_cvref_t<EndpointsRange>;
return Sender_RangeConnect<EndpointsRange_>{{}, &socket
, std::forward<EndpointsRange>(endpoints)};
}
struct StopReceiver
{
bool& _finish;
// Catch-all.
friend void tag_invoke(auto, StopReceiver&& self, auto&&...) noexcept
{
self._finish = true;
}
};
template<typename Sender>
static void IOCP_sync_wait(wi::IoCompletionPort& iocp, Sender&& sender)
{
bool finish = false;
auto op_state = unifex::connect(std::forward<Sender>(sender), StopReceiver{finish});
unifex::start(op_state);
std::error_code ec;
while (!finish)
{
wi::PortEntry entries[4];
for (const wi::PortEntry& entry : iocp.get_many(entries, ec))
{
IOCP_Overlapped* ov = static_cast<IOCP_Overlapped*>(entry.overlapped);
assert(ov);
assert(ov->_callback);
ov->_callback(ov->_user_data, entry, ec);
}
}
}
// Missing from unifex generic utilities.
struct Receiver_Detached
{
void* _ptr = nullptr;
void (*_free)(void*) = nullptr;
// Catch-all.
friend void tag_invoke(auto, Receiver_Detached&& self, auto&&...) noexcept
{
self._free(self._ptr);
}
};
template<typename Sender>
inline static auto start_detached(Sender&& sender)
{
using Op = decltype(unifex::connect(std::forward<Sender>(sender), Receiver_Detached{}));
void* ptr = malloc(sizeof(Op));
assert(ptr);
Receiver_Detached cleanup{ptr, [](void* ptr)
{
Op* op = static_cast<Op*>(ptr);
op->~Op();
free(ptr);
}};
auto* op = new(ptr) auto(unifex::connect(std::forward<Sender>(sender), std::move(cleanup)));
unifex::start(*op);
}
template<typename StopSource, typename Sender>
inline auto stop_with(StopSource& stop_source, Sender&& sender)
{
return unifex::with_query_value(
std::forward<Sender>(sender)
, unifex::get_stop_token
, stop_source.get_token());
}
| 32.897771 | 130 | 0.596088 | grishavanika |
3e9977c1a0e7d224e6d4a043c7f150dbab0fce2f | 899 | cpp | C++ | Chapter11/Exercise71/Exercise71.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | 4 | 2019-08-12T08:59:46.000Z | 2022-03-08T07:49:29.000Z | Chapter11/Exercise71/Exercise71.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | null | null | null | Chapter11/Exercise71/Exercise71.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | 5 | 2019-10-09T17:00:56.000Z | 2022-03-08T07:49:41.000Z | #include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
template<typename T>
class Position
{
public:
Position(T x, T y)
{
m_x = x;
m_y = y;
}
T const getX() { return m_x; }
T const getY() { return m_y; }
private:
T m_x;
T m_y;
};
int main()
{
Position<int> intPosition(1, 3);
Position<float> floatPosition(1.0f, 3.0f);
Position<long> longPosition(1.0, 3.0);
cout << "type: " << typeid(intPosition.getX()).name() << " X: " <<
intPosition.getX() << " Y: " << intPosition.getY() << endl;
cout << "type: " << typeid(floatPosition.getX()).name() << " X: " <<
floatPosition.getX() << " Y: " << floatPosition.getY() << endl;
cout << "type: " << typeid(longPosition.getX()).name() << " X: " <<
longPosition.getX() << " Y: " << longPosition.getY() << endl;
return 0;
}
| 27.242424 | 71 | 0.537264 | Archiit19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.