text
stringlengths 5
1.04M
|
|---|
#include "ula_tb.h"
void driver::drive(){
// Tempo para inicializacao
wait(1, SC_NS);
// Se SIZE = 16
#if SIZE == 16
//// ADD
cout << "//// Testes ADD:" << endl;
opcode = ADD;
// A = 4, B = 4, Z esperado = 8
A = "0x0004"; B = "0x0004";
wait(1, SC_NS);
// A = 4, B = - 4, Z esperado = 0, zero esperado = 1
A = "0x0004"; B = "0xfffc";
wait(1, SC_NS);
// A = -2, B = -2, Z esperado = -4
A = "0xfffe"; B = "0xfffe";
wait(1, SC_NS);
//// SUB
cout << "//// Testes SUB:" << endl;
opcode = SUB;
// A = 14, B = 10, Z esperado = 4
A = "0x000e"; B = "0x000a";
wait(1, SC_NS);
// A = 4, B = 8, Z esperado = - 4
A = "0x0004"; B = "0x0008";
wait(1, SC_NS);
// A = 14, B = -2, Z esperado = 16
A = "0x000e"; B = "0xfffe";
wait(1, SC_NS);
//// AND
cout << "//// Testes AND:" << endl;
opcode = AND;
// Z esperado = 0xf0f0
A = "0xffff"; B = "0xf0f0";
wait(1, SC_NS);
// Z esperado = 0x0000, zero esperado = 1
A = "0x0000"; B = "0xffff";
wait(1, SC_NS);
// Z esperado = 0xf000, zero esperado = 1
A = "0xff0f"; B = "0xf0f0";
wait(1, SC_NS);
//// OR
cout << "//// Testes OR:" << endl;
opcode = OR;
// Z esperado = 0xf0f0
A = "0xf0f0"; B = "0x0000";
wait(1, SC_NS);
// Z esperado = 0xffff
A = "0xffff"; B = "0x0000";
wait(1, SC_NS);
// Z esperado = 0x0f0f
A = "0x0000"; B = "0x0f0f";
wait(1, SC_NS);
//// NOT
cout << "//// Testes NOT:" << endl;
opcode = NOT;
// Z esperado 0xffff
A = "0x0000";
wait(1, SC_NS);
// Z esperado 0x0000, zero esperado = 1
A = "0xffff";
wait(1, SC_NS);
// Z esperado 0xf0f0
A = "0x0f0f";
wait(1, SC_NS);
//// XOR
cout << "//// Testes XOR:" << endl;
opcode = XOR;
// Z esperado 0x0f0f
A = "0x0f0f"; B = "0x0000";
wait(1, SC_NS);
// Z esperado 0xffff
A = "0xf0f0"; B = "0x0f0f";
wait(1, SC_NS);
// Z esperado 0x0000, zero esperado = 0
A = "0xf0f0"; B = "0xf0f0";
wait(1, SC_NS);
//// BYPASS
cout << "//// Testes BYPASS:" << endl;
opcode = BYPASS;
// Z esperado = 0x8449
A = "0x8449";
wait(1, SC_NS);
// Z esperado = 0x0000, zero = 1
A = "0x0000";
wait(1, SC_NS);
// Z esperado = 0x7193
A = "0x7193";
wait(1, SC_NS);
//// SLT
cout << "//// Testes SLT:" << endl;
opcode = SLT;
// A > B, Z esperado = 0, zero esperado = 1
A = "0x0001"; B = "0x0000";
wait(1, SC_NS);
// A < B, Z esperado = 1
A = "0xffff"; B = "0x0000";
wait(1, SC_NS);
// A = B, Z esperado = 0, zero esperado = 1
A = "0x0001"; B = "0x0001";
wait(1, SC_NS);
// Se SIZE = 32
#elif SIZE == 32
//// ADD
cout << "//// Testes ADD:" << endl;
opcode = ADD;
// A = 4, B = 4, Z esperado = 8
A = "0x00000004"; B = "0x00000004";
wait(1, SC_NS);
// A = 4, B = - 4, Z esperado = 0, zero esperado = 1
A = "0x00000004"; B = "0xfffffffc";
wait(1, SC_NS);
// A = -2, B = -2, Z esperado = -4
A = "0xfffffffe"; B = "0xfffffffe";
wait(1, SC_NS);
//// SUB
cout << "//// Testes SUB:" << endl;
opcode = SUB;
// A = 14, B = 10, Z esperado = 4
A = "0x0000000e"; B = "0x0000000a";
wait(1, SC_NS);
// A = 4, B = 8, Z esperado = - 4
A = "0x00000004"; B = "0x00000008";
wait(1, SC_NS);
// A = 14, B = -2, Z esperado = 16
A = "0x0000000e"; B = "0xfffffffe";
wait(1, SC_NS);
//// AND
cout << "//// Testes AND:" << endl;
opcode = AND;
// Z esperado = 0xf0f00000
A = "0xffff0000"; B = "0xf0f0ffff";
wait(1, SC_NS);
// Z esperado = 0x00000000, zero esperado = 1
A = "0xffff0000"; B = "0x0000ffff";
wait(1, SC_NS);
// Z esperado = 0xf0f00f0f
A = "0xffff0f0f"; B = "0xf0f0ffff";
wait(1, SC_NS);
//// OR
cout << "//// Testes OR:" << endl;
opcode = OR;
// Z esperado = 0xfffff0f0
A = "0xf0f0f0f0"; B = "0x0f0f0000";
wait(1, SC_NS);
// Z esperado = 0xffffffff
A = "0xffffffff"; B = "0x00000000";
wait(1, SC_NS);
// Z esperado = 0xffff0000
A = "0xf0f00000"; B = "0x0f0f0000";
wait(1, SC_NS);
//// NOT
cout << "//// Testes NOT:" << endl;
opcode = NOT;
// Z esperado 0x0000ffff
A = "0xffff0000";
wait(1, SC_NS);
// Z esperado 0x00000000, zero esperado = 1
A = "0xffffffff";
wait(1, SC_NS);
// Z esperado 0xffffffff
A = "0x00000000";
wait(1, SC_NS);
//// XOR
cout << "//// Testes XOR:" << endl;
opcode = XOR;
// Z esperado 0xf0f00f0f
A = "0xf0f0f0f0"; B = "0x0000ffff";
wait(1, SC_NS);
// Z esperado 0xffffffff
A = "0xf0f0f0f0"; B = "0x0f0f0f0f";
wait(1, SC_NS);
// Z esperado 0x00000000, zero esperado = 0
A = "0xf0f0f0f0"; B = "0xf0f0f0f0";
wait(1, SC_NS);
//// BYPASS
cout << "//// Testes BYPASS:" << endl;
opcode = BYPASS;
// Z esperado = 0x84496206
A = "0x84496206";
wait(1, SC_NS);
// Z esperado = 0x00000000, zero = 1
A = "0x00000000";
wait(1, SC_NS);
// Z esperado = 0x71936250
A = "0x71936250";
wait(1, SC_NS);
//// SLT
cout << "//// Testes SLT:" << endl;
opcode = SLT;
// A > B, Z esperado = 0, zero esperado = 1
A = "0x00000001"; B = "0x00000000";
wait(1, SC_NS);
// A < B, Z esperado = 1
A = "0x00000000"; B = "0x00000001";
wait(1, SC_NS);
// A = B, Z esperado = 0, zero esperado = 1
A = "0x00000001"; B = "0x00000001";
wait(1, SC_NS);
#endif
}
void monitor::monitora(){
cout << "Tempo " << sc_time_stamp() << ": ";
cout << "Z = 0x" << Z.read().to_string(SC_HEX, false) << "; zero = " << zero << endl << endl;
}
|
#pragma once
#include <iostream>
#include <complex>
using namespace std;
namespace solver{
class RealVariable{
private:
double number;
public:
RealVariable(double number = 0): number(number){}
//^//--------------------------------------------------------------------
friend RealVariable& operator^(RealVariable& n1, const double n2);
//-//--------------------------------------------------------------------
friend RealVariable& operator-(RealVariable& n1, RealVariable& n2);
friend RealVariable& operator-(RealVariable& n1, const double n2);
//+//--------------------------------------------------------------------
friend RealVariable& operator+(RealVariable& n1, RealVariable& n2);
friend RealVariable& operator+(const double n1, RealVariable& n2);
friend RealVariable& operator+(RealVariable& n1, const double n2);
//*//--------------------------------------------------------------------
friend RealVariable& operator*(const double n1, RealVariable& n2);
// / //------------------------------------------------------------------
friend RealVariable& operator/(RealVariable& n1, const double n2);
//==//-------------------------------------------------------------------
friend RealVariable& operator==(RealVariable& n1, RealVariable& n2);
friend RealVariable& operator==(RealVariable& n1, const double n2);
};//RealVariable
class ComplexVariable{
private:
complex<double> re;
complex<double> im;
public:
ComplexVariable (const double& re= 0.0,const double& im= 0.0): re(re), im(im) {}
//^//--------------------------------------------------------------------
friend ComplexVariable& operator^(ComplexVariable& n1, const double n2);
//-//--------------------------------------------------------------------
friend ComplexVariable& operator-(ComplexVariable& n1, ComplexVariable& n2);
friend ComplexVariable& operator-(ComplexVariable& n1, const double n2);
//+//--------------------------------------------------------------------
friend ComplexVariable& operator+(ComplexVariable& n1, ComplexVariable& n2);
friend ComplexVariable& operator+(const double n1, ComplexVariable& n2);
friend ComplexVariable& operator+(ComplexVariable& n1 ,complex<double> n2);
//*//--------------------------------------------------------------------
friend ComplexVariable& operator*(complex<double> n1,ComplexVariable& n2);
friend ComplexVariable& operator*(const double n1, ComplexVariable& n2);
// / //------------------------------------------------------------------
friend ComplexVariable& operator/(ComplexVariable& n1, const double n2);
//==//-------------------------------------------------------------------
friend ComplexVariable& operator==(ComplexVariable& n1, ComplexVariable& n2);
friend ComplexVariable& operator==(ComplexVariable& n1, const double n2);
};//ComplexVariable
double solve(RealVariable& x);
complex<double> solve(ComplexVariable& x);
}// namespace solver
|
#include "stdafx.h"
#include "P23.MetaTrader4.Manager.ClrWrapper.h"
void P23::MetaTrader4::Manager::ClrWrapper::LogsOut(int code, System::String^ source, System::String^ msg)
{
if (System::String::IsNullOrEmpty(source))
throw gcnew ArgumentNullException("source");
if (System::String::IsNullOrEmpty(msg))
throw gcnew ArgumentNullException("msg");
_manager->Manager->LogsOut(code, Convert(source), Convert(msg));
}
void P23::MetaTrader4::Manager::ClrWrapper::LogsMode(int mode)
{
_manager->Manager->LogsMode(mode);
}
|
/***************************************************************************
* Copyright 1998-2018 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 <boost/foreach.hpp>
#include "slg/core/namedobjectvector.h"
using namespace std;
using namespace luxrays;
using namespace slg;
//------------------------------------------------------------------------------
// NamedObjectVector
//------------------------------------------------------------------------------
NamedObjectVector::NamedObjectVector() {
}
NamedObjectVector::~NamedObjectVector() {
BOOST_FOREACH(NamedObject *o, objs)
delete o;
}
NamedObject *NamedObjectVector::DefineObj(NamedObject *newObj) {
const string &name = newObj->GetName();
if (IsObjDefined(name)) {
NamedObject *oldObj = objs[GetIndex(name)];
// Update name/object definition
const u_int index = GetIndex(name);
objs[index] = newObj;
name2index.left.erase(name);
name2index.insert(Name2IndexType::value_type(name, index));
index2obj.left.erase(index);
index2obj.insert(Index2ObjType::value_type(index, newObj));
return oldObj;
} else {
// Add the new name/object definition
const u_int index = objs.size();
objs.push_back(newObj);
name2index.insert(Name2IndexType::value_type(name, index));
index2obj.insert(Index2ObjType::value_type(index, newObj));
return NULL;
}
}
bool NamedObjectVector::IsObjDefined(const std::string &name) const {
return (name2index.left.count(name) > 0);
}
const NamedObject *NamedObjectVector::GetObj(const std::string &name) const {
return objs[GetIndex(name)];
}
const NamedObject *NamedObjectVector::GetObj(const u_int index) const {
return objs[index];
}
u_int NamedObjectVector::GetIndex(const std::string &name) const {
Name2IndexType::left_const_iterator it = name2index.left.find(name);
if (it == name2index.left.end())
throw runtime_error("Reference to an undefined NamedObject: " + name);
else
return it->second;
}
u_int NamedObjectVector::GetIndex(const NamedObject *o) const {
Index2ObjType::right_const_iterator it = index2obj.right.find(o);
if (it == index2obj.right.end())
throw runtime_error("Reference to an undefined NamedObject: " + boost::lexical_cast<string>(o));
else
return it->second;
}
const std::string &NamedObjectVector::GetName(const u_int index) const {
Name2IndexType::right_const_iterator it = name2index.right.find(index);
if (it == name2index.right.end())
throw runtime_error("Reference to an undefined NamedObject: " + index);
else
return it->second;
}
const std::string &NamedObjectVector::GetName(const NamedObject *o) const {
Name2IndexType::right_const_iterator it = name2index.right.find(GetIndex(o));
if (it == name2index.right.end())
throw runtime_error("Reference to an undefined NamedObject: " + boost::lexical_cast<string>(o));
else
return it->second;
}
u_int NamedObjectVector::GetSize()const {
return static_cast<u_int>(objs.size());
}
void NamedObjectVector::GetNames(std::vector<std::string> &names) const {
const u_int size = GetSize();
names.resize(size);
for (u_int i = 0; i < size; ++i)
names[i] = GetName(i);
}
std::vector<NamedObject *> &NamedObjectVector::GetObjs() {
return objs;
}
void NamedObjectVector::DeleteObj(const std::string &name) {
const u_int index = GetIndex(name);
objs.erase(objs.begin() + index);
name2index.left.erase(name);
index2obj.left.erase(index);
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/animation/tween.h"
#include <math.h>
#if defined(OS_WIN)
#include <float.h>
#endif
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/test/gfx_util.h"
namespace gfx {
namespace {
double next_double(double d) {
#if defined(OS_WIN)
return _nextafter(d, d + 1);
#else
// Step two units of least precision towards positive infinity. On some 32
// bit x86 compilers a single step was not enough due to loss of precision in
// optimized code.
return nextafter(nextafter(d, d + 1), d + 1);
#endif
}
// Validates that the same interpolations are made as in Blink.
TEST(TweenTest, ColorValueBetween) {
// From blink's AnimatableColorTest.
EXPECT_SKCOLOR_EQ(0xFF00FF00,
Tween::ColorValueBetween(-10.0, 0xFF00FF00, 0xFF00FF00));
EXPECT_SKCOLOR_EQ(0xFF00FF00,
Tween::ColorValueBetween(-10.0, 0xFF00FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(0xFF00FF00,
Tween::ColorValueBetween(0.0, 0xFF00FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(0xFF01FE01,
Tween::ColorValueBetween(1.0 / 255, 0xFF00FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(0xFF808080,
Tween::ColorValueBetween(0.5, 0xFF00FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(
0xFFFE01FE,
Tween::ColorValueBetween(254.0 / 255.0, 0xFF00FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(0xFFFF00FF,
Tween::ColorValueBetween(1.0, 0xFF00FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(0xFFFF00FF,
Tween::ColorValueBetween(10.0, 0xFF00FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(0xFF0C253E,
Tween::ColorValueBetween(3.0 / 16.0, 0xFF001020, 0xFF4080C0));
EXPECT_SKCOLOR_EQ(0x80FF00FF,
Tween::ColorValueBetween(0.5, 0x0000FF00, 0xFFFF00FF));
EXPECT_SKCOLOR_EQ(0x60AA55AA,
Tween::ColorValueBetween(0.5, 0x4000FF00, 0x80FF00FF));
EXPECT_SKCOLOR_EQ(0x60FFAAFF,
Tween::ColorValueBetween(0.5, 0x40FF00FF, 0x80FFFFFF));
EXPECT_SKCOLOR_EQ(0x103060A0,
Tween::ColorValueBetween(0.5, 0x10204080, 0x104080C0));
}
// Ensures that each of the 3 integers in [0, 1, 2] ae selected with equal
// weight.
TEST(TweenTest, IntValueBetween) {
EXPECT_EQ(0, Tween::IntValueBetween(0.0, 0, 2));
EXPECT_EQ(0, Tween::IntValueBetween(0.5 / 3.0, 0, 2));
EXPECT_EQ(0, Tween::IntValueBetween(1.0 / 3.0, 0, 2));
EXPECT_EQ(1, Tween::IntValueBetween(next_double(1.0 / 3.0), 0, 2));
EXPECT_EQ(1, Tween::IntValueBetween(1.5 / 3.0, 0, 2));
EXPECT_EQ(1, Tween::IntValueBetween(2.0 / 3.0, 0, 2));
EXPECT_EQ(2, Tween::IntValueBetween(next_double(2.0 / 3.0), 0, 2));
EXPECT_EQ(2, Tween::IntValueBetween(2.5 / 3.0, 0, 2));
EXPECT_EQ(2, Tween::IntValueBetween(3.0 / 3.0, 0, 2));
}
TEST(TweenTest, IntValueBetweenNegative) {
EXPECT_EQ(-2, Tween::IntValueBetween(0.0, -2, 0));
EXPECT_EQ(-2, Tween::IntValueBetween(0.5 / 3.0, -2, 0));
EXPECT_EQ(-2, Tween::IntValueBetween(1.0 / 3.0, -2, 0));
EXPECT_EQ(-1, Tween::IntValueBetween(next_double(1.0 / 3.0), -2, 0));
EXPECT_EQ(-1, Tween::IntValueBetween(1.5 / 3.0, -2, 0));
EXPECT_EQ(-1, Tween::IntValueBetween(2.0 / 3.0, -2, 0));
EXPECT_EQ(0, Tween::IntValueBetween(next_double(2.0 / 3.0), -2, 0));
EXPECT_EQ(0, Tween::IntValueBetween(2.5 / 3.0, -2, 0));
EXPECT_EQ(0, Tween::IntValueBetween(3.0 / 3.0, -2, 0));
}
TEST(TweenTest, IntValueBetweenReverse) {
EXPECT_EQ(2, Tween::IntValueBetween(0.0, 2, 0));
EXPECT_EQ(2, Tween::IntValueBetween(0.5 / 3.0, 2, 0));
EXPECT_EQ(2, Tween::IntValueBetween(1.0 / 3.0, 2, 0));
EXPECT_EQ(1, Tween::IntValueBetween(next_double(1.0 / 3.0), 2, 0));
EXPECT_EQ(1, Tween::IntValueBetween(1.5 / 3.0, 2, 0));
EXPECT_EQ(1, Tween::IntValueBetween(2.0 / 3.0, 2, 0));
EXPECT_EQ(0, Tween::IntValueBetween(next_double(2.0 / 3.0), 2, 0));
EXPECT_EQ(0, Tween::IntValueBetween(2.5 / 3.0, 2, 0));
EXPECT_EQ(0, Tween::IntValueBetween(3.0 / 3.0, 2, 0));
}
TEST(TweenTest, LinearIntValueBetween) {
EXPECT_EQ(0, Tween::LinearIntValueBetween(0.0, 0, 2));
EXPECT_EQ(0, Tween::LinearIntValueBetween(0.5 / 4.0, 0, 2));
EXPECT_EQ(0, Tween::LinearIntValueBetween(0.99 / 4.0, 0, 2));
EXPECT_EQ(1, Tween::LinearIntValueBetween(1.0 / 4.0, 0, 2));
EXPECT_EQ(1, Tween::LinearIntValueBetween(1.5 / 4.0, 0, 2));
EXPECT_EQ(1, Tween::LinearIntValueBetween(2.0 / 4.0, 0, 2));
EXPECT_EQ(1, Tween::LinearIntValueBetween(2.5 / 4.0, 0, 2));
EXPECT_EQ(1, Tween::LinearIntValueBetween(2.99 / 4.0, 0, 2));
EXPECT_EQ(2, Tween::LinearIntValueBetween(3.0 / 4.0, 0, 2));
EXPECT_EQ(2, Tween::LinearIntValueBetween(3.5 / 4.0, 0, 2));
EXPECT_EQ(2, Tween::LinearIntValueBetween(4.0 / 4.0, 0, 2));
}
TEST(TweenTest, LinearIntValueBetweenNegative) {
EXPECT_EQ(-2, Tween::LinearIntValueBetween(0.0, -2, 0));
EXPECT_EQ(-2, Tween::LinearIntValueBetween(0.5 / 4.0, -2, 0));
EXPECT_EQ(-2, Tween::LinearIntValueBetween(0.99 / 4.0, -2, 0));
EXPECT_EQ(-1, Tween::LinearIntValueBetween(1.0 / 4.0, -2, 0));
EXPECT_EQ(-1, Tween::LinearIntValueBetween(1.5 / 4.0, -2, 0));
EXPECT_EQ(-1, Tween::LinearIntValueBetween(2.0 / 4.0, -2, 0));
EXPECT_EQ(-1, Tween::LinearIntValueBetween(2.5 / 4.0, -2, 0));
EXPECT_EQ(-1, Tween::LinearIntValueBetween(2.99 / 4.0, -2, 0));
EXPECT_EQ(0, Tween::LinearIntValueBetween(3.0 / 4.0, -2, 0));
EXPECT_EQ(0, Tween::LinearIntValueBetween(3.5 / 4.0, -2, 0));
EXPECT_EQ(0, Tween::LinearIntValueBetween(4.0 / 4.0, -2, 0));
}
} // namespace
} // namespace gfx
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/cast_channel/keep_alive_delegate.h"
#include <stdint.h>
#include <memory>
#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/time/tick_clock.h"
#include "base/timer/mock_timer.h"
#include "base/timer/timer.h"
#include "base/values.h"
#include "components/cast_channel/cast_test_util.h"
#include "net/base/net_errors.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::Sequence;
namespace cast_channel {
namespace {
const int64_t kTestPingTimeoutMillis = 1000;
const int64_t kTestLivenessTimeoutMillis = 10000;
CastMessage CreateNonKeepAliveMessage(const std::string& message_type) {
CastMessage output;
output.set_protocol_version(CastMessage::CASTV2_1_0);
output.set_source_id("source");
output.set_destination_id("receiver");
output.set_namespace_("some.namespace");
output.set_payload_type(
CastMessage::PayloadType::CastMessage_PayloadType_STRING);
base::DictionaryValue type_dict;
type_dict.SetString("type", message_type);
CHECK(base::JSONWriter::Write(type_dict, output.mutable_payload_utf8()));
return output;
}
// Extends MockTimer with a mockable method ResetTriggered() which permits
// test code to set GMock expectations for Timer::Reset().
class MockTimerWithMonitoredReset : public base::MockRetainingOneShotTimer {
public:
MockTimerWithMonitoredReset() {}
~MockTimerWithMonitoredReset() override {}
// Instrumentation point for determining how many times Reset() was called.
MOCK_METHOD0(ResetTriggered, void(void));
MOCK_METHOD0(StopTriggered, void(void));
// Passes through the Reset call to the base MockTimer and visits the mock
// ResetTriggered method.
void Reset() override {
base::MockRetainingOneShotTimer::Reset();
ResetTriggered();
}
void Stop() override {
base::MockRetainingOneShotTimer::Stop();
StopTriggered();
}
};
class KeepAliveDelegateTest : public testing::Test {
public:
using ChannelError = ::cast_channel::ChannelError;
KeepAliveDelegateTest() {}
~KeepAliveDelegateTest() override {}
protected:
void SetUp() override {
inner_delegate_ = new MockCastTransportDelegate;
logger_ = new Logger();
keep_alive_ = std::make_unique<KeepAliveDelegate>(
&socket_, logger_, base::WrapUnique(inner_delegate_),
base::TimeDelta::FromMilliseconds(kTestPingTimeoutMillis),
base::TimeDelta::FromMilliseconds(kTestLivenessTimeoutMillis));
liveness_timer_ = new MockTimerWithMonitoredReset;
ping_timer_ = new MockTimerWithMonitoredReset;
EXPECT_CALL(*liveness_timer_, StopTriggered()).Times(0);
EXPECT_CALL(*ping_timer_, StopTriggered()).Times(0);
keep_alive_->SetTimersForTest(base::WrapUnique(ping_timer_),
base::WrapUnique(liveness_timer_));
}
// Runs all pending tasks in the message loop.
void RunPendingTasks() {
base::RunLoop run_loop;
run_loop.RunUntilIdle();
}
base::test::SingleThreadTaskEnvironment task_environment_;
MockCastSocket socket_;
std::unique_ptr<KeepAliveDelegate> keep_alive_;
scoped_refptr<Logger> logger_;
MockCastTransportDelegate* inner_delegate_;
MockTimerWithMonitoredReset* liveness_timer_;
MockTimerWithMonitoredReset* ping_timer_;
private:
DISALLOW_COPY_AND_ASSIGN(KeepAliveDelegateTest);
};
TEST_F(KeepAliveDelegateTest, TestErrorHandledBeforeStarting) {
EXPECT_CALL(*inner_delegate_, OnError(ChannelError::CONNECT_ERROR));
keep_alive_->OnError(ChannelError::CONNECT_ERROR);
}
TEST_F(KeepAliveDelegateTest, TestPing) {
EXPECT_CALL(*socket_.mock_transport(),
SendMessage(EqualsProto(CreateKeepAlivePingMessage()), _))
.WillOnce(PostCompletionCallbackTask<1>(net::OK));
EXPECT_CALL(*inner_delegate_, Start());
EXPECT_CALL(*ping_timer_, ResetTriggered()).Times(2);
EXPECT_CALL(*liveness_timer_, ResetTriggered()).Times(3);
EXPECT_CALL(*ping_timer_, StopTriggered());
keep_alive_->Start();
ping_timer_->Fire();
EXPECT_FALSE(ping_timer_->IsRunning());
keep_alive_->OnMessage(CreateKeepAlivePongMessage());
RunPendingTasks();
EXPECT_TRUE(ping_timer_->IsRunning());
}
TEST_F(KeepAliveDelegateTest, TestPingFailed) {
EXPECT_CALL(*socket_.mock_transport(),
SendMessage(EqualsProto(CreateKeepAlivePingMessage()), _))
.WillOnce(PostCompletionCallbackTask<1>(net::ERR_CONNECTION_RESET));
EXPECT_CALL(*inner_delegate_, Start());
EXPECT_CALL(*inner_delegate_, OnError(ChannelError::CAST_SOCKET_ERROR));
EXPECT_CALL(*ping_timer_, ResetTriggered()).Times(1);
EXPECT_CALL(*liveness_timer_, ResetTriggered()).Times(1);
EXPECT_CALL(*liveness_timer_, StopTriggered());
EXPECT_CALL(*ping_timer_, StopTriggered()).Times(2);
keep_alive_->Start();
ping_timer_->Fire();
RunPendingTasks();
EXPECT_EQ(ChannelEvent::PING_WRITE_ERROR,
logger_->GetLastError(socket_.id()).channel_event);
EXPECT_EQ(net::ERR_CONNECTION_RESET,
logger_->GetLastError(socket_.id()).net_return_value);
}
TEST_F(KeepAliveDelegateTest, TestPingAndLivenessTimeout) {
EXPECT_CALL(*socket_.mock_transport(),
SendMessage(EqualsProto(CreateKeepAlivePingMessage()), _))
.WillOnce(PostCompletionCallbackTask<1>(net::OK));
EXPECT_CALL(*inner_delegate_, OnError(ChannelError::PING_TIMEOUT));
EXPECT_CALL(*inner_delegate_, Start());
EXPECT_CALL(*ping_timer_, ResetTriggered()).Times(1);
EXPECT_CALL(*liveness_timer_, ResetTriggered()).Times(2);
EXPECT_CALL(*liveness_timer_, StopTriggered()).Times(2);
EXPECT_CALL(*ping_timer_, StopTriggered()).Times(2);
keep_alive_->Start();
ping_timer_->Fire();
liveness_timer_->Fire();
RunPendingTasks();
}
TEST_F(KeepAliveDelegateTest, TestResetTimersAndPassthroughAllOtherTraffic) {
CastMessage other_message = CreateNonKeepAliveMessage("someMessageType");
EXPECT_CALL(*inner_delegate_, OnMessage(EqualsProto(other_message)));
EXPECT_CALL(*inner_delegate_, Start());
EXPECT_CALL(*ping_timer_, ResetTriggered()).Times(2);
EXPECT_CALL(*liveness_timer_, ResetTriggered()).Times(2);
keep_alive_->Start();
keep_alive_->OnMessage(other_message);
RunPendingTasks();
}
TEST_F(KeepAliveDelegateTest, TestPassthroughMessagesAfterError) {
CastMessage message = CreateNonKeepAliveMessage("someMessageType");
CastMessage message_after_error =
CreateNonKeepAliveMessage("someMessageType2");
CastMessage late_ping_message = CreateKeepAlivePingMessage();
EXPECT_CALL(*inner_delegate_, Start()).Times(1);
EXPECT_CALL(*ping_timer_, ResetTriggered()).Times(2);
EXPECT_CALL(*liveness_timer_, ResetTriggered()).Times(2);
EXPECT_CALL(*liveness_timer_, StopTriggered()).Times(1);
EXPECT_CALL(*ping_timer_, StopTriggered()).Times(1);
Sequence message_and_error_sequence;
EXPECT_CALL(*inner_delegate_, OnMessage(EqualsProto(message)))
.Times(1)
.InSequence(message_and_error_sequence)
.RetiresOnSaturation();
EXPECT_CALL(*inner_delegate_, OnError(ChannelError::INVALID_MESSAGE))
.Times(1)
.InSequence(message_and_error_sequence);
EXPECT_CALL(*inner_delegate_, OnMessage(EqualsProto(message_after_error)))
.Times(1)
.InSequence(message_and_error_sequence)
.RetiresOnSaturation();
EXPECT_CALL(*inner_delegate_, OnMessage(EqualsProto(late_ping_message)))
.Times(0)
.InSequence(message_and_error_sequence)
.RetiresOnSaturation();
// Start, process one message, then error-out. KeepAliveDelegate will
// automatically stop itself.
keep_alive_->Start();
keep_alive_->OnMessage(message);
RunPendingTasks();
keep_alive_->OnError(ChannelError::INVALID_MESSAGE);
RunPendingTasks();
// Process a non-PING/PONG message and expect it to pass through.
keep_alive_->OnMessage(message_after_error);
RunPendingTasks();
// Process a late-arriving PING/PONG message, which should have no effect.
keep_alive_->OnMessage(late_ping_message);
RunPendingTasks();
}
TEST_F(KeepAliveDelegateTest, TestLivenessTimerResetAfterSendingMessage) {
scoped_refptr<base::TestMockTimeTaskRunner> mock_time_task_runner(
new base::TestMockTimeTaskRunner());
auto liveness_timer = std::make_unique<base::RetainingOneShotTimer>(
mock_time_task_runner->GetMockTickClock());
auto ping_timer = std::make_unique<base::RetainingOneShotTimer>(
mock_time_task_runner->GetMockTickClock());
ping_timer->SetTaskRunner(mock_time_task_runner);
liveness_timer->SetTaskRunner(mock_time_task_runner);
keep_alive_->SetTimersForTest(std::move(ping_timer),
std::move(liveness_timer));
// At time 0, start.
EXPECT_CALL(*inner_delegate_, Start());
keep_alive_->Start();
EXPECT_CALL(*socket_.mock_transport(),
SendMessage(EqualsProto(CreateKeepAlivePingMessage()), _))
.WillOnce(PostCompletionCallbackTask<1>(net::OK));
// Forward 1s, at time 1, fire ping timer.
mock_time_task_runner->FastForwardBy(
base::TimeDelta::FromMilliseconds(kTestPingTimeoutMillis));
// Forward 9s, at Time 10, do not fire liveness timer.
EXPECT_CALL(*inner_delegate_, OnError(_)).Times(0);
mock_time_task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(
kTestLivenessTimeoutMillis - kTestPingTimeoutMillis));
// Forward 1s, at time 11s, fire liveness timer.
EXPECT_CALL(*inner_delegate_, OnError(_));
mock_time_task_runner->FastForwardBy(
base::TimeDelta::FromMilliseconds(kTestPingTimeoutMillis));
}
} // namespace
} // namespace cast_channel
|
//////////////////////////////////////////////////////////////////////////////
// NOTICE:
//
// ADLib, Prop and their related set of tools and documentation are in the
// public domain. The author(s) of this software reserve no copyrights on
// the source code and any code generated using the tools. You are encouraged
// to use ADLib and Prop to develop software, in both academic and commercial
// settings, and are welcomed to incorporate any part of ADLib and Prop into
// your programs.
//
// Although you are under no obligation to do so, we strongly recommend that
// you give away all software developed using our tools.
//
// We also ask that credit be given to us when ADLib and/or Prop are used in
// your programs, and that this notice be preserved intact in all the source
// code.
//
// This software is still under development and we welcome(read crave for)
// any suggestions and help from the users.
//
// Allen Leung
// 1994
//////////////////////////////////////////////////////////////////////////////
#include <AD/automata/predict.h>
//////////////////////////////////////////////////////////////////////////////
// Constructor and destructor
//////////////////////////////////////////////////////////////////////////////
PredictSet:: PredictSet( const Grammar& g, Mem& m) : PredictSet::Super(g,m)
{
predict_set = (BitSet**)m.m_alloc(sizeof(BitSet*) * g.size());
int set_size = g.max_terminal() + 1;
for (Rule r = g.size() - 1; r >= 0; r--)
predict_set[r] = new (m, set_size) BitSet;
conflict_set = new (m, set_size) BitSet;
}
PredictSet::~PredictSet()
{}
|
/*
Copyright (c) 2002-2009 Tampere University.
This file is part of TTA-Based Codesign Environment (TCE).
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
* @file IUPortCode.cc
*
* Implementation of IUPortCode class.
*
* @author Lasse Laasonen 2005 (lasse.laasonen-no.spam-tut.fi)
* @note rating: red
*/
#include <string>
#include "IUPortCode.hh"
#include "SocketCodeTable.hh"
#include "ObjectState.hh"
using std::string;
const std::string IUPortCode::OSNAME_IU_PORT_CODE = "iu_port_code";
/**
* The constructor.
*
* Registers the created instance to the given socket code table
* automatically.
*
* @param immediateUnit Name of the immediate unit.
* @param encoding The encoding for the register file port.
* @param extraBits The number of extra zero bits in the encoding.
* @param indexWidth The number of bits reserved for the register index.
* @param parent The parent socket code table.
* @exception ObjectAlreadyExists If the socket code table has an encoding
* defined for the same port already, or if
* the encoding is ambiguous with another
* encoding in the same socket code table.
* @exception OutOfRange If some of the given values is out of range.
*/
IUPortCode::IUPortCode(
const std::string& immediateUnit, unsigned int encoding,
unsigned int extraBits, int indexWidth, SocketCodeTable& parent)
: PortCode(immediateUnit, encoding, extraBits, indexWidth) {
setParent(NULL);
parent.addIUPortCode(*this);
setParent(&parent);
}
/**
* The constructor.
*
* Creates an IU port code without port encoding. That is, the port
* code consists of mere register index. This is useful if the parent
* socket code table does not contain other port codes. Registers the
* created instance to the given socket code table automatically.
*
* @param immediateUnit Name of the immediate unit.
* @param indexWidth The number of bits reserved for the register index.
* @param parent The parent socket code table.
* @exception ObjectAlreadyExists If the socket code table has an encoding
* defined for the same port already, or if
* the encoding is ambiguous with another
* encoding in the same socket code table.
* @exception OutOfRange If some of the given values is out of range.
*/
IUPortCode::IUPortCode(
const std::string& immediateUnit, int indexWidth, SocketCodeTable& parent)
: PortCode(immediateUnit, indexWidth) {
setParent(NULL);
parent.addIUPortCode(*this);
setParent(&parent);
}
/**
* The constructor.
*
* Loads the state of the object from the given ObjectState tree.
*
* @param state The ObjectState tree.
* @param parent The parent encoding map.
* @exception ObjectStateLoadingException If an error occurs while loading
* the state.
* @exception ObjectAlreadyExists If the socket code table has an encoding
* defined for the same port already, or if
* the encoding is ambiguous with another
* encoding in the same socket code table.
*/
IUPortCode::IUPortCode(const ObjectState* state, SocketCodeTable& parent)
: PortCode(state) {
if (state->name() != OSNAME_IU_PORT_CODE) {
const string procName = "IUPortCode::IUPortCode";
throw ObjectStateLoadingException(__FILE__, __LINE__, procName);
}
setParent(NULL);
parent.addIUPortCode(*this);
setParent(&parent);
}
/**
* The destructor.
*/
IUPortCode::~IUPortCode() {
SocketCodeTable* parent = this->parent();
setParent(NULL);
parent->removeIUPortCode(*this);
}
/**
* Saves the state of the object to an ObjectState tree.
*
* @return The newly created ObjectState tree.
*/
ObjectState*
IUPortCode::saveState() const {
ObjectState* state = PortCode::saveState();
state->setName(OSNAME_IU_PORT_CODE);
return state;
}
|
// Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#include <lexy/dsl/base.hpp>
// Just to test that the header compiles.
|
#pragma once
#include <cstdbool>
#include <cstdint>
#include "commonstate.hpp"
#include "param.hpp"
#include "board.hpp"
namespace ros_flight {
class Mux {
public:
enum class control_type_t
{
RATE, // Channel is is in rate mode (mrad/s)
ANGLE, // Channel command is in angle mode (mrad)
THROTTLE, // Channel is direcly controlling throttle max/1000
ALTITUDE, // Channel is commanding a specified altitude in cm
MOTOR_DIRECT // Channel directly passes PWM input to the mixer
};
struct control_channel_t
{
bool active; // Whether or not the channel is active
control_type_t type; // What type the channel is
float value; // The value of the channel
};
struct control_t
{
control_channel_t x;
control_channel_t y;
control_channel_t z;
control_channel_t F;
} ;
public:
void init(CommonState* _common_state, Board* _board, Params* _params);
bool mux_inputs();
control_t& rc_control() { return _rc_control; }
control_t& offboard_control() { return _offboard_control; }
control_t& combined_control() { return _combined_control; }
void set_new_command(bool val) { _new_command = val; }
private:
CommonState* common_state;
Params* params;
Board* board;
control_t _rc_control;
control_t _offboard_control;
control_t _combined_control;
bool _new_command;
control_t _failsafe_control = {
{true, Mux::control_type_t::ANGLE, 0.0},
{true, Mux::control_type_t::ANGLE, 0.0},
{true, Mux::control_type_t::RATE, 0.0},
{true, Mux::control_type_t::THROTTLE, 0.0}};
};
/************************************************** Implementation ***************************************************************/
void Mux::init(CommonState* _common_state, Board* _board, Params* _params)
{
params = _params;
common_state = _common_state;
board = _board;
}
bool Mux::mux_inputs()
{
if (!_new_command)
{
// we haven't received any new commands, so we shouldn't do anything
return false;
}
// otherwise combine the new commands
if(common_state->get_armed_state() == CommonState::FAILSAFE_ARMED || common_state->get_armed_state() == CommonState::FAILSAFE_DISARMED)
{
_combined_control = _failsafe_control;
}
else
{
if (_rc_control.x.active)
{
_combined_control.x = _rc_control.x;
}
else if (_offboard_control.x.active)
{
_combined_control.x = _offboard_control.x;
}
else
{
// default to taking RC if neither is publishing
_combined_control.x = _rc_control.x;
_combined_control.x.active = true;
}
if (_rc_control.y.active)
{
_combined_control.y = _rc_control.y;
}
else if (_offboard_control.y.active)
{
_combined_control.y = _offboard_control.y;
}
else
{
// default to taking RC if neither is publishing
_combined_control.y = _rc_control.y;
_combined_control.y.active = true;
}
if (_rc_control.z.active)
{
_combined_control.z = _rc_control.z;
}
else if (_offboard_control.z.active)
{
_combined_control.z = _offboard_control.z;
}
else
{
_combined_control.z = _rc_control.z;
_combined_control.z.active = true;
}
if (params->get_param_int(Params::PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE))
{
if (_offboard_control.F.active)
{
if (_rc_control.F.type == Mux::control_type_t::THROTTLE && _offboard_control.F.type == Mux::control_type_t::THROTTLE)
{
_combined_control.F.value = (_rc_control.F.value > _offboard_control.F.value) ?
_offboard_control.F.value : _rc_control.F.value;
_combined_control.F.type = Mux::control_type_t::THROTTLE;
_combined_control.F.active = true;
}
else
{
// I'm still not quite sure how to handle the mixed altitude/throttle cases
// for now, just pass the rc along. I expect that what we really need to do
// is run the altitude controller here so we can compare throttle to throttle
_combined_control.F = _rc_control.F;
}
}
}
else // no min throttle check
{
if (_rc_control.F.active)
{
_combined_control.F = _rc_control.F;
}
else if (_offboard_control.F.active)
{
_combined_control.F = _offboard_control.F;
}
else
{
_combined_control.F = _rc_control.F;
_combined_control.F.active = true;
}
}
// Light to indicate override
if (_rc_control.x.active || _rc_control.y.active || _rc_control.z.active || _rc_control.F.active)
{
board->set_led(0, true);
}
else
{
board->set_led(0, false);
}
}
// reset the new command flag
_new_command = false;
return true;
}
} //namespace
|
/*
-----------------------------------------------------------------------------------------------
Copyright (C) 2013 Henry van Merode. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------------------------
*/
#include "ParticleUniversePCH.h"
#ifndef PARTICLE_UNIVERSE_EXPORTS
#define PARTICLE_UNIVERSE_EXPORTS
#endif
#include "ParticleAffectors/ParticleUniverseVelocityMatchingAffector.h"
namespace ParticleUniverse
{
// Constants
const Real VelocityMatchingAffector::DEFAULT_RADIUS = 100.0f;
//-----------------------------------------------------------------------
VelocityMatchingAffector::VelocityMatchingAffector(void) :
ParticleAffector(),
mRadius(DEFAULT_RADIUS)
{
}
//-----------------------------------------------------------------------
Real VelocityMatchingAffector::getRadius(void) const
{
return mRadius;
}
//-----------------------------------------------------------------------
void VelocityMatchingAffector::setRadius(Real radius)
{
mRadius = radius;
}
//-----------------------------------------------------------------------
void VelocityMatchingAffector::_prepare(ParticleTechnique* particleTechnique)
{
// Activate spatial hashing
particleTechnique->setSpatialHashingUsed(true);
}
//-----------------------------------------------------------------------
void VelocityMatchingAffector::_unprepare(ParticleTechnique* particleTechnique)
{
// Activate spatial hashing
particleTechnique->setSpatialHashingUsed(false);
}
//-----------------------------------------------------------------------
void VelocityMatchingAffector::_affect(ParticleTechnique* particleTechnique, Particle* particle, Real timeElapsed)
{
// Determine neighbouring particles.
SpatialHashTable<Particle*>* hashtable = particleTechnique->getSpatialHashTable();
if (hashtable)
{
SpatialHashTable<Particle*>::HashTableCell cell = hashtable->getCell(particle->position);
if (cell.empty())
return;
unsigned int size = static_cast<unsigned int>(cell.size());
Vector3 sumDirection = Vector3::ZERO;
Vector3 diff = Vector3::ZERO;
unsigned int count = 0;
for (unsigned int i = 0; i < size; ++i)
{
Particle* p = cell[i];
// Don't check if it is the same particle
if (particle != p)
{
// Validate whether the neighbouring particle is within range
diff = p->position - particle->position;
if (diff.length() < mRadius)
{
sumDirection += p->direction;
count++;
}
}
}
// Adjust direction
if (count > 0)
{
sumDirection /= (Real)count;
particle->direction += (sumDirection - particle->direction) * timeElapsed;
}
}
}
//-----------------------------------------------------------------------
void VelocityMatchingAffector::copyAttributesTo (ParticleAffector* affector)
{
ParticleAffector::copyAttributesTo(affector);
VelocityMatchingAffector* velocityMatchingAffector = static_cast<VelocityMatchingAffector*>(affector);
velocityMatchingAffector->mRadius = mRadius;
}
}
|
/* Copyright 2019 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "extensions/stats/plugin.h"
// WASM_PROLOG
#ifndef NULL_PLUGIN
#include "api/wasm/cpp/proxy_wasm_intrinsics.h"
#else // NULL_PLUGIN
#include "extensions/common/wasm/null/null.h"
namespace Envoy {
namespace Extensions {
namespace Common {
namespace Wasm {
namespace Null {
namespace Plugin {
#endif // NULL_PLUGIN
// END WASM_PROLOG
namespace Stats {
void PluginRootContext::onConfigure(std::unique_ptr<WasmData> configuration) {
// Parse configuration JSON string.
JsonParseOptions json_options;
Status status =
JsonStringToMessage(configuration->toString(), &config_, json_options);
if (status != Status::OK) {
LOG_WARN(absl::StrCat("Cannot parse plugin configuration JSON string ",
configuration->toString()));
return;
}
status = ::Wasm::Common::extractLocalNodeMetadata(&local_node_info_);
if (status != Status::OK) {
LOG_WARN("cannot parse local node metadata ");
return;
}
PluginDirection direction;
auto dirn_result = getPluginDirection(&direction);
if (WasmResult::Ok == dirn_result) {
outbound_ = PluginDirection::Outbound == direction;
} else {
LOG_WARN(absl::StrCat("Unable to get plugin direction: ", dirn_result));
}
// Local data does not change, so populate it on config load.
istio_dimensions_.init(outbound_, local_node_info_);
if (outbound_) {
peer_metadata_id_key_ = ::Wasm::Common::kUpstreamMetadataIdKey;
peer_metadata_key_ = ::Wasm::Common::kUpstreamMetadataKey;
} else {
peer_metadata_id_key_ = ::Wasm::Common::kDownstreamMetadataIdKey;
peer_metadata_key_ = ::Wasm::Common::kDownstreamMetadataKey;
}
debug_ = config_.debug();
node_info_cache_.set_max_cache_size(config_.max_peer_cache_size());
auto field_separator = CONFIG_DEFAULT(field_separator);
auto value_separator = CONFIG_DEFAULT(value_separator);
auto stat_prefix = CONFIG_DEFAULT(stat_prefix);
// prepend "_" to opt out of automatic namespacing
// If "_" is not prepended, envoy_ is automatically added by prometheus
// scraper"
stat_prefix = absl::StrCat("_", stat_prefix, "_");
stats_ = std::vector<StatGen>{
StatGen(
absl::StrCat(stat_prefix, "requests_total"), MetricType::Counter,
[](const ::Wasm::Common::RequestInfo&) -> uint64_t { return 1; },
field_separator, value_separator),
StatGen(
absl::StrCat(stat_prefix, "request_duration_milliseconds"),
MetricType::Histogram,
[](const ::Wasm::Common::RequestInfo& request_info) -> uint64_t {
return (request_info.end_timestamp - request_info.start_timestamp) /
1000000;
},
field_separator, value_separator),
StatGen(
absl::StrCat(stat_prefix, "request_bytes"), MetricType::Histogram,
[](const ::Wasm::Common::RequestInfo& request_info) -> uint64_t {
return request_info.request_size;
},
field_separator, value_separator),
StatGen(
absl::StrCat(stat_prefix, "response_bytes"), MetricType::Histogram,
[](const ::Wasm::Common::RequestInfo& request_info) -> uint64_t {
return request_info.response_size;
},
field_separator, value_separator)};
}
void PluginRootContext::report(
const ::Wasm::Common::RequestInfo& request_info) {
const auto& peer_node =
node_info_cache_.getPeerById(peer_metadata_id_key_, peer_metadata_key_);
// map and overwrite previous mapping.
istio_dimensions_.map(peer_node, request_info);
auto stats_it = metrics_.find(istio_dimensions_);
if (stats_it != metrics_.end()) {
for (auto& stat : stats_it->second) {
stat.record(request_info);
LOG_DEBUG(absl::StrCat(
"metricKey cache hit ", istio_dimensions_.debug_key(),
", stat=", stat.metric_id_, stats_it->first.to_string()));
}
cache_hits_accumulator_++;
if (cache_hits_accumulator_ == 100) {
incrementMetric(cache_hits_, cache_hits_accumulator_);
cache_hits_accumulator_ = 0;
}
return;
}
// fetch dimensions in the required form for resolve.
auto values = istio_dimensions_.values();
std::vector<SimpleStat> stats;
for (auto& statgen : stats_) {
auto stat = statgen.resolve(values);
LOG_DEBUG(absl::StrCat("metricKey cache miss ", statgen.name(), " ",
istio_dimensions_.debug_key(),
", stat=", stat.metric_id_));
stat.record(request_info);
stats.push_back(stat);
}
incrementMetric(cache_misses_, 1);
metrics_.try_emplace(istio_dimensions_, stats);
}
const wasm::common::NodeInfo& NodeInfoCache::getPeerById(
StringView peer_metadata_id_key, StringView peer_metadata_key) {
std::string peer_id;
if (getMetadataStringValue(MetadataType::Request, peer_metadata_id_key,
&peer_id) != Common::Wasm::WasmResult::Ok) {
LOG_DEBUG(absl::StrCat("cannot get metadata for: ", peer_metadata_id_key));
return cache_[""];
}
auto nodeinfo_it = cache_.find(peer_id);
if (nodeinfo_it != cache_.end()) {
return nodeinfo_it->second;
}
// Do not let the cache grow beyond max_cache_size_.
if (cache_.size() > max_cache_size_) {
auto it = cache_.begin();
cache_.erase(cache_.begin(), std::next(it, max_cache_size_ / 4));
LOG_INFO(absl::StrCat("cleaned cache, new cache_size:", cache_.size()));
}
google::protobuf::Struct metadata;
if (getMetadataStruct(MetadataType::Request, peer_metadata_key, &metadata) !=
Common::Wasm::WasmResult::Ok) {
LOG_DEBUG(absl::StrCat("cannot get metadata for: ", peer_metadata_key));
return cache_[""];
}
auto status =
::Wasm::Common::extractNodeMetadata(metadata, &(cache_[peer_id]));
if (status != Status::OK) {
LOG_DEBUG(absl::StrCat("cannot parse peer node metadata ",
metadata.DebugString(), ": ", status.ToString()));
return cache_[""];
}
return cache_[peer_id];
}
// Registration glue
NullPluginRootRegistry* context_registry_{};
class StatsFactory : public NullPluginFactory {
public:
const std::string name() const override { return "envoy.wasm.stats"; }
std::unique_ptr<NullVmPlugin> create() const override {
return std::make_unique<NullPlugin>(context_registry_);
}
};
static Registry::RegisterFactory<StatsFactory, NullPluginFactory> register_;
} // namespace Stats
// WASM_EPILOG
#ifdef NULL_PLUGIN
} // namespace Plugin
} // namespace Null
} // namespace Wasm
} // namespace Common
} // namespace Extensions
} // namespace Envoy
#endif
|
#include "App.h"
#include "Window.h"
#include "Input.h"
#include "Render.h"
#include "Textures.h"
#include "Audio.h"
#include "Scene.h"
#include "Physics.h"
#include "Player.h"
#include "UI.h"
#include "Defs.h"
#include "Log.h"
#include <iostream>
#include <sstream>
// Constructor
App::App(int argc, char* args[]) : argc(argc), args(args)
{
win = new Window();
input = new Input();
render = new Render();
tex = new Textures();
audio = new Audio();
physics = new Physics();
scene = new Scene();
player = new Player();
ui = new UI();
// Ordered for awake / Start / Update
// Reverse order of CleanUp
AddModule(win);
AddModule(input);
AddModule(tex);
AddModule(audio);
AddModule(scene);
AddModule(player);
AddModule(physics);
AddModule(ui);
// Render last to swap buffer
AddModule(render);
}
// Destructor
App::~App()
{
// Release modules
ListItem<Module*>* item = modules.end;
while(item != NULL)
{
RELEASE(item->data);
item = item->prev;
}
modules.Clear();
}
void App::AddModule(Module* module)
{
module->Init();
modules.Add(module);
}
// Called before render is available
bool App::Awake()
{
bool ret = LoadConfig();
if(ret == true)
{
title.Create(configApp.child("title").child_value());
win->SetTitle(title.GetString());
ListItem<Module*>* item;
item = modules.start;
while(item != NULL && ret == true)
{
ret = item->data->Awake(config.child(item->data->name.GetString()));
item = item->next;
}
}
return ret;
}
// Called before the first frame
bool App::Start()
{
bool ret = true;
ListItem<Module*>* item;
item = modules.start;
while(item != NULL && ret == true)
{
ret = item->data->Start();
item = item->next;
}
return ret;
}
// Called each loop iteration
bool App::Update()
{
bool ret = true;
PrepareUpdate();
if(input->GetWindowEvent(WE_QUIT) == true)
ret = false;
if(ret == true)
ret = PreUpdate();
if(ret == true)
ret = DoUpdate();
if(ret == true)
ret = PostUpdate();
FinishUpdate();
return ret;
}
// Load config from XML file
bool App::LoadConfig()
{
bool ret = true;
// TODO 3: Load config.xml file using load_file() method from the xml_document class
pugi::xml_parse_result result = configFile.load_file("config.xml");
// TODO 3: Check result for loading errors
if(result == NULL)
{
LOG("Could not load map xml file config.xml. pugi error: %s", result.description());
ret = false;
}
else
{
config = configFile.child("config");
configApp = config.child("app");
}
return ret;
}
// ---------------------------------------------
void App::PrepareUpdate()
{
frames++;
dt = timer.ReadSec();
timer.Start();
}
// ---------------------------------------------
void App::FinishUpdate()
{
if (lastFrameTimer.Read() > 1000)
{
lastFrameTimer.Start();
}
lastFrameMs = timer.Read();
if (frameDelay > lastFrameMs)
{
SDL_Delay(frameDelay - lastFrameMs); //fps = 60
frames = 60;
}
}
// Call modules before each loop iteration
bool App::PreUpdate()
{
bool ret = true;
ListItem<Module*>* item;
Module* pModule = NULL;
for(item = modules.start; item != NULL && ret == true; item = item->next)
{
pModule = item->data;
if(pModule->active == false) {
continue;
}
ret = item->data->PreUpdate();
}
return ret;
}
// Call modules on each loop iteration
bool App::DoUpdate()
{
bool ret = true;
ListItem<Module*>* item;
item = modules.start;
Module* pModule = NULL;
for(item = modules.start; item != NULL && ret == true; item = item->next)
{
pModule = item->data;
if(pModule->active == false) {
continue;
}
ret = item->data->Update(dt);
}
return ret;
}
// Call modules after each loop iteration
bool App::PostUpdate()
{
bool ret = true;
ListItem<Module*>* item;
Module* pModule = NULL;
for(item = modules.start; item != NULL && ret == true; item = item->next)
{
pModule = item->data;
if(pModule->active == false) {
continue;
}
ret = item->data->PostUpdate();
}
return ret;
}
// Called before quitting
bool App::CleanUp()
{
bool ret = true;
ListItem<Module*>* item;
item = modules.end;
while(item != NULL && ret == true)
{
ret = item->data->CleanUp();
item = item->prev;
}
return ret;
}
// ---------------------------------------
int App::GetArgc() const
{
return argc;
}
// ---------------------------------------
const char* App::GetArgv(int index) const
{
if(index < argc)
return args[index];
else
return NULL;
}
// ---------------------------------------
const char* App::GetTitle() const
{
return title.GetString();
}
// ---------------------------------------
const char* App::GetOrganization() const
{
return organization.GetString();
}
|
/*
* Copyright 2021 The CFU-Playground Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "software_cfu.h"
#include <stdint.h>
namespace {
uint32_t byte_sum(uint32_t rs1, uint32_t rs2) {
uint32_t retval = 0;
for (int i = 0; i < 4; i++) {
retval += (rs1 & 0xff) + (rs2 & 0xff);
rs1 >>= 8;
rs2 >>= 8;
}
return retval;
}
uint32_t byte_swap(uint32_t rs1) {
uint32_t retval = 0;
for (int i = 0; i < 32; i += 8) {
retval |= (((rs1 >> i) & 0xff) << (24 - i));
}
return retval;
}
uint32_t bit_reverse(uint32_t rs1) {
uint32_t retval = 0;
for (int i = 0; i < 32; ++i) {
retval |= (((rs1 >> i) & 0x1) << (31 - i));
}
return retval;
}
uint32_t fib(uint32_t rs1) {
if (rs1 > 46) {
return 0;
}
uint32_t s1 = 1, s2 = 1;
for (uint32_t count = rs1; count > 0; --count) {
uint32_t sum = s1 + s2;
s1 = s2;
s2 = sum;
}
return s1;
}
}; // anonymous namespace
// In this function, place C code to emulate your CFU. You can switch between
// hardware and emulated CFU by setting the CFU_SOFTWARE_DEFINED DEFINE in
// the Makefile.
uint32_t software_cfu(int funct3, int funct7, uint32_t rs1, uint32_t rs2) {
switch (funct3) {
case 0:
return byte_sum(rs1, rs2);
case 1:
return byte_swap(rs1);
case 2:
return bit_reverse(rs1);
case 3:
return fib(rs1);
default:
return 0;
}
}
|
/******************************************************************************
* Copyright (c) 2018(-2021) STMicroelectronics.
* All rights reserved.
*
* This file is part of the TouchGFX 4.17.0 distribution.
*
* This software is licensed under terms that can be found in the LICENSE file in
* the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
*******************************************************************************/
#include <touchgfx/hal/Types.hpp>
#include <touchgfx/Bitmap.hpp>
#include <touchgfx/canvas_widget_renderer/CanvasWidgetRenderer.hpp>
#include <touchgfx/canvas_widget_renderer/Rasterizer.hpp>
#include <touchgfx/hal/HAL.hpp>
#include <touchgfx/transforms/DisplayTransformation.hpp>
#include <touchgfx/widgets/canvas/CWRUtil.hpp>
#include <touchgfx/widgets/canvas/Canvas.hpp>
#include <touchgfx/widgets/canvas/CanvasWidget.hpp>
namespace touchgfx
{
Canvas::Canvas(const CanvasWidget* _widget, const Rect& invalidatedArea)
: widget(_widget),
invalidatedAreaX(0),
invalidatedAreaY(0),
invalidatedAreaWidth(0),
invalidatedAreaHeight(0),
rbuf(),
ras(),
offsetX(0),
offsetY(0),
enoughMemory(false),
penUp(true),
penHasBeenDown(false),
previousX(0),
previousY(0),
previousOutside(0),
penDownOutside(0),
initialX(0),
initialY(0)
{
assert(CanvasWidgetRenderer::hasBuffer() && "No buffer allocated for CanvasWidgetRenderer drawing");
assert(Rasterizer::POLY_BASE_SHIFT == 5 && "CanvasWidget assumes Q5 but Rasterizer uses a different setting");
// Area to redraw (relative coordinates)
Rect dirtyArea = Rect(0, 0, widget->getWidth(), widget->getHeight()) & invalidatedArea;
// Absolute position of the scalableImage.
Rect dirtyAreaAbsolute = dirtyArea;
widget->translateRectToAbsolute(dirtyAreaAbsolute);
// Transform rects to match framebuffer coordinates
// This is needed if the display is rotated compared to the framebuffer
DisplayTransformation::transformDisplayToFrameBuffer(dirtyArea, widget->getRect());
DisplayTransformation::transformDisplayToFrameBuffer(dirtyAreaAbsolute);
// Re-size buffers for optimum memory buffer layout.
enoughMemory = CanvasWidgetRenderer::setScanlineWidth(dirtyArea.width);
ras.reset();
offsetX = dirtyArea.x;
offsetY = dirtyArea.y;
invalidatedAreaX = CWRUtil::toQ5<int>(dirtyArea.x);
invalidatedAreaY = CWRUtil::toQ5<int>(dirtyArea.y);
invalidatedAreaWidth = CWRUtil::toQ5<int>(dirtyArea.width);
invalidatedAreaHeight = CWRUtil::toQ5<int>(dirtyArea.height);
// Create the rendering buffer
uint8_t* RESTRICT buf = reinterpret_cast<uint8_t*>(HAL::getInstance()->lockFrameBuffer());
int stride = HAL::lcd().framebufferStride();
uint8_t offset = 0;
switch (HAL::lcd().framebufferFormat())
{
case Bitmap::BW:
buf += (dirtyAreaAbsolute.x / 8) + dirtyAreaAbsolute.y * stride;
offset = dirtyAreaAbsolute.x % 8;
break;
case Bitmap::GRAY2:
buf += (dirtyAreaAbsolute.x / 4) + dirtyAreaAbsolute.y * stride;
offset = dirtyAreaAbsolute.x % 4;
break;
case Bitmap::GRAY4:
buf += (dirtyAreaAbsolute.x / 2) + dirtyAreaAbsolute.y * stride;
offset = dirtyAreaAbsolute.x % 2;
break;
case Bitmap::RGB565:
buf += dirtyAreaAbsolute.x * 2 + dirtyAreaAbsolute.y * stride;
break;
case Bitmap::RGB888:
buf += dirtyAreaAbsolute.x * 3 + dirtyAreaAbsolute.y * stride;
break;
case Bitmap::RGBA2222:
case Bitmap::BGRA2222:
case Bitmap::ARGB2222:
case Bitmap::ABGR2222:
case Bitmap::L8:
buf += dirtyAreaAbsolute.x + dirtyAreaAbsolute.y * stride;
break;
case Bitmap::ARGB8888:
buf += dirtyAreaAbsolute.x * 4 + dirtyAreaAbsolute.y * stride;
break;
case Bitmap::BW_RLE:
case Bitmap::A4:
case Bitmap::CUSTOM:
assert(0 && "Unsupported bit depth");
break;
}
ras.setMaxRenderY(dirtyAreaAbsolute.height);
rbuf.attach(buf, offset, dirtyAreaAbsolute.width, dirtyAreaAbsolute.height, stride);
}
Canvas::~Canvas()
{
HAL::getInstance()->unlockFrameBuffer();
}
void Canvas::moveTo(CWRUtil::Q5 x, CWRUtil::Q5 y)
{
if (!enoughMemory)
{
return;
}
if (!penUp)
{
close();
}
transformFrameBufferToDisplay(x, y);
x = x - invalidatedAreaX;
y = y - invalidatedAreaY;
uint8_t outside = isOutside(x, y, invalidatedAreaWidth, invalidatedAreaHeight);
if (outside)
{
penUp = true;
}
else
{
penDownOutside = outside;
ras.moveTo(x, y);
penUp = false;
penHasBeenDown = true;
}
initialX = x;
initialY = y;
previousX = x;
previousY = y;
previousOutside = outside;
}
void Canvas::lineTo(CWRUtil::Q5 x, CWRUtil::Q5 y)
{
if (!enoughMemory)
{
return;
}
transformFrameBufferToDisplay(x, y);
x = x - invalidatedAreaX;
y = y - invalidatedAreaY;
uint8_t outside = isOutside(x, y, invalidatedAreaWidth, invalidatedAreaHeight);
if (!previousOutside)
{
ras.lineTo(x, y);
}
else
{
if (!outside || !(previousOutside & outside))
{
// x,y is inside, or on another side compared to previous
if (penUp)
{
penDownOutside = previousOutside;
ras.moveTo(previousX, previousY);
penUp = false;
penHasBeenDown = true;
}
else
{
ras.lineTo(previousX, previousY);
}
ras.lineTo(x, y);
}
else
{
// Restrict "outside" to the same side as previous point.
outside &= previousOutside;
}
}
previousX = x;
previousY = y;
previousOutside = outside;
}
bool Canvas::render(uint8_t customAlpha)
{
// If the invalidated rect is too wide compared to the allocated buffer for CWR,
// redrawing will not help. The CanvasWidget needs to know about this situation
// and maybe try to divide the area vertically instead, but this has not been
// implemented. And probably should not.
if (!enoughMemory)
{
return true; // Redrawing a rect with fewer scanlines will not help, fake "ok" to move on
}
if (ras.wasOutlineTooComplex())
{
return false; // Try again with fewer scanlines
}
if (!penHasBeenDown)
{
return true; // Nothing drawn. Done
}
const uint8_t alpha = LCD::div255(widget->getAlpha() * customAlpha);
if (alpha == 0)
{
return true; // Invisible. Done
}
close();
widget->getPainter().setOffset(offsetX /*+widget->getX()*/, offsetY /*+widget->getY()*/);
widget->getPainter().setWidgetAlpha(alpha);
Renderer renderer(rbuf, widget->getPainter());
return ras.render(renderer);
}
uint8_t Canvas::isOutside(const CWRUtil::Q5& x, const CWRUtil::Q5& y, const CWRUtil::Q5& width, const CWRUtil::Q5& height) const
{
uint8_t outside = 0;
// Find out if (x,y) is above/below of current area
if (y < 0)
{
outside = POINT_IS_ABOVE;
}
else if (y >= height)
{
outside = POINT_IS_BELOW;
}
// Find out if (x,y) is left/right of current area
if (x < 0)
{
outside |= POINT_IS_LEFT;
}
else if (x >= width)
{
outside |= POINT_IS_RIGHT;
}
return outside;
}
void Canvas::transformFrameBufferToDisplay(CWRUtil::Q5& x, CWRUtil::Q5& y) const
{
switch (HAL::DISPLAY_ROTATION)
{
case rotate0:
break;
case rotate90:
CWRUtil::Q5 tmpY = y;
y = CWRUtil::toQ5<int>(widget->getWidth()) - x;
x = tmpY;
break;
}
}
void Canvas::close()
{
if (!penUp)
{
if (previousOutside & penDownOutside)
{
// We are outside on the same side as we started. No need
// to close the path, CWR will do this for us.
//lineTo(penDownX, penDownY);
}
else
{
if (previousOutside)
{
ras.lineTo(previousX, previousY);
}
ras.lineTo(initialX, initialY);
}
}
penUp = false;
}
} // namespace touchgfx
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "main_functions.h"
#include "audio_provider.h"
#include "command_responder.h"
#include "feature_provider.h"
#include "micro_features/micro_model_settings.h"
#include "micro_speech_model_data.h"
#include "recognize_commands.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/system_setup.h"
#include "tensorflow/lite/schema/schema_generated.h"
// Globals, used for compatibility with Arduino-style sketches.
namespace {
tflite::ErrorReporter* error_reporter = nullptr;
const tflite::Model* model = nullptr;
tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* model_input = nullptr;
FeatureProvider* feature_provider = nullptr;
RecognizeCommands* recognizer = nullptr;
int32_t previous_time = 0;
// Create an area of memory to use for input, output, and intermediate arrays.
// The size of this will depend on the model you're using, and may need to be
// determined by experimentation.
constexpr int kTensorArenaSize = 10 * 1024;
uint8_t tensor_arena[kTensorArenaSize];
int8_t feature_buffer[kFeatureElementCount];
int8_t* model_input_buffer = nullptr;
} // namespace
// The name of this function is important for Arduino compatibility.
void setup() {
tflite::InitializeTarget();
// Set up logging. Google style is to avoid globals or statics because of
// lifetime uncertainty, but since this has a trivial destructor it's okay.
// NOLINTNEXTLINE(runtime-global-variables)
static tflite::MicroErrorReporter micro_error_reporter;
error_reporter = µ_error_reporter;
// Map the model into a usable data structure. This doesn't involve any
// copying or parsing, it's a very lightweight operation.
model = tflite::GetModel(g_micro_speech_model_data);
if (model->version() != TFLITE_SCHEMA_VERSION) {
TF_LITE_REPORT_ERROR(error_reporter,
"Model provided is schema version %d not equal "
"to supported version %d.",
model->version(), TFLITE_SCHEMA_VERSION);
return;
}
// Pull in only the operation implementations we need.
// This relies on a complete list of all the ops needed by this graph.
// An easier approach is to just use the AllOpsResolver, but this will
// incur some penalty in code space for op implementations that are not
// needed by this graph.
//
// tflite::AllOpsResolver resolver;
// NOLINTNEXTLINE(runtime-global-variables)
static tflite::MicroMutableOpResolver<4> micro_op_resolver(error_reporter);
if (micro_op_resolver.AddDepthwiseConv2D() != kTfLiteOk) {
return;
}
if (micro_op_resolver.AddFullyConnected() != kTfLiteOk) {
return;
}
if (micro_op_resolver.AddSoftmax() != kTfLiteOk) {
return;
}
if (micro_op_resolver.AddReshape() != kTfLiteOk) {
return;
}
// Build an interpreter to run the model with.
static tflite::MicroInterpreter static_interpreter(
model, micro_op_resolver, tensor_arena, kTensorArenaSize, error_reporter);
interpreter = &static_interpreter;
// Allocate memory from the tensor_arena for the model's tensors.
TfLiteStatus allocate_status = interpreter->AllocateTensors();
if (allocate_status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed");
return;
}
// Get information about the memory area to use for the model's input.
model_input = interpreter->input(0);
if ((model_input->dims->size != 2) || (model_input->dims->data[0] != 1) ||
(model_input->dims->data[1] !=
(kFeatureSliceCount * kFeatureSliceSize)) ||
(model_input->type != kTfLiteInt8)) {
TF_LITE_REPORT_ERROR(error_reporter,
"Bad input tensor parameters in model");
return;
}
model_input_buffer = model_input->data.int8;
// Prepare to access the audio spectrograms from a microphone or other source
// that will provide the inputs to the neural network.
// NOLINTNEXTLINE(runtime-global-variables)
static FeatureProvider static_feature_provider(kFeatureElementCount,
feature_buffer);
feature_provider = &static_feature_provider;
static RecognizeCommands static_recognizer(error_reporter);
recognizer = &static_recognizer;
previous_time = 0;
}
// The name of this function is important for Arduino compatibility.
void loop() {
// Fetch the spectrogram for the current time.
const int32_t current_time = LatestAudioTimestamp();
int how_many_new_slices = 0;
TfLiteStatus feature_status = feature_provider->PopulateFeatureData(
error_reporter, previous_time, current_time, &how_many_new_slices);
if (feature_status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(error_reporter, "Feature generation failed");
return;
}
previous_time = current_time;
// If no new audio samples have been received since last time, don't bother
// running the network model.
if (how_many_new_slices == 0) {
return;
}
// Copy feature buffer to input tensor
for (int i = 0; i < kFeatureElementCount; i++) {
model_input_buffer[i] = feature_buffer[i];
}
// Run the model on the spectrogram input and make sure it succeeds.
TfLiteStatus invoke_status = interpreter->Invoke();
if (invoke_status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed");
return;
}
// Obtain a pointer to the output tensor
TfLiteTensor* output = interpreter->output(0);
// Determine whether a command was recognized based on the output of inference
const char* found_command = nullptr;
uint8_t score = 0;
bool is_new_command = false;
TfLiteStatus process_status = recognizer->ProcessLatestResults(
output, current_time, &found_command, &score, &is_new_command);
if (process_status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(error_reporter,
"RecognizeCommands::ProcessLatestResults() failed");
return;
}
// Do something based on the recognized command. The default implementation
// just prints to the error console, but you should replace this with your
// own function for a real application.
RespondToCommand(error_reporter, current_time, found_command, score,
is_new_command);
}
|
/*
* @brief 数学/写像12相/分割数 $n = m$ 版
*/
#define PROBLEM "https://judge.yosupo.jp/problem/partition_function"
#include <iostream>
#include <vector>
#include "../../../math/modint.hpp"
#include "../../../math/convolution/number_theoretic_transform.hpp"
#include "../../../math/formal_power_series/formal_power_series.hpp"
#include "../../../math/twelvefold_way/partition_function_by_fps.hpp"
int main() {
using ModInt = MInt<0>;
ModInt::set_mod(998244353);
FormalPowerSeries<ModInt>::set_mul(
[](const std::vector<ModInt>& a, const std::vector<ModInt>& b) -> std::vector<ModInt> {
static NumberTheoreticTransform<0> ntt;
return ntt.convolution(a, b);
});
int n;
std::cin >> n;
const std::vector<ModInt> p = partition_function_by_fps<ModInt>(n);
for (int i = 0; i <= n; ++i) {
std::cout << p[i] << " \n"[i == n];
}
return 0;
}
|
#include "StdAfx.h"
#include "CustomRoboCompress.h"
CCustomRoboCompress::CCustomRoboCompress(void)
{
}
CCustomRoboCompress::~CCustomRoboCompress(void)
{
}
/*standard 32bit byteswapcustomroboping*/
unsigned long byteswapcustomrobo(unsigned long w)
{return (w >> 24) | ((w >> 8) & 0x0000ff00) | ((w << 8) & 0x00ff0000) | (w << 24);
}
/****************************************/
/*get the size of a file
it happens often enough it might as well be a function
plus, it won't mess with CUR_POS*/
/****************************************/
unsigned long filesizecustomrobo(FILE *in)
{unsigned long cur,end;
cur=ftell(in);
fseek(in,0,SEEK_END);
end=ftell(in);
fseek(in,cur,SEEK_SET);
return end;}
/*****************************************
weird string check function
entirely because nothing else was working
*****************************************/
unsigned long chewy(unsigned char *search,unsigned long searchx,unsigned char *table,unsigned long tablex)
{unsigned long x,locate;
unsigned char compare[18];
for(locate=0;locate<tablex;locate++)
{for(x=0;x<searchx;x++) compare[x]=table[x+locate];
for(x=0;x<searchx;x++)
{
if(search[x]!=compare[x]) break;
}
if(x==searchx) return locate;
}
return 0x8000;}
/*************************************
basic idea behind the compression scheme
(note: this is slow and crappy)
There are three buffers:
search string, null terminated
alias buffer -which is really just a subset of the output-
allocated and null terminated
packet of data to be output in file, containing:
bitflag byte stating which are alias bytes
the bytes themselves, either 1-byte literals or 2-byte aliases (8-16 total)
strstr() is used to search the alias buffer for the search string.
the search string is initially 18 bytes long (3bytes + 15 max),
and the alias buffer also contains the string-1 char in the case of "replication".
If a hit is not found, both buffers are shortened with NULLs and retested.
If it is not found with a 3-byte search string,
the single byte is stored and the corresponding bitflag toggled
format in output will look like: aa #A, where Aaa is an address, #+3=bytes
so, let that intel processor byteswapcustomrobo for you by using an int!
In the case of a hit, first the series is retested ot get the last possible hit.
This provides compression 100% equivalent to the original source.
The position to the hit is determined and
added to the alias file offset to determine it's file location.
That value is masked to produce a three-nibble offset.
The bytes are swapped, then the length of the search string -3
is stored in the last nibble.
As you can tell, the more redundancy within the file, the faster it compresses.
Pretty much any halfwit can come up with a better scheme & implementation.
I'm a hacker, not a coder...
oh yeah...
returns 1 if an error, or 0 if all is well.
*source is your input file (tempy, already extended by 0xFEE)
*out is your outut
source_init is original position in source
out_init is original position in out
index is the current position-0x1000
current is the byte sequence you are testing (in CR starts at 0xFEE)
size is the size of the block during allocation
*alias points to the allocated block of test values
search is your search string, up to 18 char long + NULL
bitflag stores your nifty bitflag data
bitflag is 0 if a couplet, 1 if a normal byte
shift left after each iteration (lead = lead << 1;)
*hit and *nexthit point to the results of strstr
values[] stores the eight values
*************************************/
unsigned long CRpress(FILE *source, FILE *out, unsigned long current,unsigned long source_size)
{unsigned long searchx,size,hit,y;
unsigned char *alias, search[18], bitflag,value[16];
unsigned short x,valuex;
if(!(alias = (unsigned char *) malloc(0x1012)))
{fprintf(stderr,"\nhorrible memory allocation problem\naborting....");
system("PAUSE");
exit(1);
}
/*lupus*/
while(current<filesizecustomrobo(source))
{
valuex=0;
bitflag=0; /*reset flag. add 1 if set, then advance with leftshift*/
for(x=0;x<8;x++) /*do this 8 times - one for each value*/
{bitflag = bitflag >> 1; /*advance to next flag*/
/*grab search string.
it should return # actually read, so use that to determine allocation size*/
fseek(source,current,SEEK_SET);
if((searchx=fread(search,1,18,source))>0)/*if done reading, loop until finished*/
{
/*set size for allocated block 0xFFF + #read. if current<0x1000, use current.
realloc with a NULL pointer should act like malloc*/
if(current<0x1000) size=current;
else size=0xFFF;
fseek(source,current-size,SEEK_SET);
if(!((unsigned char *) realloc(alias,size+searchx-1)))
{fprintf(stderr,"\nhorrible memory allocation problem\naborting....");
system("PAUSE");
exit(1);
}
/*copy data into block*/
fread(alias,1,size+searchx-1,source);
/*actual search: repeat until a hit found or string is 2char*/
while(searchx>2)
{if((hit=chewy(search,searchx,alias,size))<0x8000) break;
/*otherwise, try a smaller string*/
searchx--;
}
/*new search method, should be less stupid*/
if(searchx>2) /*if string found though, get latest possible string*/
{/*while (strstr(hit,search)!=NULL) hit=strstr(hit,search);*/
/*don't need *size* anymore this run - set as file offset*/
size=current-size+hit;
value[valuex]= (size & 0xFF);
size=size >> 4;
value[valuex+1]= (char)((size & 0xF0) + (searchx-3));
current+=searchx;
valuex+=2;
}
else {bitflag+= 0x80; /*if hit NULL (never found)*/
fseek(source,current,SEEK_SET);
value[valuex]=fgetc(source);
current++;
valuex++;
}
} /*end of values left>0 check*/
}/*end for(valuex=0;valuex<8;valuex++)*/
/*now that the whole value is assembled, write to out*/
fputc(bitflag,out);
for(x=0;x<valuex;x++) fputc(value[x],out);
} /*lupus*/
/*Roswell that ends well*/
free(alias);
return current;}
/**pulls couplets and handles aliasing**/
int Suck(FILE * olde, FILE* newe, FILE* swap){
unsigned int addy,y;
unsigned long range;
unsigned char buffer;
/*character aliasing*/
/*
Memory is aliased in Ya-0 derivative compressions
When the lead bit = 0, it reads in two characters which determine the address and # characters copied
The alias follows the format aa #A, where Aaa is the address offset and #+3 characters read
These are copied one byte at a time, so replicating the last written character is possible
The address is also incremented in 0x1000's using the current file position
If the combined address value is larger than the current filesizecustomrobo, though, it will subtract the value instead
In this implementation, the file is decompressed into a buffer, so the actual file starts at 0xFEE
*/
addy=fgetc(olde);
range=fgetc(olde);
addy=addy+((range/0x10)*0x100);
range&=0xF;
range+=3;
addy+=(ftell(swap)&0xFFFFF000);
if(addy>ftell(swap)) addy-=0x1000;
/*read in one at a time (supports duplication this way)*/
for(y=0;y<range;y++)
{fseek(swap,addy+y,SEEK_SET);
buffer = fgetc(swap);
fseek(swap,0,SEEK_END);
fputc(buffer,swap);
}
return 0;}
/**basic ripping**/
int Rend(int offset, FILE * olde, FILE* newe, FILE* swap){
unsigned long x;
unsigned long addies[3];
unsigned char lead, trick;
/*add 0xFEE bytes to -swap-*/
for(x=0;x<0xFEE;x++) fputc(0,swap);
fread(&addies[0],4,1,olde);
fread(&addies[1],4,1,olde);
fread(&addies[2],4,1,olde);
for(x=0;x<3;x++) addies[x]=byteswapcustomrobo(addies[x]);
while(ftell(olde)<(offset + addies[1]+0x8))
{
lead=fgetc(olde);
for(x=0;x<8;x++)
{if(lead & 1)
{trick = fgetc(olde);
fputc(trick,swap);}
else Suck(olde, newe, swap);
lead = lead >> 1;
}
}
/*copy and truncate file from -swap- to -newe-*/
fseek(swap,0xFEE,SEEK_SET);
for(x=0;x<addies[2];x++) fputc(fgetc(swap),newe);
return addies[0];
}
int CCustomRoboCompress::decode(FILE * olde, int offset, CString filename, int& fileSizeCompressed)
{
FILE* swap= fopen(filename + "tempASDASDDdddd.bin", "wb+");
FILE* newe = fopen(filename, "wb+");
fileSizeCompressed = Rend(offset, olde, newe, swap);
fseek(newe, 0, SEEK_END);
int decompressedSize = ftell(newe);
fclose(newe);
fclose(swap);
::DeleteFile(filename + "tempASDASDDdddd.bin");
return decompressedSize;
}
bool CCustomRoboCompress::encode(CString inFileName, CString outFileName)
{
char y;
FILE *in, *out, *tempy;
unsigned long x;
in = fopen(inFileName, "rb");
if (in == NULL)
return false;
/*well, had to add 0xFEE 00's anyway
make a temp file, and copy the original to it
this will be the main sample to work with*/
tempy=fopen("asdasrtrtmpe.bin", "wb+");
if (tempy == NULL)
{
fclose(in);
return false;
}
/*in theory, filesizecustomrobo() doesn't tamper with file position*/
for(x=0;x<0xFEE;x++) fputc(0,tempy);
for(x=0;x<filesizecustomrobo(in);x++) fputc(fgetc(in),tempy);
fclose(in);
out = fopen(outFileName, "wb+");
if (out == NULL)
{
fclose(tempy);
return false;
}
/*the first two pointers get overwritten later, so just send something that size*/
x=byteswapcustomrobo(x);
fwrite(&x,4,1,out);
fwrite(&x,4,1,out);
fwrite(&x,4,1,out); /*out @ 0xC*/
printf("\nCompressing.\nThis will take a while due to some crappy code...\n");
/*now to actually do some compression*/
//printf("\n%X of %X bytes compressed",CRpress(tempy,out,0xfee,x)-0xfee,filesizecustomrobo(tempy)-0xFEE);
CRpress(tempy,out,0xfee,x);
/*mop up
here the offsets are added to the output file
at +4, set the size of data, which is the filesizecustomrobo -0xC (data length)
then, extend to word and set the total file size to 0x0
this is included here as the compression is also used with different formats*/
x=byteswapcustomrobo(filesizecustomrobo(out)-0x8);
fseek(out,4,SEEK_SET);
fwrite(&x,4,1,out);
/*word extend*/
fseek(out,-1,SEEK_END);
y=fgetc(out);
fseek(out,0,SEEK_END);
while(filesizecustomrobo(out)%4) fputc(y,out);
x=byteswapcustomrobo(filesizecustomrobo(out));
rewind(out);
fwrite(&x,4,1,out);
fclose(out);
fclose(tempy);
return true;
}
|
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
vector<string> split(string const& s, char delim=' ')
{
vector<string> elems;
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
//Here's another solution. It's compact and reasonably efficient :
std::vector<std::string> split2(const std::string &text, char sep) {
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
tokens.push_back(text.substr(start, end - start));
start = end + 1;
}
tokens.push_back(text.substr(start));
return tokens;
}
//It can easily be templatised to handle string separators, wide strings, etc.
//
//Note that splitting "" results in a single empty string and splitting "," (ie.sep) results in two empty strings.
//
//It can also be easily expanded to skip empty tokens :
std::vector<std::string> split3(const std::string &text, char sep) {
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
if (end != start) {
tokens.push_back(text.substr(start, end - start));
}
start = end + 1;
}
if (end != start) {
tokens.push_back(text.substr(start));
}
return tokens;
}
//If splitting a string at multiple delimiters while skipping empty tokens is desired, this version may be used :
std::vector<std::string> split4(const std::string& text, const std::string& delims)
{
std::vector<std::string> tokens;
std::size_t start = text.find_first_not_of(delims), end = 0;
while ((end = text.find_first_of(delims, start)) != std::string::npos)
{
tokens.push_back(text.substr(start, end - start));
start = text.find_first_not_of(delims, end);
}
if (start != std::string::npos)
tokens.push_back(text.substr(start));
return tokens;
}
int main()
{
string s = "It's a test, \nhow are\t you--I'm fine.";
for (auto ele : split4(s," \t\n-,"))cout << ele << endl;
}
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <proxygen/lib/http/codec/compress/StaticHeaderTable.h>
#include <folly/Indestructible.h>
#include <glog/logging.h>
#include <list>
using std::list;
using std::string;
using std::vector;
namespace {
// Array of static header table entires pair
// Note: if updating this table (should never have to but whatever), update
// isHeaderNameInTableWithNonEmptyValue as well
const char* s_tableEntries[][2] = {
{":authority", ""},
{":method", "GET"},
{":method", "POST"},
{":path", "/"},
{":path", "/index.html"},
{":scheme", "http"},
{":scheme", "https"},
{":status", "200"},
{":status", "204"},
{":status", "206"},
{":status", "304"},
{":status", "400"},
{":status", "404"},
{":status", "500"},
{"accept-charset", ""},
{"accept-encoding", "gzip, deflate"},
{"accept-language", ""},
{"accept-ranges", ""},
{"accept", ""},
{"access-control-allow-origin", ""},
{"age", ""},
{"allow", ""},
{"authorization", ""},
{"cache-control", ""},
{"content-disposition", ""},
{"content-encoding", ""},
{"content-language", ""},
{"content-length", ""},
{"content-location", ""},
{"content-range", ""},
{"content-type", ""},
{"cookie", ""},
{"date", ""},
{"etag", ""},
{"expect", ""},
{"expires", ""},
{"from", ""},
{"host", ""},
{"if-match", ""},
{"if-modified-since", ""},
{"if-none-match", ""},
{"if-range", ""},
{"if-unmodified-since", ""},
{"last-modified", ""},
{"link", ""},
{"location", ""},
{"max-forwards", ""},
{"proxy-authenticate", ""},
{"proxy-authorization", ""},
{"range", ""},
{"referer", ""},
{"refresh", ""},
{"retry-after", ""},
{"server", ""},
{"set-cookie", ""},
{"strict-transport-security", ""},
{"transfer-encoding", ""},
{"user-agent", ""},
{"vary", ""},
{"via", ""},
{"www-authenticate", ""}
};
const int kEntriesSize = sizeof(s_tableEntries) / (2 * sizeof(const char*));
}
namespace proxygen {
bool StaticHeaderTable::isHeaderCodeInTableWithNonEmptyValue(
HTTPHeaderCode headerCode) {
switch(headerCode) {
case HTTP_HEADER_COLON_METHOD:
case HTTP_HEADER_COLON_PATH:
case HTTP_HEADER_COLON_SCHEME:
case HTTP_HEADER_COLON_STATUS:
case HTTP_HEADER_ACCEPT_ENCODING:
return true;
default:
return false;
}
}
StaticHeaderTable::StaticHeaderTable(
const char* entries[][2],
int size)
: HeaderTable(0) {
// calculate the size
list<HPACKHeader> hlist;
uint32_t byteCount = 0;
for (int i = 0; i < size; ++i) {
hlist.push_back(HPACKHeader(entries[i][0], entries[i][1]));
byteCount += hlist.back().bytes();
}
// initialize with a capacity that will exactly fit the static headers
init(byteCount);
hlist.reverse();
for (auto& header : hlist) {
add(std::move(header));
}
}
const StaticHeaderTable& StaticHeaderTable::get() {
static const folly::Indestructible<StaticHeaderTable> table(
s_tableEntries, kEntriesSize);
return *table;
}
}
|
// Copyright (c) 2011-2016 The Alphapay Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "key.h"
#include "keystore.h"
#include "policy/policy.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/interpreter.h"
#include "script/sign.h"
#include "script/ismine.h"
#include "uint256.h"
#include "test/test_bitcoin.h"
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
typedef std::vector<unsigned char> valtype;
BOOST_FIXTURE_TEST_SUITE(multisig_tests, BasicTestingSetup)
CScript
sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction, int whichIn)
{
uint256 hash = SignatureHash(scriptPubKey, transaction, whichIn, SIGHASH_ALL, 0, SIGVERSION_BASE);
CScript result;
result << OP_0; // CHECKMULTISIG bug workaround
BOOST_FOREACH(const CKey &key, keys)
{
std::vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
}
return result;
}
BOOST_AUTO_TEST_CASE(multisig_verify)
{
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
ScriptError err;
CKey key[4];
CAmount amount = 0;
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
CMutableTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CMutableTransaction txTo[3]; // Spending transaction
for (int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
std::vector<CKey> keys;
CScript s;
// Test a AND b:
keys.assign(1,key[0]);
keys.push_back(key[1]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK(VerifyScript(s, a_and_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
for (int i = 0; i < 4; i++)
{
keys.assign(1,key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 1: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
keys.assign(1,key[1]);
keys.push_back(key[i]);
s = sign_multisig(a_and_b, keys, txTo[0], 0);
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_and_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[0], 0, amount), &err), strprintf("a&b 2: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
// Test a OR b:
for (int i = 0; i < 4; i++)
{
keys.assign(1,key[i]);
s = sign_multisig(a_or_b, keys, txTo[1], 0);
if (i == 0 || i == 1)
{
BOOST_CHECK_MESSAGE(VerifyScript(s, a_or_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
else
{
BOOST_CHECK_MESSAGE(!VerifyScript(s, a_or_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err), strprintf("a|b: %d", i));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
}
s.clear();
s << OP_0 << OP_1;
BOOST_CHECK(!VerifyScript(s, a_or_b, NULL, flags, MutableTransactionSignatureChecker(&txTo[1], 0, amount), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err));
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
keys.assign(1,key[i]);
keys.push_back(key[j]);
s = sign_multisig(escrow, keys, txTo[2], 0);
if (i < j && i < 3 && j < 3)
{
BOOST_CHECK_MESSAGE(VerifyScript(s, escrow, NULL, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 1: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
else
{
BOOST_CHECK_MESSAGE(!VerifyScript(s, escrow, NULL, flags, MutableTransactionSignatureChecker(&txTo[2], 0, amount), &err), strprintf("escrow 2: %d %d", i, j));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
}
}
BOOST_AUTO_TEST_CASE(multisig_IsStandard)
{
CKey key[4];
for (int i = 0; i < 4; i++)
key[i].MakeNewKey(true);
txnouttype whichType;
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_and_b, whichType));
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(a_or_b, whichType));
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(::IsStandard(escrow, whichType));
CScript one_of_four;
one_of_four << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << ToByteVector(key[3].GetPubKey()) << OP_4 << OP_CHECKMULTISIG;
BOOST_CHECK(!::IsStandard(one_of_four, whichType));
CScript malformed[6];
malformed[0] << OP_3 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
malformed[1] << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
malformed[2] << OP_0 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
malformed[3] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_0 << OP_CHECKMULTISIG;
malformed[4] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_CHECKMULTISIG;
malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey());
for (int i = 0; i < 6; i++)
BOOST_CHECK(!::IsStandard(malformed[i], whichType));
}
BOOST_AUTO_TEST_CASE(multisig_Solver1)
{
// Tests Solver() that returns lists of keys that are
// required to satisfy a ScriptPubKey
//
// Also tests IsMine() and ExtractDestination()
//
// Note: ExtractDestination for the multisignature transactions
// always returns false for this release, even if you have
// one key that would satisfy an (a|b) or 2-of-3 keys needed
// to spend an escrow transaction.
//
CBasicKeyStore keystore, emptykeystore, partialkeystore;
CKey key[3];
CTxDestination keyaddr[3];
for (int i = 0; i < 3; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
keyaddr[i] = key[i].GetPubKey().GetID();
}
partialkeystore.AddKey(key[0]);
{
std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 1);
CTxDestination addr;
BOOST_CHECK(ExtractDestination(s, addr));
BOOST_CHECK(addr == keyaddr[0]);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_DUP << OP_HASH160 << ToByteVector(key[0].GetPubKey().GetID()) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 1);
CTxDestination addr;
BOOST_CHECK(ExtractDestination(s, addr));
BOOST_CHECK(addr == keyaddr[0]);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
}
{
std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK_EQUAL(solutions.size(), 4U);
CTxDestination addr;
BOOST_CHECK(!ExtractDestination(s, addr));
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK_EQUAL(solutions.size(), 4U);
std::vector<CTxDestination> addrs;
int nRequired;
BOOST_CHECK(ExtractDestinations(s, whichType, addrs, nRequired));
BOOST_CHECK(addrs[0] == keyaddr[0]);
BOOST_CHECK(addrs[1] == keyaddr[1]);
BOOST_CHECK(nRequired == 1);
BOOST_CHECK(IsMine(keystore, s));
BOOST_CHECK(!IsMine(emptykeystore, s));
BOOST_CHECK(!IsMine(partialkeystore, s));
}
{
std::vector<valtype> solutions;
txnouttype whichType;
CScript s;
s << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
BOOST_CHECK(Solver(s, whichType, solutions));
BOOST_CHECK(solutions.size() == 5);
}
}
BOOST_AUTO_TEST_CASE(multisig_Sign)
{
// Test SignSignature() (and therefore the version of Solver() that signs transactions)
CBasicKeyStore keystore;
CKey key[4];
for (int i = 0; i < 4; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
}
CScript a_and_b;
a_and_b << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript a_or_b;
a_or_b << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CScript escrow;
escrow << OP_2 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
CMutableTransaction txFrom; // Funding transaction
txFrom.vout.resize(3);
txFrom.vout[0].scriptPubKey = a_and_b;
txFrom.vout[1].scriptPubKey = a_or_b;
txFrom.vout[2].scriptPubKey = escrow;
CMutableTransaction txTo[3]; // Spending transaction
for (int i = 0; i < 3; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
}
for (int i = 0; i < 3; i++)
{
BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0, SIGHASH_ALL), strprintf("SignSignature %d", i));
}
}
BOOST_AUTO_TEST_SUITE_END()
|
#include<iostream>
#include<thread>
#include<chrono>
#include<mutex>
using namespace std;
mutex m;
int* generateArray(int N) {
int* values = new int[N];
for (int i = 0; i < N; i++) {
values[i] = i % 100;
}
return values;
}
int getMinim(int* values, int iStart, int iFinal) {
int minim = values[iStart];
for (int i = iStart; i < iFinal; i++) {
if (minim > values[i]) {
minim = values[i];
}
}
return minim;
}
double getAverage(int* values, int iStart, int iFinal) {
double average = 0;
for (int i = iStart; i < iFinal; i++) {
average += values[i];
}
return average / (iFinal - iStart);
}
void getEvenCount(int* values, int iStart, int iFinal, int& count) {
for (int i = iStart; i < iFinal; i++) {
if (values[i] % 2 == 0) {
{
m.lock();
count += 1;
m.unlock();
}
}
}
}
//functie care poate fi executata pe un alt thread
void call_from_thread() {
std::cout << endl << "Hello World from another thread";
}
//functie cu parametri
void call_from_thread_2(int tid) {
std::cout << "\n Hello World from another thread" << tid;
}
int main() {
cout << endl << "Start main";
//definire thread
std::thread t1(call_from_thread);
//lansare thread
t1.join();
//definire grup de thread-uri
const int N_THREADS = 4;
thread* list = new thread[N_THREADS];
for (int i = 0; i < N_THREADS; i++) {
list[i] = thread(call_from_thread_2, i);
}
for (int i = 0; i < N_THREADS; i++) {
list[i].join();
}
cout << endl << "***************** TEST MIN, MEDIE SI NUMERE PARE SECVENTIAL **********************";
const int N = 300000000;
int* values = generateArray(N);
int nrNumerePare = 0;
std::chrono::system_clock::time_point tStart = std::chrono::system_clock::now();
int min = getMinim(values, 0, N);
double average = getAverage(values, 0, N);
getEvenCount(values, 0, N, nrNumerePare);
std::chrono::system_clock::time_point tFinal = std::chrono::system_clock::now();
cout << endl << "Min = " << min << " Average = " << average << " Even numbers = " << nrNumerePare << " Time = " << std::chrono::duration_cast<chrono::milliseconds>(tFinal - tStart).count();
/*
2 thread-uri pt min si average
*/
cout << endl << "***************** TEST MIN, MEDIE SI NUMERE PARE PARALEL **********************";
tStart = std::chrono::system_clock::now();
thread tMinim(getMinim, values, 0, N);
thread tAverage(getAverage, values, 0, N);
/*
2 thread-uri pt numar elemente pare
*/
nrNumerePare = 0;
unsigned int nrNumerePare1 = 0;
unsigned int nrNumerePare2 = 0;
thread tPare1(getEvenCount, values, 0, N / 2, ref(nrNumerePare1));
thread tPare2(getEvenCount, values, N / 2, N, ref(nrNumerePare2));
tPare1.join();
tPare2.join();
tMinim.join();
tAverage.join();
tFinal = std::chrono::system_clock::now();
cout << endl << "Nr elemente pare = " << nrNumerePare1 + nrNumerePare2;
cout << endl << "Parallel Time = " << std::chrono::duration_cast<chrono::milliseconds>(tFinal - tStart).count();
cout << endl << "End main";
}
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/math_ops.cc.
#include "tensorflow/core/kernels/segment_reduction_ops_impl.h"
namespace tensorflow {
namespace internal {
// Static routines not in the templated class to reduce code size
void SegmentReductionValidationHelper(OpKernelContext* context,
const Tensor& input,
const Tensor& segment_ids) {
OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(input.shape()),
errors::InvalidArgument("input must be at least rank 1"));
OP_REQUIRES(context, TensorShapeUtils::IsVector(segment_ids.shape()),
errors::InvalidArgument("segment_ids should be a vector."));
const int64 num_indices = segment_ids.NumElements();
OP_REQUIRES(context, num_indices == input.dim_size(0),
errors::InvalidArgument(
"segment_ids should be the same size as dimension 0 of"
" input."));
}
bool SegmentReductionDoValidation(OpKernelContext* c, const Tensor& input,
const Tensor& segment_ids) {
SegmentReductionValidationHelper(c, input, segment_ids);
return c->status().ok();
}
// check routines not in the templated class to reduce code size
void UnsortedSegmentReductionValidation(OpKernel* op_kernel,
OpKernelContext* context,
const Tensor& data,
const Tensor& segment_ids,
const Tensor& num_segments) {
OP_REQUIRES(
context, TensorShapeUtils::IsScalar(num_segments.shape()),
errors::InvalidArgument("num_segments should be a scalar, not shape ",
num_segments.shape().DebugString()));
OP_REQUIRES(
context, TensorShapeUtils::StartsWith(data.shape(), segment_ids.shape()),
errors::InvalidArgument("data.shape = ", data.shape().DebugString(),
" does not start with segment_ids.shape = ",
segment_ids.shape().DebugString()));
}
bool UnsortedSegmentReductionDoValidation(OpKernel* op_kernel,
OpKernelContext* context,
const Tensor& data,
const Tensor& segment_ids,
const Tensor& num_segments) {
UnsortedSegmentReductionValidation(op_kernel, context, data, segment_ids,
num_segments);
return context->status().ok();
}
} // namespace internal
#define REGISTER_CPU_KERNEL_SEGMENT(name, functor, type, index_type, \
default_value) \
REGISTER_KERNEL_BUILDER( \
Name(name) \
.Device(DEVICE_CPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<index_type>("Tindices"), \
SegmentReductionOp<CPUDevice, type, index_type, functor, default_value>)
#define REGISTER_REAL_CPU_KERNELS(type, index_type) \
REGISTER_CPU_KERNEL_SEGMENT("SegmentSum", Eigen::internal::SumReducer<type>, \
type, index_type, 0); \
REGISTER_CPU_KERNEL_SEGMENT( \
"SegmentMean", Eigen::internal::MeanReducer<type>, type, index_type, 0); \
REGISTER_CPU_KERNEL_SEGMENT( \
"SegmentProd", Eigen::internal::ProdReducer<type>, type, index_type, 1); \
REGISTER_CPU_KERNEL_SEGMENT("SegmentMin", Eigen::internal::MinReducer<type>, \
type, index_type, 0); \
REGISTER_CPU_KERNEL_SEGMENT("SegmentMax", Eigen::internal::MaxReducer<type>, \
type, index_type, 0)
#define REGISTER_COMPLEX_CPU_KERNELS(type, index_type) \
REGISTER_CPU_KERNEL_SEGMENT("SegmentSum", Eigen::internal::SumReducer<type>, \
type, index_type, 0); \
REGISTER_CPU_KERNEL_SEGMENT( \
"SegmentMean", Eigen::internal::MeanReducer<type>, type, index_type, 0); \
REGISTER_CPU_KERNEL_SEGMENT( \
"SegmentProd", Eigen::internal::ProdReducer<type>, type, index_type, 1);
#define REGISTER_REAL_CPU_KERNELS_ALL(type) \
REGISTER_REAL_CPU_KERNELS(type, int32)
#define REGISTER_COMPLEX_CPU_KERNELS_ALL(type) \
REGISTER_COMPLEX_CPU_KERNELS(type, int32)
TF_CALL_REAL_NUMBER_TYPES(REGISTER_REAL_CPU_KERNELS_ALL);
REGISTER_COMPLEX_CPU_KERNELS_ALL(complex64);
REGISTER_COMPLEX_CPU_KERNELS_ALL(complex128);
#undef REGISTER_CPU_KERNEL_SEGMENT
#undef REGISTER_REAL_CPU_KERNELS
#undef REGISTER_COMPLEX_CPU_KERNELS
#undef REGISTER_REAL_CPU_KERNELS_ALL
#undef REGISTER_COMPLEX_CPU_KERNELS_ALL
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER_GPU_SORTED_KERNELS(type, index_type) \
REGISTER_KERNEL_BUILDER(Name("SegmentSum") \
.Device(DEVICE_GPU) \
.TypeConstraint<type>("T") \
.TypeConstraint<index_type>("Tindices"), \
SegmentSumGPUOp<type, index_type>)
#define REGISTER_GPU_SORTED_KERNELS_ALL(type) \
REGISTER_GPU_SORTED_KERNELS(type, int32)
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_SORTED_KERNELS_ALL);
#undef REGISTER_GPU_SORTED_KERNELS
#undef REGISTER_GPU_SORTED_KERNELS_ALL
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
*****************************************************************************
*
* File: ExExeUtilCli.cpp
* Description:
*
*
* Language: C++
*
*
*
*
*****************************************************************************
*/
//#include "ComCextdecs.h"
#include "cli_stdh.h"
#include "ex_stdh.h"
#include "sql_id.h"
#include "ComSqlId.h"
#include "ExExeUtilCli.h"
OutputInfo::OutputInfo(Lng32 numEntries)
: numEntries_(numEntries)
{
for (Int32 i = 0; i < numEntries_; i++)
{
data_[i] = NULL;
len_[i] = 0;
}
}
void OutputInfo::insert(Lng32 index, char * data)
{
data_[index] = data;
}
void OutputInfo::insert(Lng32 index, char * data, Lng32 len)
{
data_[index] = data;
len_[index] = len;
}
char * OutputInfo::get(Lng32 index)
{
if (index < numEntries_)
return data_[index];
else
return NULL;
}
short OutputInfo::get(Lng32 index, char* &data, Lng32 &len)
{
if (index < numEntries_)
{
data = data_[index];
len = len_[index];
return 0;
}
return -1;
}
void OutputInfo::dealloc(CollHeap * heap)
{
for (Int32 i = 0; i < numEntries_; i++)
{
NADELETEBASIC(data_[i], heap);
}
}
/////////////////////////////////////////////////////////////////
// class ExeCliInterface
/////////////////////////////////////////////////////////////////
ExeCliInterface::ExeCliInterface(CollHeap * heap, Int32 isoMapping,
ContextCli * currContext,
const char *parentQid)
: heap_(heap),
module_(NULL),
stmt_(NULL),
sql_src_(NULL),
input_desc_(NULL),
output_desc_(NULL),
rs_input_maxsize_desc_(NULL),
outputBuf_(NULL),
inputBuf_(NULL),
currContext_(currContext),
moduleWithCK_(NULL),
stmtWithCK_(NULL),
sql_src_withCK_(NULL),
input_desc_withCK_(NULL),
output_desc_withCK_(NULL),
outputBuf_withCK_(NULL),
rsInputBuffer_(NULL),
isoMapping_((Int32)SQLCHARSETCODE_ISO88591), // ISO_MAPPING=ISO88591
parentQid_(parentQid),
inputAttrs_(NULL),
outputAttrs_(NULL),
explainData_(NULL),
explainDataLen_(0),
flags_(0)
{
if (parentQid_)
{
Int32 len = str_len(parentQid_);
ex_assert( len >= ComSqlId::MIN_QUERY_ID_LEN, "parentQid too short.");
ex_assert( len <= ComSqlId::MAX_QUERY_ID_LEN, "parentQid too long.");
ex_assert( !str_cmp(parentQid_, COM_SESSION_ID_PREFIX, 4),
"invalid parentQid.");
}
}
ExeCliInterface::~ExeCliInterface()
{
dealloc();
}
Lng32 ExeCliInterface::deallocStuff(SQLMODULE_ID * &module,
SQLSTMT_ID * &stmt,
SQLDESC_ID * &sql_src,
SQLDESC_ID * &input_desc,
SQLDESC_ID * &output_desc)
{
if (sql_src)
{
SQL_EXEC_DeallocDesc(sql_src);
NADELETEBASIC(sql_src, heap_);
sql_src = NULL;
}
if (stmt)
{
SQL_EXEC_DeallocStmt(stmt);
NADELETEBASIC(stmt, heap_);
stmt = NULL;
}
if (input_desc)
{
SQL_EXEC_DeallocDesc(input_desc);
NADELETEBASIC(input_desc, heap_);
input_desc = NULL;
}
if (output_desc)
{
SQL_EXEC_DeallocDesc(output_desc);
NADELETEBASIC(output_desc, heap_);
output_desc = NULL;
}
if (module)
{
NADELETEBASIC(module, heap_);
module = NULL;
}
if (rsInputBuffer_)
{
NADELETEBASIC(rsInputBuffer_, heap_);
rsInputBuffer_ = NULL;
}
if (outputAttrs_)
{
NADELETEBASIC(outputAttrs_, heap_);
outputAttrs_ = NULL;
}
if (outputBuf_)
{
NADELETEBASIC(outputBuf_, heap_);
outputBuf_ = NULL;
}
return 0;
}
Lng32 ExeCliInterface::dealloc()
{
return deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
}
void ExeCliInterface::clearGlobalDiags()
{
SQL_EXEC_ClearDiagnostics(NULL);
}
Lng32 ExeCliInterface::allocStuff(SQLMODULE_ID * &module,
SQLSTMT_ID * &stmt,
SQLDESC_ID * &sql_src,
SQLDESC_ID * &input_desc,
SQLDESC_ID * &output_desc,
const char * stmtName
)
{
Lng32 retcode = 0;
deallocStuff(module, stmt, sql_src, input_desc, output_desc);
clearGlobalDiags();
module = new(heap_) SQLMODULE_ID;
init_SQLMODULE_ID(module);
// Allocate a SQL statement
stmt = new(heap_) SQLSTMT_ID;
if (stmtName)
{
init_SQLSTMT_ID(stmt, SQLCLI_CURRENT_VERSION, stmt_name, module);
stmt->identifier =
new(heap_) char[strlen(stmtName) +1];
strcpy((char*)stmt->identifier, stmtName);
stmt->identifier_len = (Lng32)strlen(stmtName);
}
else
init_SQLSTMT_ID(stmt, SQLCLI_CURRENT_VERSION, stmt_handle, module);
retcode = SQL_EXEC_AllocStmt(stmt, 0);
if (retcode < 0)
return retcode;
// Allocate a descriptor which will hold the SQL statement source
sql_src = new(heap_) SQLSTMT_ID;
init_SQLDESC_ID(sql_src, SQLCLI_CURRENT_VERSION, desc_handle, module);
retcode = SQL_EXEC_AllocDesc(sql_src, 1);
if (retcode < 0)
return retcode;
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_TYPE_FS,
REC_BYTE_V_ANSI, 0);
if (retcode < 0)
return retcode;
// Allocate a descriptor which will hold the SQL statement input
input_desc = new(heap_) SQLSTMT_ID;
init_SQLDESC_ID(input_desc, SQLCLI_CURRENT_VERSION, desc_handle, module);
retcode = SQL_EXEC_AllocDesc(input_desc, 1);
if (retcode < 0)
return retcode;
// Allocate a descriptor which will hold the SQL statement output
output_desc = new(heap_) SQLSTMT_ID;
init_SQLDESC_ID(output_desc, SQLCLI_CURRENT_VERSION, desc_handle, module);
retcode = SQL_EXEC_AllocDesc(output_desc, 1);
if (retcode < 0)
return retcode;
return 0;
}
Lng32 ExeCliInterface::prepare(const char * stmtStr,
SQLMODULE_ID * module,
SQLSTMT_ID * stmt,
SQLDESC_ID * sql_src,
SQLDESC_ID * input_desc,
SQLDESC_ID * output_desc,
char ** outputBuf,
Queue * outputVarPtrList,
char ** inputBuf,
Queue * inputVarPtrList,
char *uniqueStmtId,
Lng32 *uniqueStmtIdLen,
SQL_QUERY_COST_INFO *query_cost_info,
SQL_QUERY_COMPILER_STATS_INFO *comp_stats_info,
NABoolean monitorThis,
NABoolean doNotCachePlan)
{
Lng32 retcode = 0;
ULng32 prepFlags = 0;
SQL_QUERY_COST_INFO local_query_cost_info;
SQL_QUERY_COMPILER_STATS_INFO local_comp_stats_info;
if (monitorThis)
prepFlags |= PREPARE_MONITOR_THIS_QUERY;
if ((currContext_) && (currContext_->getSessionDefaults()))
{
if(currContext_->getSessionDefaults()->callEmbeddedArkcmp())
prepFlags |= PREPARE_USE_EMBEDDED_ARKCMP;
}
if (doNotCachePlan)
{
prepFlags |= PREPARE_NO_TEXT_CACHE;
prepFlags |= PREPARE_DONT_CACHE;
}
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_LENGTH,
strlen(stmtStr) + 1, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_VAR_PTR,
(Long)stmtStr, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_SetDescItem(sql_src, 1, SQLDESC_CHAR_SET,
(Int32)SQLCHARSETCODE_UTF8,0);
if (retcode != SUCCESS)
return retcode;
char parentQid[ComSqlId::MAX_QUERY_ID_LEN + 1];
char *pQidPtr = NULL;
if (parentQid_)
{
// The parentQid_ is a const char *, but the CLI doesn't
// want a const char * arg, so convert it safely here.
memset(parentQid, 0, sizeof(parentQid));
memcpy(parentQid, parentQid_, ComSqlId::MAX_QUERY_ID_LEN);
pQidPtr = parentQid;
}
retcode = SQL_EXEC_SetStmtAttr(stmt, SQL_ATTR_PARENT_QID, 0, pQidPtr);
if (retcode < 0)
return retcode;
// set parserflags to indicate that this is an internal query from exeutil
NABoolean flagWasSetHere = FALSE;
if (currContext_)
{
if (((currContext_->getSqlParserFlags() & 0x20000) == 0) &&
(NOT notExeUtilInternalQuery())) // this is an exeutil internal query. This is the default.
{
flagWasSetHere = TRUE;
currContext_->setSqlParserFlags(0x20000); // INTERNAL_QUERY_FROM EXEUTIL
}
}
if (uniqueStmtId == NULL)
retcode = SQL_EXEC_Prepare2(stmt, sql_src,NULL,0,NULL,
(query_cost_info?query_cost_info:&local_query_cost_info),
(comp_stats_info?comp_stats_info:&local_comp_stats_info),
NULL,0,prepFlags);
else
{
prepFlags |= PREPARE_STANDALONE_QUERY;
retcode = SQL_EXEC_Prepare2(stmt, sql_src, NULL, 0, NULL,
(query_cost_info?query_cost_info:&local_query_cost_info),
(comp_stats_info?comp_stats_info:&local_comp_stats_info),
uniqueStmtId, uniqueStmtIdLen, prepFlags);
}
// reset internal exeutil query parserflags if it was set in this method.
if ((currContext_) && (flagWasSetHere))
currContext_->resetSqlParserFlags(0x20000); // INTERNAL_QUERY_FROM EXEUTIL
// return the error code that was returned from SQL_EXEC_Prepare
if (retcode < 0)
return retcode;
// clear diagnostics to reset any warnings.
SQL_EXEC_ClearDiagnostics(NULL);
Lng32 num_input_entries, num_output_entries;
retcode = SQL_EXEC_DescribeStmt(stmt, input_desc, output_desc);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescEntryCount(input_desc, &num_input_entries);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescEntryCount(output_desc, &num_output_entries);
if (retcode != SUCCESS)
return retcode;
numInputEntries_ = num_input_entries;
numOutputEntries_ = num_output_entries;
inputAttrs_ = NULL;
outputAttrs_ = NULL;
if (numInputEntries_ > 0)
inputAttrs_ = (Attrs*) (new(heap_) char[sizeof(Attrs) * numInputEntries_]);
if (numOutputEntries_ > 0)
outputAttrs_ = (Attrs*) (new(heap_) char[sizeof(Attrs) * numOutputEntries_]);
short entry=1;
Lng32 datatype = 0;
Lng32 datacharset = 0;
Lng32 length = 0;
Lng32 null_flag = 0;
Lng32 dataOffset = -1;
Lng32 nullIndOffset = -1;
outputDatalen_ = 0;
inputDatalen_ = 0;
for (; entry <= num_output_entries; entry++)
{
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_TYPE_FS,
&datatype, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_OCTET_LENGTH,
&length, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_NULLABLE,
&null_flag, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_CHAR_SET,
&datacharset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
outputDatalen_ += length;
if (null_flag)
outputDatalen_ += SQL_NULL_HDR_SIZE;
if (datatype == REC_BYTE_V_ASCII ||
datatype == REC_BYTE_V_ASCII_LONG ||
datatype == REC_BYTE_V_DOUBLE)
outputDatalen_ += SQL_VARCHAR_HDR_SIZE;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_NULL_IND_OFFSET,
&nullIndOffset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_DATA_OFFSET,
&dataOffset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
outputAttrs_[entry-1].fsDatatype_ = datatype;
outputAttrs_[entry-1].length_ = length;
outputAttrs_[entry-1].nullFlag_ = null_flag;
outputAttrs_[entry-1].indOffset_ = nullIndOffset;
outputAttrs_[entry-1].varOffset_ = dataOffset;
}
if (outputBuf)
{
if ((*outputBuf == NULL) &&
(outputDatalen_ > 0))
*outputBuf = new (heap_) char[outputDatalen_];
Lng32 curpos = 0;
for (entry=1; entry <= num_output_entries; entry++)
{
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_NULLABLE,
&null_flag, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
if (null_flag)
{
retcode = SQL_EXEC_SetDescItem(output_desc, entry,
SQLDESC_IND_PTR,
(Long)&(*outputBuf)[curpos],0);
if (retcode != SUCCESS)
return retcode;
curpos += SQL_NULL_HDR_SIZE;
}
retcode = SQL_EXEC_SetDescItem(output_desc, entry,
SQLDESC_VAR_PTR,
(Long)&(*outputBuf)[curpos],0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_OCTET_LENGTH,
&length, 0, 0, 0, 0);
if (outputVarPtrList)
{
outputVarPtrList->insert((char*) &(*outputBuf)[curpos]);
}
curpos += length;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_TYPE_FS,
&datatype, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc, entry,
SQLDESC_CHAR_SET,
&datacharset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
if (datatype == REC_BYTE_V_ASCII ||
datatype == REC_BYTE_V_ASCII_LONG ||
datatype == REC_BYTE_V_DOUBLE)
curpos += SQL_VARCHAR_HDR_SIZE;
}
}
entry=1;
inputDatalen_ = 0;
for (; entry <= num_input_entries; entry++)
{
Lng32 alignedLen = 0;
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_ALIGNED_LENGTH,
&alignedLen, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
inputDatalen_ += alignedLen;
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_TYPE_FS,
&datatype, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_OCTET_LENGTH,
&length, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_NULLABLE,
&null_flag, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_NULL_IND_OFFSET,
&nullIndOffset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_DATA_OFFSET,
&dataOffset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
inputAttrs_[entry-1].fsDatatype_ = datatype;
inputAttrs_[entry-1].length_ = length;
inputAttrs_[entry-1].nullFlag_ = null_flag;
inputAttrs_[entry-1].indOffset_ = nullIndOffset;
inputAttrs_[entry-1].varOffset_ = dataOffset;
}
if (inputBuf)
{
if ((*inputBuf == NULL) &&
(inputDatalen_ > 0))
*inputBuf = new (heap_) char[inputDatalen_];
Lng32 curpos = 0;
for (entry=1; entry <= num_input_entries; entry++)
{
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_NULL_IND_OFFSET,
&nullIndOffset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(input_desc, entry,
SQLDESC_DATA_OFFSET,
&dataOffset, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
if (nullIndOffset >= 0)
{
retcode = SQL_EXEC_SetDescItem(input_desc, entry,
SQLDESC_IND_PTR,
(Long)&(*inputBuf)[nullIndOffset],0);
if (retcode != SUCCESS)
return retcode;
}
retcode = SQL_EXEC_SetDescItem(input_desc, entry,
SQLDESC_VAR_PTR,
(Long)&(*inputBuf)[dataOffset],0);
if (retcode != SUCCESS)
return retcode;
}
}
return 0;
}
Lng32 ExeCliInterface::setupExplainData(SQLMODULE_ID * module,
SQLSTMT_ID * stmt)
{
Lng32 retcode = 0;
if (explainData_)
NADELETEBASIC(explainData_, getHeap());
explainData_ = NULL;
explainDataLen_ = 0;
// get explain fragment.
explainDataLen_ = 50000; // start with 50K bytes
Int32 retExplainLen = 0;
explainData_ = new(getHeap()) char[explainDataLen_+1];
retcode = SQL_EXEC_GetExplainData(stmt,
explainData_, explainDataLen_+1,
&retExplainLen
);
if (retcode == -CLI_GENCODE_BUFFER_TOO_SMALL)
{
NADELETEBASIC(explainData_, getHeap());
explainDataLen_ = retExplainLen;
explainData_ = new(getHeap()) char[explainDataLen_ + 1];
retcode = SQL_EXEC_GetExplainData(stmt,
explainData_, explainDataLen_+1,
&retExplainLen
);
}
if (retcode != SUCCESS)
{
NADELETEBASIC(explainData_, getHeap());
explainData_ = NULL;
explainDataLen_ = 0;
return retcode;
}
explainDataLen_ = retExplainLen;
return retcode;
}
Lng32 ExeCliInterface::setupExplainData()
{
return setupExplainData(module_, stmt_);
}
Lng32 ExeCliInterface::exec(char * inputBuf, Lng32 inputBufLen)
{
Lng32 retcode = 0;
if (! stmt_)
{
return -CLI_STMT_NOT_EXISTS;
}
// set parserflags to indicate that this is an internal query from exeutil
NABoolean flagWasSetHere = FALSE;
if (currContext_)
{
if (((currContext_->getSqlParserFlags() & 0x20000) == 0) &&
(NOT notExeUtilInternalQuery())) // this is an exeutil internal query. This is the default.
{
flagWasSetHere = TRUE;
currContext_->setSqlParserFlags(0x20000); // INTERNAL_QUERY_FROM EXEUTIL
}
}
if ((inputBuf) && (inputBuf_) && (inputDatalen_ > 0) && (inputBufLen > 0))
memcpy(inputBuf_, inputBuf, MINOF(inputDatalen_, inputBufLen));
retcode = SQL_EXEC_Exec(stmt_, input_desc_, 0);
// reset internal exeutil query parserflags if it was set in this method.
if ((currContext_) && (flagWasSetHere))
currContext_->resetSqlParserFlags(0x20000); // INTERNAL_QUERY_FROM EXEUTIL
if (retcode != SUCCESS)
return retcode;
return retcode;
}
Lng32 ExeCliInterface::fetch()
{
Lng32 retcode = 0;
retcode = SQL_EXEC_Fetch(stmt_, output_desc_, 0);
if (retcode != SUCCESS)
return retcode;
return retcode;
}
//if indicator pointer is NULL, do not retrieve the indicator
//the datatype SQLTYPECODE... is added (the others did not work)
Lng32 ExeCliInterface::getPtrAndLen(short entry, char* &ptr, Lng32 &len, short**ind)
{
Long data_addr;
Lng32 datatype = 0;
Lng32 retcode;
Long ind_addr;
retcode = SQL_EXEC_GetDescItem(output_desc_, entry,
SQLDESC_VAR_PTR,
&data_addr, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc_, entry,
SQLDESC_IND_PTR ,
&ind_addr, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
if (ind != NULL)
*ind = (short*)ind_addr;
retcode = SQL_EXEC_GetDescItem(output_desc_, entry,
SQLDESC_TYPE,
&datatype, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescItem(output_desc_, entry,
SQLDESC_OCTET_LENGTH,
&len, 0, 0, 0, 0);
if (retcode != SUCCESS)
return retcode;
short *nullIndPtr = (short *)ind_addr;
if (nullIndPtr && *nullIndPtr < 0)
{
// without this test, when "showddl component sql_operations"
// ran some child query which returned a nullable column
// with a SQL NULL value, junk from data_addr was interpreted
// as a length and the caller of this method tried to allocate
// too many bytes.
len = 0;
}
else
if (datatype == REC_BYTE_V_ASCII ||
datatype == REC_BYTE_V_ASCII_LONG ||
datatype == REC_BYTE_V_DOUBLE ||
datatype == SQLTYPECODE_VARCHAR_WITH_LENGTH ||
datatype == SQLTYPECODE_VARCHAR_LONG ||
datatype == SQLTYPECODE_BLOB ||
datatype == SQLTYPECODE_CLOB
)
{
// Depending on value of len, first 2 or 4 bytes of data indicate
// the actual length -- adjust data and length
if (len & 0xFFFF8000)
{
Lng32 VClen;
str_cpy_all((char*)&VClen, (char*)data_addr, sizeof(Lng32));
data_addr += sizeof(Lng32);
len = VClen;
}
else
{
short VClen;
str_cpy_all((char*)&VClen, (char*)data_addr, sizeof(short));
data_addr += sizeof(short);
len = VClen;
}
}
ptr = (char*)data_addr;
return 0;
}
Lng32 ExeCliInterface::getHeadingAndLen(short entry, char* heading, Lng32 &len)
{
Lng32 retcode;
len = 0;
retcode = SQL_EXEC_GetDescItem(output_desc_, entry,
SQLDESC_HEADING,
0, heading,
ComMAX_1_PART_EXTERNAL_UTF8_NAME_LEN_IN_BYTES, &len, 0);
if (retcode != SUCCESS)
return retcode;
if (len == 0)
{
retcode = SQL_EXEC_GetDescItem(output_desc_, entry,
SQLDESC_NAME,
0, heading,
ComMAX_1_PART_EXTERNAL_UTF8_NAME_LEN_IN_BYTES/*CAT_MAX_HEADING_LEN*/, &len, 0);
if (retcode != SUCCESS)
return retcode;
}
return 0;
}
Lng32 ExeCliInterface::getNumEntries(Lng32 &numInput, Lng32 &numOutput)
{
Lng32 retcode = 0;
retcode = SQL_EXEC_GetDescEntryCount(input_desc_, &numInput);
if (retcode != SUCCESS)
return retcode;
retcode = SQL_EXEC_GetDescEntryCount(output_desc_, &numOutput);
if (retcode != SUCCESS)
return retcode;
return retcode;
}
Lng32 ExeCliInterface::getAttributes(short entry, NABoolean forInput,
Lng32 &fsDatatype, Lng32 &length,
Lng32 *indOffset, Lng32 *varOffset)
{
Lng32 retcode = 0;
if (forInput)
{
fsDatatype = inputAttrs_[entry-1].fsDatatype_;
length = inputAttrs_[entry-1].length_;
if (indOffset)
*indOffset = inputAttrs_[entry-1].indOffset_;
if (varOffset)
*varOffset = inputAttrs_[entry-1].varOffset_;
}
else
{
fsDatatype = outputAttrs_[entry-1].fsDatatype_;
length = outputAttrs_[entry-1].length_;
if (indOffset)
*indOffset = outputAttrs_[entry-1].indOffset_;
if (varOffset)
*varOffset = outputAttrs_[entry-1].varOffset_;
}
return retcode;
}
Lng32 ExeCliInterface::getDataOffsets(short entry, Lng32 forInput,
Lng32 *indOffset, Lng32 *varOffset)
{
Lng32 temp;
if (forInput)
{
if (inputAttrs_ && inputAttrs_[entry-1].varOffset_ && inputAttrs_[entry-1].indOffset_)
{
*varOffset = inputAttrs_[entry-1].varOffset_;
*indOffset = inputAttrs_[entry-1].indOffset_;
}
else
{
return getAttributes(entry, forInput, temp, temp,
indOffset, varOffset);
}
}
else
{
return getAttributes(entry, forInput, temp, temp,
indOffset, varOffset);
}
return 0;
}
Lng32 ExeCliInterface::getStmtAttr(char * stmtName, Lng32 attrName,
Lng32 * numeric_value, char * string_value)
{
Lng32 retcode = 0;
SQLMODULE_ID module;
init_SQLMODULE_ID(&module);
char stmtNameBuf[400];
SQLSTMT_ID stmt;
init_SQLSTMT_ID(&stmt, SQLCLI_CURRENT_VERSION, stmt_name, &module);
stmt.identifier = stmtNameBuf;
strcpy((char*)stmt.identifier, stmtName);
stmt.identifier_len = (Lng32)strlen(stmtName);
retcode = SQL_EXEC_GetStmtAttr(&stmt, attrName, numeric_value, string_value,
0, NULL);
return retcode;
}
Lng32 ExeCliInterface::close()
{
Lng32 retcode = 0;
if (stmt_)
{
retcode = SQL_EXEC_CloseStmt(stmt_);
if (retcode != SUCCESS)
return retcode;
}
return retcode;
}
Lng32 ExeCliInterface::executeImmediatePrepare(const char * stmtStr,
char * outputBuf,
Lng32 * outputBufLen,
Int64 * rowsAffected,
NABoolean monitorThis,
char * stmtName
)
{
Lng32 retcode = 0;
if (outputBufLen)
*outputBufLen = 0;
retcode = allocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_,
stmtName);
if (retcode != SUCCESS)
return retcode;
retcode = prepare(stmtStr, module_, stmt_, sql_src_,
input_desc_, output_desc_, &outputBuf,NULL,&inputBuf_,
NULL,NULL,NULL,NULL,NULL,monitorThis);
if (retcode < 0)
{
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
return retcode;
}
return 0;
}
Lng32 ExeCliInterface::executeImmediatePrepare2(const char * stmtStr,
char *uniqueStmtId,
Lng32 *uniqueStmtIdLen,
SQL_QUERY_COST_INFO *query_cost_info,
SQL_QUERY_COMPILER_STATS_INFO *comp_stats_info,
char * outputBuf,
Lng32 * outputBufLen,
Int64 * rowsAffected,
NABoolean monitorThis
)
{
Lng32 retcode = 0;
if (outputBufLen)
*outputBufLen = 0;
retcode = allocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
if (retcode != SUCCESS)
return retcode;
retcode = prepare(stmtStr, module_, stmt_, sql_src_,
input_desc_, output_desc_, &outputBuf, NULL, NULL, NULL,
uniqueStmtId, uniqueStmtIdLen, query_cost_info, comp_stats_info,monitorThis);
if (retcode < 0)
{
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
return retcode;
}
return 0;
}
Lng32 ExeCliInterface::executeImmediateExec(const char * stmtStr,
char * outputBuf,
Lng32 * outputBufLen,
NABoolean nullTerminate,
Int64 * rowsAffected,
ComDiagsArea **diagsArea)
{
Lng32 retcode = 0;
Lng32 diagsCount = 0;
retcode = exec();
if (retcode < 0)
{
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
goto ExecReturn;
}
retcode = fetch();
if (retcode < 0)
{
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
goto ExecReturn;
}
if ((outputBuf) &&
(outputBufLen))
{
*outputBufLen = 0;
if (retcode != 100)
{
char * ptr;
Lng32 len;
getPtrAndLen(1, ptr, len);
str_cpy_all(outputBuf, ptr, len);
if (nullTerminate)
outputBuf[len] = 0;
*outputBufLen = len;
}
}
Lng32 rc;
if (retcode >= 0)
{
if (rowsAffected)
{
Int64 tmpRowsAffected = 0;
rc = SQL_EXEC_GetDiagnosticsStmtInfo2(NULL, SQLDIAG_ROW_COUNT,
&tmpRowsAffected, NULL,
0, NULL);
if (rc == EXE_NUMERIC_OVERFLOW)
{
GetRowsAffected(rowsAffected);
}
else
*rowsAffected = tmpRowsAffected;
}
rc = SQL_EXEC_GetDiagnosticsStmtInfo2(NULL, SQLDIAG_NUMBER,
&diagsCount, NULL, 0, NULL);
// No need to passback the warnings of SQL_NO_DATA (100)
if (retcode == 100)
diagsCount--;
}
ExecReturn:
if (retcode < 0 || diagsCount > 0)
{
if (diagsArea != NULL)
{
if (*diagsArea == NULL)
*diagsArea = ComDiagsArea::allocate(heap_);
rc = SQL_EXEC_MergeDiagnostics_Internal(**diagsArea);
}
// if diagsArea is not passed in, retain the diagnostics info
// in ContextCli for it to be retrieved later
// But, deallocate the statement
else
{
rc = close();
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
return retcode;
}
}
rc = close();
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
clearGlobalDiags();
return retcode;
}
// When the globalDiags is not null, errors and warnings are
// passed to the caller. If *globalsDiags points to NULL,
// allocate ComDiagsArea and pass back the error or warnings
// to the caller.
//
// If *globalDiags points to ComDiagsArea already, pass back
// the diagnostics conditions back to the caller after executing
// the stmtStr along with new errors or warnings.
Lng32 ExeCliInterface::executeImmediate(const char * stmtStr,
char * outputBuf,
Lng32 * outputBufLen,
NABoolean nullTerminate,
Int64 * rowsAffected,
NABoolean monitorThis,
ComDiagsArea **globalDiags)
{
Lng32 retcode = 0;
ComDiagsArea * tempDiags = NULL;
if (globalDiags != NULL && *globalDiags != NULL && (*globalDiags)->getNumber() > 0)
{
tempDiags = ComDiagsArea::allocate(heap_);
tempDiags->mergeAfter(**globalDiags);
}
clearGlobalDiags();
outputBuf_ = NULL;
inputBuf_ = NULL;
retcode = executeImmediatePrepare(stmtStr,
(nullTerminate ? outputBuf_ : outputBuf),
outputBufLen,
rowsAffected,monitorThis);
if (retcode < 0)
goto ExecuteImmediateReturn;
retcode = executeImmediateExec(stmtStr,
outputBuf, outputBufLen,
nullTerminate,
rowsAffected,
globalDiags);
ExecuteImmediateReturn:
if ((globalDiags))
{
// Allocate the diagnostics area if needed
// and populate the diagnostics conditions
if (*globalDiags == NULL && retcode != 0 && retcode != 100) {
*globalDiags = ComDiagsArea::allocate(getHeap());
SQL_EXEC_MergeDiagnostics_Internal(**globalDiags);
}
// populate the diagnostics conditons passed in
if (tempDiags)
(*globalDiags)->mergeAfter(*tempDiags);
}
if (tempDiags)
tempDiags->deAllocate();
return retcode;
}
short ExeCliInterface::fetchRowsPrologue(const char * sqlStrBuf,
NABoolean noExec,
NABoolean monitorThis,
char * stmtName)
{
Lng32 retcode;
clearGlobalDiags();
retcode = allocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_,
stmtName);
if (retcode < 0)
{
//ex_assert(0, "Error in fetchRows");
return (short)retcode;
}
outputBuf_ = NULL;
inputBuf_ = NULL;
retcode = prepare(sqlStrBuf, module_, stmt_, sql_src_,
input_desc_, output_desc_, &outputBuf_, NULL,
&inputBuf_, NULL,NULL,NULL,NULL,NULL,monitorThis);
if (retcode < 0)
{
//ex_assert(0, "Error in fetchRows");
return (short)retcode;
}
if (NOT noExec)
{
retcode = exec();
if (retcode < 0)
{
//ex_assert(0, "Error in fetchRows");
return (short)retcode;
}
}
return 0;
}
short ExeCliInterface::fetchRowsEpilogue(const char * sqlStrBuf,
NABoolean noClose)
{
if (NOT noClose)
close();
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
if (NOT noClose)
SQL_EXEC_ClearDiagnostics(NULL);
return 0;
}
short ExeCliInterface::initializeInfoList(Queue* &infoList,
NABoolean infoListIsOutputInfo)
{
if (infoList)
{
infoList->position();
while (NOT infoList->atEnd())
{
if (infoListIsOutputInfo)
{
OutputInfo * r = (OutputInfo*)infoList->getCurr();
r->dealloc(getHeap());
}
else
{
char * c = (char*)infoList->getCurr();
NADELETEBASIC(c, getHeap());
}
infoList->advance();
}
NADELETE(infoList, Queue, getHeap());
}
infoList = new(getHeap()) Queue(getHeap());
return 0;
}
short ExeCliInterface::fetchAllRows(Queue * &infoList,
const char * query,
Lng32 inNumOutputEntries,
NABoolean varcharFormat,
NABoolean monitorThis,
NABoolean initInfoList)
{
short rc = 0;
Lng32 numOutputEntries = inNumOutputEntries;
if (initInfoList)
{
rc = initializeInfoList(infoList, TRUE);
if (rc < 0)
{
return rc;
}
}
rc = fetchRowsPrologue(query,FALSE,monitorThis);
if (rc < 0)
{
return rc;
}
NABoolean rowsFound = FALSE;
while ((rc >= 0) &&
(rc != 100))
{
rc = (short)fetch();
if (rc < 0)
{
fetchRowsEpilogue(0, TRUE);
return rc;
}
if (rc == 100)
continue;
rowsFound = TRUE;
if (numOutputEntries == -1)
{
char * ob = new(getHeap()) char[outputDatalen()];
str_cpy_all(ob, outputBuf(),
outputDatalen());
infoList->insert(ob);
}
else
{
if (numOutputEntries == 0)
numOutputEntries = numOutputEntries_;
OutputInfo * oi = new(getHeap()) OutputInfo(numOutputEntries);
for (Int32 j = 0; j < numOutputEntries; j++)
{
char * ptr;
Lng32 len;
getPtrAndLen(j+1, ptr, len);
NABoolean nullTerminate =
DFS2REC::is8bitCharacter(outputAttrs_[j].fsDatatype_);
char * r = new(getHeap()) char
[(varcharFormat ? SQL_VARCHAR_HDR_SIZE : 0)
+ len + (nullTerminate ? 1 : 0)];
if (varcharFormat)
{
*(short*)r = (short)len;
str_cpy_all(&r[SQL_VARCHAR_HDR_SIZE], ptr, len);
if (nullTerminate)
r[SQL_VARCHAR_HDR_SIZE + len] = 0;
}
else
{
str_cpy_all(r, ptr, len);
if (nullTerminate)
r[len] = 0;
}
oi->insert(j, r, len);
}
infoList->insert(oi);
}
} // while
rc = fetchRowsEpilogue(0);
if (rc < 0)
{
return rc;
}
if (NOT rowsFound)
rc = 100;
return rc;
}
short ExeCliInterface::clearExecFetchClose(char * inputBuf,
Lng32 inputBufLen,
// ptr to buf where output values will be copied to.
// Caller need to allocate this.
char * outputBuf,
Lng32 * outputBufLen)
{
Lng32 retcode = 0;
SQL_EXEC_ClearDiagnostics(NULL);
retcode = exec(inputBuf, inputBufLen);
if (retcode < 0)
{
return (short)retcode;
}
retcode = fetch();
if (retcode < 0)
{
return (short)retcode;
}
if ((outputBuf) &&
(outputBufLen))
{
*outputBufLen = 0;
if (retcode != 100)
{
char * currPtr = outputBuf;
for (Int32 j = 0; j < numOutputEntries_; j++)
{
char * ptr;
Lng32 len;
getPtrAndLen(j+1, ptr, len);
str_cpy_all(currPtr, ptr, len);
currPtr += len;
*outputBufLen += len;
}
}
}
close();
if (retcode == 100)
fetchRowsEpilogue(NULL, TRUE);
return (short)retcode;
}
short ExeCliInterface::clearExecFetchCloseOpt(char * inputBuf,
Lng32 inputBufLen,
// ptr to buf where output values will be copied to.
// Caller need to allocate this.
char * outputBuf,
Lng32 * outputBufLen,
Int64 * rowsAffected)
{
Lng32 retcode = 0;
if (inputBuf)
{
if (inputDatalen_ < inputBufLen)
{
// input data will not fit in inputBuf_.
// return error.
return -EXE_STRING_OVERFLOW;
}
str_cpy_all(inputBuf_, inputBuf, inputBufLen);
}
if (rowsAffected)
*rowsAffected = 0;
retcode = SQL_EXEC_ClearExecFetchClose(
stmt_,
(numInputEntries_ > 0 ? input_desc_ : NULL),
(numOutputEntries_ > 0 ? output_desc_ : NULL),
0, 0, 0);
if ((retcode == 0) ||
((retcode >= 0) && (retcode != 100)))
{
if ((numOutputEntries_ > 0) &&
(outputBuf) &&
(outputBufLen))
{
*outputBufLen = 0;
char * currPtr = outputBuf;
for (Int32 j = 0; j < numOutputEntries_; j++)
{
char * ptr;
Lng32 len;
getPtrAndLen(j+1, ptr, len);
str_cpy_all(currPtr, ptr, len);
currPtr += len;
*outputBufLen += len;
}
if (rowsAffected)
{
*rowsAffected = 1;
}
} // values being returned
else if (rowsAffected)
{
Lng32 tmpRowsAffected = 0;
retcode = SQL_EXEC_GetDiagnosticsStmtInfo2(NULL, SQLDIAG_ROW_COUNT,
&tmpRowsAffected, NULL,
0, NULL);
if(retcode == EXE_NUMERIC_OVERFLOW) // rowsAffected > LONG_MAX
{
GetRowsAffected(rowsAffected);
}
else
*rowsAffected = (Int64)tmpRowsAffected;
} // rowsAffected
}
return (short)retcode;
}
Lng32 ExeCliInterface::executeImmediateCEFC(const char * stmtStr,
char * inputBuf,
Lng32 inputBufLen,
char * outputBuf,
Lng32 * outputBufLen,
Int64 * rowsAffected
)
{
Lng32 retcode = 0;
clearGlobalDiags();
outputBuf_ = NULL;
inputBuf_ = NULL;
retcode = executeImmediatePrepare(stmtStr,
outputBuf,
outputBufLen,
rowsAffected);
if (retcode < 0)
goto ExecuteImmediateCEFCReturn;
retcode = clearExecFetchCloseOpt(inputBuf, inputBufLen, NULL, NULL, rowsAffected);
ExecuteImmediateCEFCReturn:
return retcode;
}
Lng32 ExeCliInterface::cwrsAllocStuff(SQLMODULE_ID * &module,
SQLSTMT_ID * &stmt,
SQLDESC_ID * &sql_src,
SQLDESC_ID * &input_desc,
SQLDESC_ID * &output_desc,
SQLDESC_ID * &rs_input_maxsize_desc,
const char * stmtName
)
{
Lng32 retcode = 0;
retcode = cwrsDeallocStuff(module,
stmt,
sql_src,
input_desc,
output_desc,
rs_input_maxsize_desc);
if (retcode < 0)
{
return (short)retcode;
}
retcode = allocStuff(module,
stmt,
sql_src,
input_desc,
output_desc);
if (retcode < 0)
{
return (short)retcode;
}
// Allocate a descriptor to set input array maximum size
rs_input_maxsize_desc = new(heap_) SQLSTMT_ID;
init_SQLDESC_ID(rs_input_maxsize_desc, SQLCLI_CURRENT_VERSION, desc_handle, module);
retcode = SQL_EXEC_AllocDesc(rs_input_maxsize_desc, 1);
if (retcode < 0)
return retcode;
retcode = SQL_EXEC_SetDescItem(rs_input_maxsize_desc, 1, SQLDESC_TYPE,
SQLTYPECODE_INTEGER, NULL);
if (retcode < 0)
return retcode;
retcode = SQL_EXEC_SetDescItem( rs_input_maxsize_desc,
1, // entry #1, attr value.
SQLDESC_VAR_PTR, // what to set - host var addr
(long) &rsMaxsize_, // Notice that output from CLI
// will be read from host var
// rowset_size.
NULL);
retcode = SQL_EXEC_SetStmtAttr(stmt,
SQL_ATTR_INPUT_ARRAY_MAXSIZE,
rsMaxsize_,
NULL);
return retcode;
}
Lng32 ExeCliInterface::cwrsDeallocStuff(
SQLMODULE_ID * &module,
SQLSTMT_ID * &stmt,
SQLDESC_ID * &sql_src,
SQLDESC_ID * &input_desc,
SQLDESC_ID * &output_desc,
SQLDESC_ID * &rs_input_maxsize_desc)
{
deallocStuff(module, stmt, sql_src, input_desc, output_desc);
if (rs_input_maxsize_desc)
{
SQL_EXEC_DeallocDesc(rs_input_maxsize_desc);
NADELETEBASIC(rs_input_maxsize_desc, heap_);
rs_input_maxsize_desc = NULL;
}
return 0;
}
Lng32 ExeCliInterface::cwrsPrepare(const char * stmtStr,
Lng32 rs_maxsize, NABoolean monitorThis)
{
Lng32 retcode = 0;
rsMaxsize_ = rs_maxsize;
retcode = cwrsAllocStuff(module_, stmt_, sql_src_,
input_desc_, output_desc_,
rs_input_maxsize_desc_);
if (retcode != SUCCESS)
return retcode;
retcode = prepare(stmtStr, module_, stmt_, sql_src_,
input_desc_, output_desc_, NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,monitorThis);
if (retcode < 0)
{
cwrsDeallocStuff(module_, stmt_, sql_src_,
input_desc_, output_desc_,
rs_input_maxsize_desc_);
return retcode;
}
numQuadFields_ = numInputEntries_;// + 1;
quadFields_ = (SQLCLI_QUAD_FIELDS*)
new (heap_) char[sizeof(SQLCLI_QUAD_FIELDS) * numQuadFields_];
rsInputBuffer_ = new(heap_) char[rsMaxsize_ * inputDatalen_];
Lng32 fsDatatype;
Lng32 length;
Lng32 indOffset = 0;
Lng32 varOffset = 0;
quadFields_[0].var_layout = 0;
quadFields_[0].var_ptr = (void *)&currRSrow_;
quadFields_[0].ind_layout = 0;
quadFields_[0].ind_ptr = NULL;
Lng32 currOffset = 0;
for (Lng32 entry = 2; entry <= numInputEntries_; entry++)
{
getAttributes(entry, TRUE,
fsDatatype, length,
&indOffset, &varOffset);
quadFields_[entry-1].var_layout = length;
quadFields_[entry-1].var_ptr = (void*)&rsInputBuffer_[currOffset];
quadFields_[entry-1].ind_layout = 0;
quadFields_[entry-1].ind_ptr = NULL;
currOffset += length * rsMaxsize_;
}
currRSrow_ = 0;
return 0;
}
Lng32 ExeCliInterface::cwrsExec(
char * inputRow,
Int32 inputRowLen,
Int64 * rowsAffected)
{
Lng32 retcode = 0;
Int32 rowset_status[1]; // Has no functionality currently.
//However it is part of RowsetSetDesc API
if ((inputRow) && (currRSrow_ < rsMaxsize_))
{
Lng32 fsDatatype;
Lng32 length;
Lng32 indOffset = 0;
Lng32 varOffset = 0;
for (Lng32 entry = 2; entry <= numInputEntries_; entry++)
{
getAttributes(entry, TRUE,
fsDatatype, length,
&indOffset, &varOffset);
str_cpy_all((char*)((long)(quadFields_[entry-1].var_ptr) +
currRSrow_*length),
&inputRow[varOffset], length);
}
currRSrow_++;
return 0;
}
if ((inputRow == NULL) && (currRSrow_ == 0))
return 0;
retcode = SQL_EXEC_SETROWSETDESCPOINTERS(input_desc_,
currRSrow_,
rowset_status,
1,
numQuadFields_,
quadFields_);
if (retcode < 0)
return retcode;
retcode = exec();
if (retcode < 0)
return retcode;
retcode = fetch();
if (retcode < 0)
return retcode;
if (retcode >= 0)
{
if (rowsAffected)
{
Lng32 tmpRowsAffected = 0;
retcode = SQL_EXEC_GetDiagnosticsStmtInfo2(NULL, SQLDIAG_ROW_COUNT,
&tmpRowsAffected, NULL,
0, NULL);
if(retcode == EXE_NUMERIC_OVERFLOW) // rowsAffected > LONG_MAX
{
GetRowsAffected(rowsAffected);
}
else
*rowsAffected = (Int64)tmpRowsAffected;
retcode = 0;
}
}
retcode = close();
currRSrow_ = 0;
// current input row has not been moved to the rowset buffer.
// move the input row to the rowset buffer
return cwrsExec(inputRow, inputRowLen, rowsAffected);
}
Lng32 ExeCliInterface::cwrsClose(Int64 * rowsAffected)
{
Lng32 retcode = 0;
if (rowsAffected)
*rowsAffected = 0;
retcode = cwrsExec(NULL, 0, rowsAffected);
Lng32 retcode2 = cwrsDeallocStuff(module_, stmt_, sql_src_,
input_desc_, output_desc_,
rs_input_maxsize_desc_);
return retcode;
}
Lng32 ExeCliInterface::rwrsPrepare(const char * stmtStr, Lng32 rs_maxsize,NABoolean monitorThis)
{
Lng32 retcode = 0;
rsMaxsize_ = rs_maxsize;
retcode = allocStuff(module_, stmt_, sql_src_,
input_desc_, output_desc_);
if (retcode != SUCCESS)
return retcode;
/*
retcode = SQL_EXEC_SetStmtAttr(stmt_,
SQL_ATTR_INPUT_ARRAY_MAXSIZE,
rsMaxsize_,
NULL);
if (retcode != SUCCESS)
return retcode;
*/
retcode = prepare(stmtStr, module_, stmt_, sql_src_,
input_desc_, output_desc_, NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,monitorThis);
if (retcode < 0)
{
deallocStuff(module_, stmt_, sql_src_,
input_desc_, output_desc_);
return retcode;
}
rsInputBuffer_ = new(heap_) char[rsMaxsize_ * inputDatalen_];
retcode = SQL_EXEC_SetDescItem(input_desc_,0,SQLDESC_ROWSET_TYPE, 3, 0);
retcode = SQL_EXEC_SetDescItem(input_desc_,0,SQLDESC_ROWWISE_ROWSET_PTR,
(long)rsInputBuffer_, 0);
retcode = SQL_EXEC_SetDescItem(input_desc_,0,SQLDESC_ROWWISE_ROWSET_ROW_LEN,
inputDatalen_, 0);
currRSrow_ = 0;
return 0;
}
Lng32 ExeCliInterface::rwrsExec(
char * inputRow,
Int32 inputRowLen,
Int64 * rowsAffected)
{
Lng32 retcode = 0;
clearGlobalDiags();
if (rowsAffected)
*rowsAffected = 0;
if ((inputRow) && (currRSrow_ < rsMaxsize_))
{
str_cpy_all(&rsInputBuffer_[currRSrow_ * inputDatalen_],
inputRow, inputRowLen);
currRSrow_++;
return 0;
}
if ((inputRow == NULL) && (currRSrow_ == 0))
return 0;
retcode = SQL_EXEC_SetDescItem(input_desc_, 0, SQLDESC_ROWWISE_ROWSET_SIZE,
currRSrow_, 0);
retcode = exec();
if (retcode < 0)
return retcode;
retcode = fetch();
if (retcode < 0)
return retcode;
Lng32 cliRetcode = -1;
if (retcode >= 0)
{
cliRetcode = retcode;
if (rowsAffected)
{
Lng32 tmpRowsAffected = 0;
retcode = SQL_EXEC_GetDiagnosticsStmtInfo2(NULL, SQLDIAG_ROW_COUNT,
&tmpRowsAffected, NULL,
0, NULL);
if(retcode == EXE_NUMERIC_OVERFLOW) // rowsAffected > LONG_MAX
{
GetRowsAffected(rowsAffected);
}
else
*rowsAffected = (Int64)tmpRowsAffected;
retcode = 0;
}
}
currRSrow_ = 0;
return retcode;
}
Lng32 ExeCliInterface::rwrsClose()
{
Lng32 retcode = 0;
retcode = rwrsExec(NULL, 0, NULL);
close();
deallocStuff(module_, stmt_, sql_src_,
input_desc_, output_desc_);
return retcode;
}
short ExeCliInterface::prepareAndExecRowsPrologue(const char * sqlInitialStrBuf,
char * sqlSecondaryStrBuf,
Queue* initialOutputVarPtrList,
Queue* secondaryOutputVarPtrList,
Int64 &rowsAffected,
NABoolean monitorThis)
{
Lng32 retcode = 0;
SQL_EXEC_ClearDiagnostics(NULL);
retcode = allocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
if (retcode < 0)
return (short)retcode;
// Prepare
outputBuf_ = NULL;
inputBuf_ = NULL;
retcode = prepare(sqlInitialStrBuf, module_, stmt_, sql_src_,
input_desc_, output_desc_, &outputBuf_,
initialOutputVarPtrList, NULL,NULL,NULL,NULL,
NULL,NULL,monitorThis);
if (retcode < 0)
return (short)retcode;
retcode = allocStuff(moduleWithCK_, stmtWithCK_, sql_src_withCK_,
input_desc_withCK_, output_desc_withCK_);
if (retcode < 0)
return (short)retcode;
// Prepare
outputBuf_withCK_ = NULL;
retcode = prepare(sqlSecondaryStrBuf, moduleWithCK_, stmtWithCK_, sql_src_withCK_,
input_desc_withCK_, output_desc_withCK_, &outputBuf_withCK_,
secondaryOutputVarPtrList,NULL,NULL,NULL,NULL,
NULL,NULL,monitorThis);
if (retcode < 0)
return (short)retcode;
// Ensure the input entries have the correct character set type
retcode = setCharsetTypes();
if (retcode < 0)
return (short)retcode;
retcode = SQL_EXEC_Exec(stmt_, input_desc_, 0);
if (retcode < 0)
return (short)retcode;
Lng32 cliRetcode = -1;
retcode = SQL_EXEC_Fetch(stmt_, output_desc_, 0);
if (retcode < 0)
return (short)retcode;
if (retcode >= 0) // we continue for warnings (retcode > 0)
// and NO errors or warnings (retcode == 0)
{
cliRetcode = retcode; // save the retcode from cli fetch.
setOutputPtrsAsInputPtrs(initialOutputVarPtrList, 0);
Int64 tmpRowsAffected = 0;
retcode = SQL_EXEC_GetDiagnosticsStmtInfo2(NULL, SQLDIAG_ROW_COUNT,
&tmpRowsAffected, NULL,
0, NULL);
if(retcode == EXE_NUMERIC_OVERFLOW) // rowsAffected > LONG_MAX
{
GetRowsAffected(&rowsAffected);
}
else
rowsAffected = tmpRowsAffected;
}
SQL_EXEC_ClearDiagnostics(NULL);
retcode = SQL_EXEC_CloseStmt(stmt_);
if (retcode < 0)
return (short)retcode;
// return the return code from the cli fetch if it succeded.
if (cliRetcode != -1)
return (short) cliRetcode;
else
return (short) retcode;
}
short ExeCliInterface::execContinuingRows(Queue * continuingOutputVarPtrList,
Int64 &rowsAffected)
{
Lng32 retcode = 0;
SQL_EXEC_ClearDiagnostics(NULL);
retcode = SQL_EXEC_Exec(stmtWithCK_, input_desc_withCK_, 0);
if (retcode < 0)
return (short)retcode;
Lng32 cliRetcode = -1;
retcode = SQL_EXEC_Fetch(stmtWithCK_, output_desc_withCK_, 0);
if (retcode < 0)
return (short)retcode;
if (retcode >= 0)
{
cliRetcode = retcode; // save the retcode from cli fetch.
setOutputPtrsAsInputPtrs(continuingOutputVarPtrList, 0);
Int64 tmpRowsAffected = 0;
retcode = SQL_EXEC_GetDiagnosticsStmtInfo2(NULL, SQLDIAG_ROW_COUNT,
&tmpRowsAffected, NULL,
0, NULL);
if(retcode == EXE_NUMERIC_OVERFLOW) // rowsAffected > LONG_MAX
{
GetRowsAffected(&rowsAffected);
}
else
rowsAffected = tmpRowsAffected;
}
retcode = SQL_EXEC_CloseStmt(stmtWithCK_);
if (retcode < 0)
return (short)retcode;
// return the return code from the cli fetch if it succeded.
if (cliRetcode != -1)
return (short) cliRetcode;
else
return (short) retcode;
}
Lng32 ExeCliInterface::setCharsetTypes()
{
Lng32 retcode = 0;
Lng32 num_input_entries = 0;
// Obtain the number of entries
retcode = SQL_EXEC_GetDescEntryCount(input_desc_withCK_, &num_input_entries);
if (retcode < 0)
return (short)retcode;
Lng32 data_charset = 0;
for (Lng32 i = 1; i <= num_input_entries; i++)
{
retcode = SQL_EXEC_GetDescItem(output_desc_withCK_,
i,
SQLDESC_CHAR_SET,
&data_charset, 0, 0, 0, 0);
if (retcode < 0)
return (short)retcode;
if (data_charset != SQLCHARSETCODE_UNKNOWN)
{
retcode = SQL_EXEC_SetDescItem(input_desc_withCK_,
i,
SQLDESC_CHAR_SET,
data_charset, 0);
if (retcode < 0)
return (short)retcode;
}
}
return (short)retcode;
}
void ExeCliInterface::setOutputPtrsAsInputPtrs(Queue* outputVarPtrList,
SQLDESC_ID * target_inputDesc)
{
// Process the queue
Int32 j = 1;
outputVarPtrList->position();
while (NOT outputVarPtrList->atEnd())
{
char * entry = (char*)outputVarPtrList->getCurr();
SQL_EXEC_SetDescItem(input_desc_withCK_, j++,
SQLDESC_VAR_PTR,
(Long)entry, 0);
outputVarPtrList->advance();
}
return;
}
Lng32 ExeCliInterface::prepareAndExecRowsEpilogue()
{
Lng32 retcode = 0;
retcode = close();
deallocStuff(module_, stmt_, sql_src_, input_desc_, output_desc_);
if (stmtWithCK_)
{
retcode = SQL_EXEC_CloseStmt(stmtWithCK_);
}
deallocStuff(moduleWithCK_, stmtWithCK_,
sql_src_withCK_, input_desc_withCK_, output_desc_withCK_);
SQL_EXEC_ClearDiagnostics(NULL);
return 0;
}
Lng32 ExeCliInterface::beginWork()
{
return executeImmediate("begin work;");
}
Lng32 ExeCliInterface::commitWork()
{
return executeImmediate("commit work waited;");
}
Lng32 ExeCliInterface::rollbackWork()
{
return executeImmediate("rollback work;");
}
Lng32 ExeCliInterface::autoCommit(NABoolean v)
{
if (v)
return executeImmediate("set transaction autocommit ON;");
else
return executeImmediate("set transaction autocommit OFF;");
}
Lng32 ExeCliInterface::beginXn()
{
return SQL_EXEC_Xact(SQLTRANS_BEGIN, 0);
}
Lng32 ExeCliInterface::commitXn()
{
return SQL_EXEC_Xact(SQLTRANS_COMMIT, 0);
}
Lng32 ExeCliInterface::rollbackXn()
{
return SQL_EXEC_Xact(SQLTRANS_ROLLBACK, 0);
}
Lng32 ExeCliInterface::statusXn()
{
return SQL_EXEC_Xact(SQLTRANS_STATUS, NULL);
}
Lng32 ExeCliInterface::createContext(char * contextHandle)
{
Lng32 rc = 0;
rc = SQL_EXEC_CreateContext((SQLCTX_HANDLE*)contextHandle, NULL, FALSE);
return rc;
}
Lng32 ExeCliInterface::switchContext(char * contextHandle)
{
Lng32 rc = 0;
rc = SQL_EXEC_SwitchContext(*(SQLCTX_HANDLE*)contextHandle, NULL);
return rc;
}
Lng32 ExeCliInterface::currentContext(char * contextHandle)
{
Lng32 rc = 0;
rc = SQL_EXEC_CurrentContext((SQLCTX_HANDLE*)contextHandle);
return rc;
}
Lng32 ExeCliInterface::deleteContext(char* contextHandle) // in buf contains context handle
{
return SQL_EXEC_DeleteContext(*(SQLCTX_HANDLE*)contextHandle);
}
Lng32 ExeCliInterface::retrieveSQLDiagnostics(ComDiagsArea *toDiags)
{
Lng32 retcode;
ex_assert(toDiags != NULL, "ComDiagsArea is null");
retcode = SQL_EXEC_MergeDiagnostics_Internal(*toDiags);
SQL_EXEC_ClearDiagnostics(NULL);
return retcode;
}
ComDiagsArea *ExeCliInterface::allocAndRetrieveSQLDiagnostics(ComDiagsArea *&toDiags)
{
Lng32 retcode;
NABoolean daAllocated = FALSE;
if (toDiags == NULL) {
toDiags = ComDiagsArea::allocate(heap_);
daAllocated = TRUE;
}
retcode = SQL_EXEC_MergeDiagnostics_Internal(*toDiags);
SQL_EXEC_ClearDiagnostics(NULL);
if (retcode == 0)
return toDiags;
else {
if (daAllocated)
toDiags->decrRefCount();
return NULL;
}
}
Lng32 ExeCliInterface::GetRowsAffected(Int64 *rowsAffected)
{
SQLDESC_ID *rowCountDesc = NULL;
SQLMODULE_ID * module = NULL;
Lng32 retcode = SUCCESS;
NABoolean sqlWarning = FALSE;
SQLDIAG_STMT_INFO_ITEM_ID sqlItem = SQLDIAG_ROW_COUNT;
rowCountDesc = new(heap_) SQLDESC_ID;
rowCountDesc->version = SQLCLI_CURRENT_VERSION;
rowCountDesc->name_mode = desc_handle;
module = new(heap_) SQLMODULE_ID;
rowCountDesc->module = module;
module->module_name = 0;
module->charset = "ISO88591";
module->module_name_len = 0;
module->version = SQLCLI_CURRENT_VERSION;
rowCountDesc->identifier = 0;
rowCountDesc->handle = 0;
// get number of rows affected
retcode = SQL_EXEC_AllocDesc (rowCountDesc, 1);
retcode = SQL_EXEC_SetDescItem(rowCountDesc, 1,
SQLDESC_TYPE_FS, REC_BIN64_SIGNED, 0);
retcode = SQL_EXEC_SetDescItem(rowCountDesc, 1,
SQLDESC_VAR_PTR, (Long)rowsAffected, 0);
Lng32 *temp;
temp = (Lng32 *) &sqlItem;
retcode = SQL_EXEC_GetDiagnosticsStmtInfo(temp, rowCountDesc);
// free up resources
SQL_EXEC_DeallocDesc(rowCountDesc);
return SUCCESS;
} // GetRowsAffected()
Lng32 ExeCliInterface::holdAndSetCQD(const char * defaultName, const char * defaultValue, ComDiagsArea *globalDiags)
{
Lng32 cliRC;
char buf[400];
strcpy(buf, "control query default ");
strcat(buf, defaultName);
strcat(buf, " hold;");
// hold the current value for defaultName
cliRC = executeImmediate(buf, NULL, NULL, TRUE, NULL, 0,&globalDiags);
if (cliRC < 0)
{
return cliRC;
}
// now set the new value for defaultName
strcpy(buf, "control query default ");
strcat(buf, defaultName);
strcat(buf, " '");
strcat(buf, defaultValue);
strcat(buf, "';");
cliRC = executeImmediate(buf, NULL, NULL, TRUE, NULL, 0,&globalDiags);
if (cliRC < 0)
{
return cliRC;
}
return 0;
}
Lng32 ExeCliInterface::restoreCQD(const char * defaultName, ComDiagsArea *globalDiags)
{
Lng32 cliRC;
char buf[400];
// remove this cqd from the cqd array
strcpy(buf, "control query default ");
strcat(buf, defaultName);
strcat(buf, " reset;");
cliRC = executeImmediate(buf, NULL, NULL, TRUE, NULL, 0,&globalDiags);
if (cliRC < 0)
{
return cliRC;
}
// restore the saved cqd default value
strcpy(buf, "control query default ");
strcat(buf, defaultName);
strcat(buf, " restore;");
cliRC = executeImmediate(buf, NULL, NULL, TRUE, NULL, 0,&globalDiags);
if (cliRC < 0)
{
return cliRC;
}
return 0;
}
Lng32 ExeCliInterface::getCQDval(const char * defaultName,
char * val,
ComDiagsArea *globalDiags)
{
Lng32 cliRC;
char buf[400];
strcpy(buf, "cqd showcontrol_show_all 'ON';");
cliRC = executeImmediate(buf);
if (cliRC < 0)
{
return cliRC;
}
char valBuf[4000];
Lng32 valBufLen = 0;
strcpy(buf, "showcontrol default ");
strcat(buf, defaultName);
strcat(buf, ", match full, no header;");
cliRC = executeImmediate(buf, valBuf, &valBufLen);
if (cliRC < 0)
{
strcpy(buf, "cqd showcontrol_show_all 'OFF';");
executeImmediate(buf);
return cliRC;
}
strcpy(val, valBuf);
strcpy(buf, "cqd showcontrol_show_all 'OFF';");
cliRC = executeImmediate(buf);
return 0;
}
Lng32 ExeCliInterface::setCQS(const char * shape, ComDiagsArea *globalDiags)
{
Lng32 cliRC;
cliRC = executeImmediate(shape, NULL, NULL, TRUE, NULL, 0,&globalDiags);
if (cliRC < 0)
{
return cliRC;
}
return 0;
}
Lng32 ExeCliInterface::resetCQS(ComDiagsArea * globalDiags)
{
Lng32 cliRC;
char buf[400];
strcpy(buf, "control query shape cut ");
cliRC = executeImmediate(buf, NULL, NULL, TRUE, NULL, 0,&globalDiags);
if (cliRC < 0)
{
return cliRC;
}
return 0;
}
// methods for routine invocation
Lng32 ExeCliInterface::getRoutine(
/* IN */ const char *serializedInvocationInfo,
/* IN */ Int32 invocationInfoLen,
/* IN */ const char *serializedPlanInfo,
/* IN */ Int32 planInfoLen,
/* IN */ Int32 language,
/* IN */ Int32 paramStyle,
/* IN */ const char *externalName,
/* IN */ const char *containerName,
/* IN */ const char *externalPath,
/* IN */ const char *librarySqlName,
/* OUT */ Int32 *handle,
/* IN/OUT */ ComDiagsArea *diags)
{
Lng32 retcode = 0;
SQL_EXEC_ClearDiagnostics(NULL);
retcode = SQL_EXEC_GetRoutine(
serializedInvocationInfo,
invocationInfoLen,
serializedPlanInfo,
planInfoLen,
language,
paramStyle,
externalName,
containerName,
externalPath,
librarySqlName,
handle);
if (retcode != 0 && diags)
{
SQL_EXEC_MergeDiagnostics_Internal(*diags);
SQL_EXEC_ClearDiagnostics(NULL);
}
return retcode;
}
Lng32 ExeCliInterface::invokeRoutine(
/* IN */ Int32 handle,
/* IN */ Int32 phaseEnumAsInt,
/* IN */ const char *serializedInvocationInfo,
/* IN */ Int32 invocationInfoLen,
/* OUT */ Int32 *invocationInfoLenOut,
/* IN */ const char *serializedPlanInfo,
/* IN */ Int32 planInfoLen,
/* IN */ Int32 planNum,
/* OUT */ Int32 *planInfoLenOut,
/* IN */ char *inputRow,
/* IN */ Int32 inputRowLen,
/* OUT */ char *outputRow,
/* IN */ Int32 outputRowLen,
/* IN/OUT */ ComDiagsArea *diags)
{
Lng32 retcode = 0;
SQL_EXEC_ClearDiagnostics(NULL);
retcode = SQL_EXEC_InvokeRoutine(
handle,
phaseEnumAsInt,
serializedInvocationInfo,
invocationInfoLen,
invocationInfoLenOut,
serializedPlanInfo,
planInfoLen,
planNum,
planInfoLenOut,
inputRow,
inputRowLen,
outputRow,
outputRowLen);
if (retcode != 0 && diags)
{
SQL_EXEC_MergeDiagnostics_Internal(*diags);
SQL_EXEC_ClearDiagnostics(NULL);
}
return retcode;
}
Lng32 ExeCliInterface::getRoutineInvocationInfo(
/* IN */ Int32 handle,
/* IN/OUT */ char *serializedInvocationInfo,
/* IN */ Int32 invocationInfoMaxLen,
/* OUT */ Int32 *invocationInfoLenOut,
/* IN/OUT */ char *serializedPlanInfo,
/* IN */ Int32 planInfoMaxLen,
/* IN */ Int32 planNum,
/* OUT */ Int32 *planInfoLenOut,
/* IN/OUT */ ComDiagsArea *diags)
{
Lng32 retcode = 0;
SQL_EXEC_ClearDiagnostics(NULL);
retcode = SQL_EXEC_GetRoutineInvocationInfo(
handle,
serializedInvocationInfo,
invocationInfoMaxLen,
invocationInfoLenOut,
serializedPlanInfo,
planInfoMaxLen,
planNum,
planInfoLenOut);
if (retcode != 0 && diags)
{
SQL_EXEC_MergeDiagnostics_Internal(*diags);
SQL_EXEC_ClearDiagnostics(NULL);
}
return retcode;
}
Lng32 ExeCliInterface::putRoutine(
/* IN */ Int32 handle,
/* IN/OUT */ ComDiagsArea *diags)
{
Lng32 retcode = 0;
SQL_EXEC_ClearDiagnostics(NULL);
retcode = SQL_EXEC_PutRoutine(
handle);
if (retcode != 0 && diags)
{
SQL_EXEC_MergeDiagnostics_Internal(*diags);
SQL_EXEC_ClearDiagnostics(NULL);
}
return retcode;
}
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <limits.h>
#include <vcl/bmpacc.hxx>
#include <vcl/octree.hxx>
#include <impoct.hxx>
// ---------
// - pMask -
// ---------
static sal_uInt8 pImplMask[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
// -------------
// - NodeCache -
// -------------
ImpNodeCache::ImpNodeCache( const sal_uLong nInitSize ) :
pActNode( NULL )
{
const sal_uLong nSize = nInitSize + 4;
for( sal_uLong i = 0; i < nSize; i++ )
{
OctreeNode* pNewNode = new NODE;
pNewNode->pNextInCache = pActNode;
pActNode = pNewNode;
}
}
// ------------------------------------------------------------------------
ImpNodeCache::~ImpNodeCache()
{
while( pActNode )
{
OctreeNode* pNode = pActNode;
pActNode = pNode->pNextInCache;
delete pNode;
}
}
// ----------
// - Octree -
// ----------
Octree::Octree( sal_uLong nColors ) :
nMax ( nColors ),
nLeafCount ( 0L ),
pTree ( NULL ),
pAcc ( NULL )
{
pNodeCache = new ImpNodeCache( nColors );
memset( pReduce, 0, ( OCTREE_BITS + 1 ) * sizeof( PNODE ) );
}
// ------------------------------------------------------------------------
Octree::Octree( const BitmapReadAccess& rReadAcc, sal_uLong nColors ) :
nMax ( nColors ),
nLeafCount ( 0L ),
pTree ( NULL ),
pAcc ( &rReadAcc )
{
pNodeCache = new ImpNodeCache( nColors );
memset( pReduce, 0, ( OCTREE_BITS + 1 ) * sizeof( PNODE ) );
ImplCreateOctree();
}
// ------------------------------------------------------------------------
Octree::~Octree()
{
ImplDeleteOctree( &pTree );
delete pNodeCache;
}
// ------------------------------------------------------------------------
void Octree::AddColor( const BitmapColor& rColor )
{
pColor = &(BitmapColor&) rColor;
nLevel = 0L;
ImplAdd( &pTree );
while( nLeafCount > nMax )
ImplReduce();
}
// ------------------------------------------------------------------------
void Octree::ImplCreateOctree()
{
if( !!*pAcc )
{
const long nWidth = pAcc->Width();
const long nHeight = pAcc->Height();
if( pAcc->HasPalette() )
{
for( long nY = 0; nY < nHeight; nY++ )
{
for( long nX = 0; nX < nWidth; nX++ )
{
pColor = &(BitmapColor&) pAcc->GetPaletteColor( pAcc->GetPixelIndex( nY, nX ) );
nLevel = 0L;
ImplAdd( &pTree );
while( nLeafCount > nMax )
ImplReduce();
}
}
}
else
{
BitmapColor aColor;
pColor = &aColor;
for( long nY = 0; nY < nHeight; nY++ )
{
for( long nX = 0; nX < nWidth; nX++ )
{
aColor = pAcc->GetPixel( nY, nX );
nLevel = 0L;
ImplAdd( &pTree );
while( nLeafCount > nMax )
ImplReduce();
}
}
}
}
}
// ------------------------------------------------------------------------
void Octree::ImplDeleteOctree( PPNODE ppNode )
{
for ( sal_uLong i = 0UL; i < 8UL; i++ )
{
if ( (*ppNode)->pChild[ i ] )
ImplDeleteOctree( &(*ppNode)->pChild[ i ] );
}
pNodeCache->ImplReleaseNode( *ppNode );
*ppNode = NULL;
}
// ------------------------------------------------------------------------
void Octree::ImplAdd( PPNODE ppNode )
{
// ggf. neuen Knoten erzeugen
if( !*ppNode )
{
*ppNode = pNodeCache->ImplGetFreeNode();
(*ppNode)->bLeaf = ( OCTREE_BITS == nLevel );
if( (*ppNode)->bLeaf )
nLeafCount++;
else
{
(*ppNode)->pNext = pReduce[ nLevel ];
pReduce[ nLevel ] = *ppNode;
}
}
if( (*ppNode)->bLeaf )
{
(*ppNode)->nCount++;
(*ppNode)->nRed += pColor->GetRed();
(*ppNode)->nGreen += pColor->GetGreen();
(*ppNode)->nBlue += pColor->GetBlue();
}
else
{
const sal_uLong nShift = 7 - nLevel;
const sal_uInt8 cMask = pImplMask[ nLevel ];
const sal_uLong nIndex = ( ( ( pColor->GetRed() & cMask ) >> nShift ) << 2 ) |
( ( ( pColor->GetGreen() & cMask ) >> nShift ) << 1 ) |
( ( pColor->GetBlue() & cMask ) >> nShift );
nLevel++;
ImplAdd( &(*ppNode)->pChild[ nIndex ] );
}
}
// ------------------------------------------------------------------------
void Octree::ImplReduce()
{
sal_uLong i;
PNODE pNode;
sal_uLong nRedSum = 0L;
sal_uLong nGreenSum = 0L;
sal_uLong nBlueSum = 0L;
sal_uLong nChilds = 0L;
for ( i = OCTREE_BITS - 1; i && !pReduce[i]; i-- ) {}
pNode = pReduce[ i ];
pReduce[ i ] = pNode->pNext;
for ( i = 0; i < 8; i++ )
{
if ( pNode->pChild[ i ] )
{
PNODE pChild = pNode->pChild[ i ];
nRedSum += pChild->nRed;
nGreenSum += pChild->nGreen;
nBlueSum += pChild->nBlue;
pNode->nCount += pChild->nCount;
pNodeCache->ImplReleaseNode( pNode->pChild[ i ] );
pNode->pChild[ i ] = NULL;
nChilds++;
}
}
pNode->bLeaf = sal_True;
pNode->nRed = nRedSum;
pNode->nGreen = nGreenSum;
pNode->nBlue = nBlueSum;
nLeafCount -= --nChilds;
}
// ------------------------------------------------------------------------
void Octree::CreatePalette( PNODE pNode )
{
if( pNode->bLeaf )
{
pNode->nPalIndex = nPalIndex;
aPal[ nPalIndex++ ] = BitmapColor( (sal_uInt8) ( (double) pNode->nRed / pNode->nCount ),
(sal_uInt8) ( (double) pNode->nGreen / pNode->nCount ),
(sal_uInt8) ( (double) pNode->nBlue / pNode->nCount ) );
}
else for( sal_uLong i = 0UL; i < 8UL; i++ )
if( pNode->pChild[ i ] )
CreatePalette( pNode->pChild[ i ] );
}
// ------------------------------------------------------------------------
void Octree::GetPalIndex( PNODE pNode )
{
if ( pNode->bLeaf )
nPalIndex = pNode->nPalIndex;
else
{
const sal_uLong nShift = 7 - nLevel;
const sal_uInt8 cMask = pImplMask[ nLevel++ ];
const sal_uLong nIndex = ( ( ( pColor->GetRed() & cMask ) >> nShift ) << 2 ) |
( ( ( pColor->GetGreen() & cMask ) >> nShift ) << 1 ) |
( ( pColor->GetBlue() & cMask ) >> nShift );
GetPalIndex( pNode->pChild[ nIndex ] );
}
}
// -------------------
// - InverseColorMap -
// -------------------
InverseColorMap::InverseColorMap( const BitmapPalette& rPal ) :
nBits( 8 - OCTREE_BITS )
{
sal_uLong* cdp;
sal_uInt8* crgbp;
const sal_uLong nColorMax = 1 << OCTREE_BITS;
const sal_uLong xsqr = 1 << ( nBits << 1 );
const sal_uLong xsqr2 = xsqr << 1;
const sal_uLong nColors = rPal.GetEntryCount();
const long x = 1L << nBits;
const long x2 = x >> 1L;
sal_uLong r, g, b;
long rxx, gxx, bxx;
long rdist, gdist, bdist;
long crinc, cginc, cbinc;
ImplCreateBuffers( nColorMax );
for( sal_uLong nIndex = 0; nIndex < nColors; nIndex++ )
{
const BitmapColor& rColor = rPal[ (sal_uInt16) nIndex ];
const sal_uInt8 cRed = rColor.GetRed();
const sal_uInt8 cGreen = rColor.GetGreen();
const sal_uInt8 cBlue = rColor.GetBlue();
rdist = cRed - x2;
gdist = cGreen - x2;
bdist = cBlue - x2;
rdist = rdist*rdist + gdist*gdist + bdist*bdist;
crinc = ( xsqr - ( cRed << nBits ) ) << 1L;
cginc = ( xsqr - ( cGreen << nBits ) ) << 1L;
cbinc = ( xsqr - ( cBlue << nBits ) ) << 1L;
cdp = (sal_uLong*) pBuffer;
crgbp = pMap;
for( r = 0, rxx = crinc; r < nColorMax; rdist += rxx, r++, rxx += xsqr2 )
{
for( g = 0, gdist = rdist, gxx = cginc; g < nColorMax; gdist += gxx, g++, gxx += xsqr2 )
{
for( b = 0, bdist = gdist, bxx = cbinc; b < nColorMax; bdist += bxx, b++, cdp++, crgbp++, bxx += xsqr2 )
if ( !nIndex || ( (long) *cdp ) > bdist )
{
*cdp = bdist;
*crgbp = (sal_uInt8) nIndex;
}
}
}
}
}
// ------------------------------------------------------------------------
InverseColorMap::~InverseColorMap()
{
rtl_freeMemory( pBuffer );
rtl_freeMemory( pMap );
}
// ------------------------------------------------------------------------
void InverseColorMap::ImplCreateBuffers( const sal_uLong nMax )
{
const sal_uLong nCount = nMax * nMax * nMax;
const sal_uLong nSize = nCount * sizeof( sal_uLong );
pMap = (sal_uInt8*) rtl_allocateMemory( nCount );
memset( pMap, 0x00, nCount );
pBuffer = (sal_uInt8*) rtl_allocateMemory( nSize );
memset( pBuffer, 0xff, nSize );
}
|
/*
* Copyright (C) 2018 ifm syntron gmbh
*
* 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 distribted 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.
*/
//
// ex-timetamp.cpp
//
// Request some frames from the camera and write the timestamps to stdout
//
#include <iostream>
#include <memory>
#include <ctime>
#include <iomanip>
#include <ifm3d/camera.h>
#include <ifm3d/fg.h>
#include <ifm3d/image.h>
std::string formatTimestamp(ifm3d::TimePointT timestamp)
{
using namespace std::chrono;
std::time_t time = std::chrono::system_clock::to_time_t(
std::chrono::time_point_cast<std::chrono::system_clock::duration>(
timestamp));
milliseconds milli = duration_cast<milliseconds>(
timestamp.time_since_epoch() - duration_cast<seconds>(
timestamp.time_since_epoch()));
std::ostringstream s;
s << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S")
<< ":" << std::setw(3) << std::setfill('0') << milli.count();
return s.str();
}
int main(int argc, const char **argv)
{
auto cam = ifm3d::Camera::MakeShared();
ifm3d::ImageBuffer::Ptr img = std::make_shared<ifm3d::ImageBuffer>();
ifm3d::FrameGrabber::Ptr fg =
std::make_shared<ifm3d::FrameGrabber>(
cam, ifm3d::IMG_AMP|ifm3d::IMG_CART);
for (int i = 0; i < 10; i++)
{
if (!fg->WaitForFrame(img.get(), 1000))
{
std::cerr << "Error getting frame from camera" << std::endl;
continue;
}
ifm3d::TimePointT timestamp = img->TimeStamp();
std::cout << "Timestamp of frame "
<< std::setw(2) << std::setfill('0')
<< (i+1) << ": " << formatTimestamp(timestamp)
<< std::endl;
}
return 0;
}
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <utility>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#define MAX 10010
#define MOD 1000000007
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
vector<int> adjList[MAX];
int main()
{
int n,m,u,v,k;
deque<int> q;
scanf("%d %d",&n,&m);
vector<int> topo_variant(n+1);
vector<int> indegree(n+1,0);
for(int i=1;i<=m;i++)
{
scanf("%d",&k);
for(int j=0;j<k;j++)
{
scanf("%d",&v);
u = i;
adjList[u].push_back(v);
//u -> v
//this means indegree of v increases by 1
indegree[v] += 1;
}
}
for(int i=1;i<=n;i++)
{
// cout<<indegree[i]<<" ";
if(indegree[i]==0)
q.push_back(i);
}
//cout<<endl;
// sort(q.begin(),q.end());
// for(int i=0;i<q.size();i++)
// cout<<q[i]<<" ";
//cout<<endl;
int parent = 0;
while(!q.empty())
{
v = q.front();
q.pop_front();
topo_variant[v] = parent; //initially v is the main boss
for(int i=0;i<adjList[v].size();i++)
{
indegree[adjList[v][i]] -= 1;
// for(int x=0;x<n;x++)
// cout<<indegree[x]<<" ";
// cout<<endl;
if(indegree[adjList[v][i]] == 0)
q.push_back(adjList[v][i]);
//sort(q.begin(),q.end());
//for(int i=0;i<q.size();i++)
// cout<<q[i]<<" ";
//cout<<endl;
}
parent = v;
}
for(int i=1;i<=n;i++)
cout<<topo_variant[i]<<"\n";
return 0;
}
|
//===- test_cxx_gen.cc ----------------------------------------------------===//
//
// Copyright (C) 2019-2020 Alibaba Group Holding Limited.
//
// 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.
// =============================================================================
// clang-format off
// REQUIRES: odla_tensorrt
// RUN: %cxx %s -DCG_TEST -o %t %flags %include %link
// RUN: %t > %t.gen.cc
// RUN: cat %t.gen.cc | FileCheck %s --check-prefix=GEN
// RUN: %cxx %s -DRUNTIME_TEST -I%odla_path/include -c -o %t.main.o
// RUN: %cxx %t.gen.cc -I%odla_path/include -c -o %t.gen.o
// RUN: %cxx %t.gen.o %t.main.o %odla_link -lodla_tensorrt -o %t.tensort_exe
// RUN: %t.tensort_exe 2>&1| FileCheck %s --check-prefix=EXECUTE
// GEN: include <ODLA/odla.h>
// GEN: extern float const w0[3];
// GEN: extern float const w1[3];
// GEN: static odla_computation Comp;
// GEN: int func(const float input[3], float out_add1[3]) {
// GEN: func_init();
// GEN: odla_BindToArgumentById((const odla_value_id)"input", input, Ctx);
// GEN: odla_BindToOutputById((const odla_value_id)"add1", out_add1, Ctx);
// GEN: odla_ExecuteComputation(Comp, Ctx, ODLA_COMPUTE_INFERENCE, nullptr);
// GEN: }
// EXECUTE: 6.000000
// EXECUTE: 9.000000
// EXECUTE: 12.000000
// clang-format on
#include "test_cxx_gen.in"
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LIBP2P_INCLUDE_LIBP2P_NETWORK_IMPL_DNSADDR_RESOLVER_IMPL_HPP
#define LIBP2P_INCLUDE_LIBP2P_NETWORK_IMPL_DNSADDR_RESOLVER_IMPL_HPP
#include <libp2p/network/dnsaddr_resolver.hpp>
#include <memory>
#include <string>
#include <boost/asio.hpp>
#include <libp2p/network/cares/cares.hpp>
namespace libp2p::network {
class DnsaddrResolverImpl : public DnsaddrResolver {
public:
static constexpr auto kDnsaddr = multi::Protocol::Code::DNS_ADDR;
enum class Error {
INVALID_DNSADDR = 1,
MALFORMED_RESPONSE,
BAD_ADDR_IN_RESPONSE,
};
DnsaddrResolverImpl(std::shared_ptr<boost::asio::io_context> io_context,
const c_ares::Ares &cares);
void load(multi::Multiaddress address, AddressesCallback callback) override;
private:
/// Convert multiaddr "/dnsaddr/hostname" to string "_dnsaddr.hostname"
static outcome::result<std::string> dnsaddrUriFromMultiaddr(
const multi::Multiaddress &address);
std::shared_ptr<boost::asio::io_context> io_context_;
// captured by reference intentionally to force DI use the single instance
const c_ares::Ares &cares_;
};
} // namespace libp2p::network
OUTCOME_HPP_DECLARE_ERROR(libp2p::network, DnsaddrResolverImpl::Error);
#endif // LIBP2P_INCLUDE_LIBP2P_NETWORK_IMPL_DNSADDR_RESOLVER_IMPL_HPP
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2017 The PIVX developers
// Copyright (c) 2016-2017 The RSTR developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/rstr-config.h"
#endif
#include "tinyformat.h"
#include "utiltime.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
using namespace std;
static int64_t nMockTime = 0; //! For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
int64_t GetTimeMillis()
{
return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
.total_milliseconds();
}
int64_t GetTimeMicros()
{
return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
.total_microseconds();
}
void MilliSleep(int64_t n)
{
/**
* Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50
* until fixed in 1.52. Use the deprecated sleep method for the broken case.
* See: https://svn.boost.org/trac/boost/ticket/7238
*/
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
{
// std::locale takes ownership of the pointer
std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
std::stringstream ss;
ss.imbue(loc);
ss << boost::posix_time::from_time_t(nTime);
return ss.str();
}
std::string DurationToDHMS(int64_t nDurationTime)
{
int seconds = nDurationTime % 60;
nDurationTime /= 60;
int minutes = nDurationTime % 60;
nDurationTime /= 60;
int hours = nDurationTime % 24;
int days = nDurationTime / 24;
if (days)
return strprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds);
if (hours)
return strprintf("%02dh:%02dm:%02ds", hours, minutes, seconds);
return strprintf("%02dm:%02ds", minutes, seconds);
}
|
#include <iostream>
#include <stdio.h>
#include<list>
using namespace std;
class Hall{
private:
string name;
int contactNumber;
double costPerDay;
string ownerName;
public:
Hall(){ }
Hall(string name, int contactNumber, double costPerDay, string ownerName){
this->name = name;
this->contactNumber = contactNumber;
this->costPerDay = costPerDay;
this->ownerName = ownerName;
}
list<Hall> getHallDetails(){
list<Hall> hallList;
hallList.push_back(Hall("Chiltington",1798888137,30000,"Robert"));
hallList.push_back(Hall("Kilmersdon",1761436767,22000,"James"));
return hallList;
}
void setName(string name){
this->name=name;
}
string getName(){
return this->name;
}
void setContactNumber(int contactNumber){
this->contactNumber=contactNumber;
}
int getContactNumber(){
return this->contactNumber;
}
void setCostPerDay(double costPerDay){
this->costPerDay=costPerDay;
}
double getCostPerDay(){
return this->costPerDay;
}
void setOwnerName(string ownerName){
this->ownerName=ownerName;
}
string getOwnerName(){
return this->ownerName;
}
};
|
// Copyright (c) 2007-2015 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/// \file new.hpp
#if !defined(HPX_RUNTIME_COMPONENTS_NEW_OCT_10_2012_1256PM)
#define HPX_RUNTIME_COMPONENTS_NEW_OCT_10_2012_1256PM
#include <hpx/hpx_fwd.hpp>
#include <hpx/traits/is_distribution_policy.hpp>
#include <hpx/traits/is_component.hpp>
#include <hpx/runtime/naming/name.hpp>
#include <hpx/runtime/components/stubs/stub_base.hpp>
#include <hpx/runtime/components/default_distribution_policy.hpp>
#include <hpx/lcos/future.hpp>
#include <hpx/util/move.hpp>
#include <type_traits>
#include <vector>
#include <algorithm>
#include <boost/utility/enable_if.hpp>
#if defined(DOXYGEN)
namespace hpx
{
/// \brief Create one or more new instances of the given Component type
/// on the specified locality.
///
/// This function creates one or more new instances of the given Component
/// type on the specified locality and returns a future object for the
/// global address which can be used to reference the new component
/// instance.
///
/// \param locality [in] The global address of the locality where the
/// new instance should be created on.
/// \param vs [in] Any number of arbitrary arguments (passed by
/// value, by const reference or by rvalue reference)
/// which will be forwarded to the constructor of
/// the created component instance.
///
/// \note This function requires to specify an explicit template
/// argument which will define what type of component(s) to
/// create, for instance:
/// \code
/// hpx::future<hpx::id_type> f =
/// hpx::new_<some_component>(hpx::find_here(), ...);
/// hpx::id_type id = f.get();
/// \endcode
///
/// \returns The function returns different types depending on its use:\n
/// * If the explicit template argument \a Component represents a
/// component type (<code>traits::is_component<Component>::value</code>
/// evaluates to true), the function will return an \a hpx::future
/// object instance which can be used to retrieve the global
/// address of the newly created component.
/// * If the explicit template argument \a Component represents a
/// client side object (<code>traits::is_client<Component>::value</code>
/// evaluates to true), the function will return a new instance
/// of that type which can be used to refer to the newly created
/// component instance.
///
template <typename Component, typename ...Ts>
<unspecified>
new_(id_type const& locality, Ts&&... vs);
/// \brief Create multiple new instances of the given Component type on the
/// specified locality.
///
/// This function creates multiple new instances of the given Component type
/// on the specified locality and returns a future object for the
/// global address which can be used to reference the new component
/// instance.
///
/// \param locality [in] The global address of the locality where the
/// new instance should be created on.
/// \param count [in] The number of component instances to create
/// \param vs [in] Any number of arbitrary arguments (passed by
/// value, by const reference or by rvalue reference)
/// which will be forwarded to the constructor of
/// the created component instance.
///
/// \note This function requires to specify an explicit template
/// argument which will define what type of component(s) to
/// create, for instance:
/// \code
/// hpx::future<std::vector<hpx::id_type> > f =
/// hpx::new_<some_component[]>(hpx::find_here(), 10, ...);
/// hpx::id_type id = f.get();
/// \endcode
///
/// \returns The function returns different types depending on its use:\n
/// * If the explicit template argument \a Component
/// represents an array of a component type (i.e. \a Component[],
/// where <code>traits::is_component<Component>::value</code>
/// evaluates to true), the function will return an \a hpx::future
/// object instance which holds a std::vector<hpx::id_type>, where
/// eahc of the items in this vector is a global address of one
/// of the newly created components.
/// * If the explicit template argument \a Component
/// represents an array of a client side object type (i.e. \a Component[],
/// where <code>traits::is_client<Component>::value</code>
/// evaluates to true), the function will return an \a hpx::future
/// object instance which holds a std::vector<hpx::id_type>, where
/// eahc of the items in this vector is a client side instance of
/// the given type, each representing one of the newly created
/// components.
///
template <typename Component, typename ...Ts>
<unspecified>
new_(id_type const& locality, std::size_t count, Ts&&... vs);
/// \brief Create one or more new instances of the given Component type
/// based on the given distribution policy.
///
/// This function creates one or more new instances of the given Component
/// type on the localities defined by the given distribution policy and
/// returns a future object for global address which can be used to reference
/// the new component instance(s).
///
/// \param policy [in] The distribution policy used to decide where to
/// place the newly created.
/// \param vs [in] Any number of arbitrary arguments (passed by
/// value, by const reference or by rvalue reference)
/// which will be forwarded to the constructor of
/// the created component instance.
///
/// \note This function requires to specify an explicit template
/// argument which will define what type of component(s) to
/// create, for instance:
/// \code
/// hpx::future<hpx::id_type> f =
/// hpx::new_<some_component>(hpx::default_layout, ...);
/// hpx::id_type id = f.get();
/// \endcode
///
/// \returns The function returns different types depending on its use:\n
/// * If the explicit template argument \a Component represents a
/// component type (<code>traits::is_component<Component>::value</code>
/// evaluates to true), the function will return an \a hpx::future
/// object instance which can be used to retrieve the global
/// address of the newly created component.
/// * If the explicit template argument \a Component represents a
/// client side object (<code>traits::is_client<Component>::value</code>
/// evaluates to true), the function will return a new instance
/// of that type which can be used to refer to the newly created
/// component instance.
///
template <typename Component, typename DistPolicy, typename ...Ts>
<unspecified>
new_(DistPolicy const& policy, Ts&&... vs);
/// \brief Create multiple new instances of the given Component type on the
/// localities as defined by the given distribution policy.
///
/// This function creates multiple new instances of the given Component type
/// on the localities defined by the given distribution policy and returns
/// a future object for the global address which can be used to reference
/// the new component instance.
///
/// \param policy [in] The distribution policy used to decide where to
/// place the newly created.
/// \param count [in] The number of component instances to create
/// \param vs [in] Any number of arbitrary arguments (passed by
/// value, by const reference or by rvalue reference)
/// which will be forwarded to the constructor of
/// the created component instance.
///
/// \note This function requires to specify an explicit template
/// argument which will define what type of component(s) to
/// create, for instance:
/// \code
/// hpx::future<std::vector<hpx::id_type> > f =
/// hpx::new_<some_component[]>(hpx::default_layout, 10, ...);
/// hpx::id_type id = f.get();
/// \endcode
///
/// \returns The function returns different types depending on its use:\n
/// * If the explicit template argument \a Component
/// represents an array of a component type (i.e. \a Component[],
/// where <code>traits::is_component<Component>::value</code>
/// evaluates to true), the function will return an \a hpx::future
/// object instance which holds a std::vector<hpx::id_type>, where
/// eahc of the items in this vector is a global address of one
/// of the newly created components.\n
/// * If the explicit template argument \a Component
/// represents an array of a client side object type (i.e. \a Component[],
/// where <code>traits::is_client<Component>::value</code>
/// evaluates to true), the function will return an \a hpx::future
/// object instance which holds a std::vector<hpx::id_type>, where
/// eahc of the items in this vector is a client side instance of
/// the given type, each representing one of the newly created
/// components.
///
template <typename Component, typename DistPolicy, typename ...Ts>
<unspecified>
new_(DistPolicy const& policy, std::size_t count, Ts&&... vs);
}
#else
namespace hpx { namespace components
{
///////////////////////////////////////////////////////////////////////////
namespace detail
{
// create a single instance of a component
template <typename Component>
struct new_component
{
typedef hpx::future<hpx::id_type> type;
template <typename ...Ts>
static type call(hpx::id_type const& locality, Ts&&... vs)
{
using components::stub_base;
return stub_base<Component>::create_async(
locality, std::forward<Ts>(vs)...);
}
template <typename DistPolicy, typename ...Ts>
static type call(DistPolicy const& policy, Ts&&... vs)
{
return policy.template create<Component>(std::forward<Ts>(vs)...);
}
};
// create multiple component instances
template <typename Component>
struct new_component<Component[]>
{
typedef hpx::future<std::vector<hpx::id_type> > type;
template <typename ...Ts>
static type call(hpx::id_type const& locality, std::size_t count,
Ts&&... vs)
{
using components::stub_base;
return stub_base<Component>::bulk_create_async(
locality, count, std::forward<Ts>(vs)...);
}
template <typename DistPolicy, typename ...Ts>
static type call(DistPolicy const& policy, std::size_t count,
Ts&&... vs)
{
typedef typename DistPolicy::bulk_locality_result
bulk_locality_result;
hpx::future<std::vector<bulk_locality_result> > f =
policy.template bulk_create<Component>(count,
std::forward<Ts>(vs)...);
return f.then(launch::sync,
[count](hpx::future<std::vector<bulk_locality_result> > && f) -> std::vector<hpx::id_type>
{
std::vector<hpx::id_type> result;
result.reserve(count);
for (bulk_locality_result& r: f.get())
{
std::move(r.second.begin(), r.second.end(),
std::back_inserter(result));
}
return result;
});
}
};
}
///////////////////////////////////////////////////////////////////////////
template <typename Component, typename ...Ts>
inline typename boost::lazy_enable_if_c<
traits::is_component_or_component_array<Component>::value,
detail::new_component<Component>
>::type
new_(id_type const& locality, Ts&&... vs)
{
return detail::new_component<Component>::call(
locality, std::forward<Ts>(vs)...);
}
template <typename Component, typename DistPolicy, typename ...Ts>
inline typename boost::lazy_enable_if_c<
traits::is_component_or_component_array<Component>::value &&
traits::is_distribution_policy<DistPolicy>::value,
detail::new_component<Component>
>::type
new_(DistPolicy const& policy, Ts&&... vs)
{
return detail::new_component<Component>::call(
policy, std::forward<Ts>(vs)...);
}
///////////////////////////////////////////////////////////////////////////
namespace detail
{
// create a single instance of a component
template <typename Client>
struct new_client
{
typedef Client type;
typedef typename Client::server_component_type component_type;
template <typename ...Ts>
static type call(hpx::id_type const& locality, Ts&&... vs)
{
using components::stub_base;
return make_client<Client>(
stub_base<component_type>::create_async(
locality, std::forward<Ts>(vs)...));
}
template <typename DistPolicy, typename ...Ts>
static type call(DistPolicy const& policy, Ts&&... vs)
{
return make_client<Client>(
policy.template create<component_type>(
std::forward<Ts>(vs)...));
}
};
// create multiple client instances
template <typename Client>
struct new_client<Client[]>
{
typedef hpx::future<std::vector<Client> > type;
typedef typename Client::server_component_type component_type;
template <typename ...Ts>
static type call(Ts&&... vs)
{
return new_component<component_type[]>::call(
std::forward<Ts>(vs)...
)
.then(
[](hpx::future<std::vector<hpx::id_type> > && v)
-> std::vector<Client>
{
return make_client<Client>(v.get());
}
);
}
};
}
///////////////////////////////////////////////////////////////////////////
template <typename Client, typename ...Ts>
inline typename boost::lazy_enable_if_c<
traits::is_client_or_client_array<Client>::value,
detail::new_client<Client>
>::type
new_(id_type const& locality, Ts&&... vs)
{
return detail::new_client<Client>::call(
locality, std::forward<Ts>(vs)...);
}
template <typename Client, typename DistPolicy, typename ...Ts>
inline typename boost::lazy_enable_if_c<
traits::is_client_or_client_array<Client>::value &&
traits::is_distribution_policy<DistPolicy>::value,
detail::new_client<Client>
>::type
new_(DistPolicy const& policy, Ts&&... vs)
{
return detail::new_client<Client>::call(
policy, std::forward<Ts>(vs)...);
}
}}
namespace hpx
{
using hpx::components::new_;
}
#endif
#endif // HPX_NEW_OCT_10_2012_1256PM
|
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#pragma warning (disable : 4786)
// TpWrapper.cpp: implementation of the CTpWrapper class.
//
//////////////////////////////////////////////////////////////////////
#include "TpWrapper.hpp"
#include <stdio.h>
#include "workunit.hpp"
#include "exception_util.hpp"
#include "portlist.h"
#include "daqueue.hpp"
#include "dautils.hpp"
#include "dameta.hpp"
#ifdef _CONTAINERIZED
#error "Should not be compiled in the container build"
#endif
const char* MSG_FAILED_GET_ENVIRONMENT_INFO = "Failed to get environment information.";
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
IPropertyTree* CTpWrapper::getEnvironment(const char* xpath)
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root = &constEnv->getPTree();
if (!xpath || !*xpath)
return LINK(root);
IPropertyTree* pSubTree = root->queryPropTree( xpath );
if (pSubTree)
return LINK(pSubTree);
return NULL;
}
void CTpWrapper::getClusterMachineList(double clientVersion,
const char* ClusterType,
const char* ClusterPath,
const char* ClusterDirectory,
IArrayOf<IEspTpMachine> &MachineList,
bool& hasThorSpareProcess,
const char* ClusterName)
{
try
{
StringBuffer returnStr,path;
getAttPath(ClusterPath,path);
set<string> machineNames; //used for checking duplicates
if (strcmp(eqTHORMACHINES,ClusterType) == 0)
{
bool multiSlaves = false;
getMachineList(clientVersion, eqThorMasterProcess, path.str(), "", ClusterDirectory, MachineList);
getThorSlaveMachineList(clientVersion, ClusterName, ClusterDirectory, MachineList);
unsigned count = MachineList.length();
getThorSpareMachineList(clientVersion, ClusterName, ClusterDirectory, MachineList);
//The checkMultiSlavesFlag is for legacy multiSlaves environment, not for new environments.
//count < MachineList.length(): There is some node for eqThorSpareProcess being added to the MachineList.
if (!checkMultiSlavesFlag(ClusterName) &&(count < MachineList.length()))
hasThorSpareProcess = true;
}
else if (strcmp(eqHOLEMACHINES,ClusterType) == 0)
{
getMachineList(clientVersion, eqHoleSocketProcess, path.str(), "", ClusterDirectory, MachineList);
getMachineList(clientVersion, eqHoleProcessorProcess, path.str(), "", ClusterDirectory, MachineList);
getMachineList(clientVersion, eqHoleControlProcess, path.str(), "", ClusterDirectory, MachineList);
getMachineList(clientVersion, eqHoleCollatorProcess, path.str(), "", ClusterDirectory, MachineList);
getMachineList(clientVersion, eqHoleStandbyProcess, path.str(), "", ClusterDirectory, MachineList);
}
else if (strcmp(eqROXIEMACHINES,ClusterType) == 0)
{
getMachineList(clientVersion, "RoxieServerProcess", path.str(), "", ClusterDirectory, MachineList, &machineNames);
}
else if (strcmp(eqMACHINES,ClusterType) == 0)
{
//load a list of available machines.......
getMachineList(clientVersion, "Computer", "/Environment/Hardware", "", ClusterDirectory, MachineList);
}
else if (strcmp("AVAILABLEMACHINES",ClusterType) == 0)
{
getMachineList(clientVersion, "Computer", "/Environment/Hardware", eqMachineAvailablability, ClusterDirectory, MachineList);
}
else if (strcmp("DROPZONE",ClusterType) == 0)
{
getDropZoneMachineList(clientVersion, false, MachineList);
}
else if (strcmp("STANDBYNNODE",ClusterType) == 0)
{
getThorSpareMachineList(clientVersion, ClusterName, ClusterDirectory, MachineList);
getMachineList(clientVersion, eqHoleStandbyProcess, path.str(), "", ClusterDirectory, MachineList);
}
else if (strcmp("THORSPARENODES",ClusterType) == 0)
{
getThorSpareMachineList(clientVersion, ClusterName, ClusterDirectory, MachineList);
}
else if (strcmp("HOLESTANDBYNODES",ClusterType) == 0)
{
getMachineList(clientVersion, eqHoleStandbyProcess, path.str(), "", ClusterDirectory, MachineList);
}
}
catch(IException* e){
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...){
IWARNLOG("Unknown Exception caught within CTpWrapper::getClusterMachineList");
}
}
void CTpWrapper::fetchInstances(const char* ServiceType, IPropertyTree& service,
IArrayOf<IEspTpMachine>& tpMachines)
{
Owned<IPropertyTreeIterator> instances = service.getElements("Instance");
if (instances->first()) {
do {
IPropertyTree& instanceNode = instances->query();
IEspTpMachine* machine = createTpMachine("", "");
getMachineInfo(*machine, instanceNode, "/Environment/Software", ServiceType, "@computer");
machine->setPort( instanceNode.getPropInt("@port") );
const char* directory = instanceNode.queryProp("@directory");
if (directory && *directory)
machine->setDirectory( directory );
tpMachines.append(*machine);
} while (instances->next());
}
}
void CTpWrapper::getTpDaliServers(double clientVersion, IArrayOf<IConstTpDali>& list)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqDali);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpDali> pService = createTpDali("","");
const char* name = serviceTree.queryProp("@name");
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBackupComputer(serviceTree.queryProp("@backupCoputer"));
pService->setBackupDirectory(serviceTree.queryProp("@backupDirectory"));
pService->setBuild(serviceTree.queryProp("@build"));
pService->setType(eqDali);
StringBuffer tmpDir, tmpAuditDir;
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "dali", name, tmpDir))
{
const char* pStr = tmpDir.str();
if (pStr)
{
if (strchr(pStr, '/'))
tmpDir.append("/");
else
tmpDir.append("\\");
tmpAuditDir.set(tmpDir.str());
tmpDir.append("server");
pService->setLogDirectory(tmpDir.str());
if (clientVersion >= 1.27)
{
tmpAuditDir.append("audit");
pService->setAuditLogDirectory(tmpAuditDir.str());
}
}
}
else
{
pService->setLogDirectory(serviceTree.queryProp("@LogDir")); // backward compatible
}
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqDali, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpEclServers(IArrayOf<IConstTpEclServer>& list, const char* serverName)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqEclServer);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpEclServer> pService = createTpEclServer("","");
const char* name = serviceTree.queryProp("@name");
if (serverName && stricmp(name, serverName))
continue;
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "eclserver", name, tmpDir))
{
pService->setLogDirectory( tmpDir.str() );
}
else
{
pService->setLogDirectory(serviceTree.queryProp("@eclLogDir"));
}
pService->setType(eqEclServer);
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqEclServer, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpEclCCServers(IArrayOf<IConstTpEclServer>& list, const char* serverName)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
getTpEclCCServers(root, list, serverName);
return;
}
void CTpWrapper::getTpEclCCServers(IPropertyTree* environmentSoftware, IArrayOf<IConstTpEclServer>& list, const char* serverName)
{
if (!environmentSoftware)
return;
Owned<IPropertyTreeIterator> services= environmentSoftware->getElements(eqEclCCServer);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
const char* name = serviceTree.queryProp("@name");
const char* logDir = serviceTree.queryProp("@logDir");
if (serverName && stricmp(name, serverName))
continue;
Owned<IEspTpEclServer> pService = createTpEclServer("","");
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
StringBuffer tmpDir;
if (getConfigurationDirectory(environmentSoftware->queryPropTree("Directories"), "log", "eclccserver", name, tmpDir))
{
pService->setLogDirectory( tmpDir.str() );
}
else
{
pService->setLogDirectory(logDir);
}
pService->setType(eqEclCCServer);
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqEclCCServer, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpEclAgents(IArrayOf<IConstTpEclAgent>& list, const char* agentName)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqEclAgent);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
const char* name = serviceTree.queryProp("@name");
if (agentName && stricmp(name, agentName))
continue;
const char* daliServers = serviceTree.queryProp("@daliServers");
const char* logDir = serviceTree.queryProp("@logDir");
Owned<IEspTpEclAgent> pService = createTpEclAgent("","");
pService->setDaliServer(daliServers);
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "eclagent", name, tmpDir))
{
pService->setLogDir( tmpDir.str() );
}
else
{
pService->setLogDir(logDir);
}
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
pService->setType(eqEclAgent);
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqEclAgent, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpEclSchedulers(IArrayOf<IConstTpEclScheduler>& list, const char* serverName)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqEclScheduler);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
const char* name = serviceTree.queryProp("@name");
const char* logDir = serviceTree.queryProp("@logDir");
if (serverName && stricmp(name, serverName))
continue;
Owned<IEspTpEclScheduler> pService = createTpEclScheduler("","");
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "eclscheduler", name, tmpDir))
{
pService->setLogDirectory( tmpDir.str() );
}
else
{
pService->setLogDirectory(logDir);
}
pService->setType(eqEclScheduler);
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqEclScheduler, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpEspServers(IArrayOf<IConstTpEspServer>& list)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqEsp);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpEspServer> pService = createTpEspServer("","");
const char* name = serviceTree.queryProp("@name");
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
pService->setType(eqEsp);
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "esp", name, tmpDir))
{
pService->setLogDirectory( tmpDir.str() );
}
else
{
const char* logDir = serviceTree.queryProp("@logDir");
if (logDir && *logDir)
pService->setLogDirectory(logDir);
}
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqEsp, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
Owned<IPropertyTreeIterator> iBinding = serviceTree.getElements("EspBinding");
IArrayOf<IEspTpBinding> tpBindings;
ForEach(*iBinding)
{
IPropertyTree& binding = iBinding->query();
const char* service = binding.queryProp("@service");
if (service && *service)
{
Owned<IEspTpBinding> pTpBinding = createTpBinding("", "");
pTpBinding->setName (binding.queryProp("@name"));
pTpBinding->setService(service);
pTpBinding->setProtocol (binding.queryProp("@protocol"));
pTpBinding->setPort (binding.queryProp("@port"));
StringBuffer xpath;
xpath.appendf("EspService[@name='%s']", service);
IPropertyTree* pServiceNode = root->queryPropTree(xpath.str());
if (pServiceNode)
{
const char* serviceType = pServiceNode->queryProp("Properties/@type");
if (serviceType && *serviceType)
pTpBinding->setServiceType(serviceType);
const char* bindingType = pServiceNode->queryProp("Properties/@bindingType");
if (bindingType && *bindingType)
pTpBinding->setBindingType(bindingType);
const char* buildSet = pServiceNode->queryProp("@buildSet");
if (buildSet && *buildSet)
pTpBinding->setServiceBuildSet(buildSet);
}
tpBindings.append(*pTpBinding.getLink());
}
}
pService->setTpBindings( tpBindings);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpDfuServers(IArrayOf<IConstTpDfuServer>& list)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqDfu);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpDfuServer> pService = createTpDfuServer("","");
const char* name = serviceTree.queryProp("@name");
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
pService->setQueue(serviceTree.queryProp("@queue"));
pService->setType(eqDfu);
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "dfuserver", name, tmpDir))
{
pService->setLogDirectory( tmpDir.str() );
}
else
{
pService->setLogDirectory(serviceTree.queryProp("@dfuLogDir"));
}
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqDfu, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getClear());
}
}
void CTpWrapper::getTpSashaServers(IArrayOf<IConstTpSashaServer>& list)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqSashaServer);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpSashaServer> pService = createTpSashaServer("","");
const char* name = serviceTree.queryProp("@name");
pService->setName(name);
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "sasha", name, tmpDir))
{
pService->setLogDirectory( tmpDir.str() );
}
else
{
pService->setLogDirectory(serviceTree.queryProp("@logDir"));
}
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqSashaServer, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpLdapServers(IArrayOf<IConstTpLdapServer>& list)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqLdapServer);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpLdapServer> pService = createTpLdapServer("","");
pService->setName(serviceTree.queryProp("@name"));
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqLdapServer, serviceTree, tpMachines);
int port = serviceTree.getPropInt("@ldapPort", 0);
if (tpMachines.length() == 0)
{
const char* computer = serviceTree.queryProp("@computer");
if (computer && *computer)
{
Owned<IEspTpMachine> machine = createTpMachine("", "");
setMachineInfo(computer, "LDAPServerProcess", *machine);
StringBuffer tmpPath;
StringBuffer ppath("/Environment/Software");
setAttPath(ppath, "Instance", "name", computer, tmpPath);
machine->setPath(tmpPath.str());
if (port)
machine->setPort( port );
tpMachines.append(*machine.getLink());
}
}
else
{
const int nMachines = tpMachines.length();
for (int i=0; i<nMachines; i++)
tpMachines.item(i).setPort(port);
}
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpFTSlaves(IArrayOf<IConstTpFTSlave>& list)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqFTSlave);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpFTSlave> pService = createTpFTSlave("","");
pService->setName(serviceTree.queryProp("@name"));
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqFTSlave, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTpGenesisServers(IArrayOf<IConstTpGenesisServer>& list)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> services= root->getElements(eqGenesisServer);
ForEach(*services)
{
IPropertyTree& serviceTree = services->query();
Owned<IEspTpGenesisServer> pService = createTpGenesisServer("","");
pService->setName(serviceTree.queryProp("@name"));
pService->setDescription(serviceTree.queryProp("@description"));
pService->setBuild(serviceTree.queryProp("@build"));
IArrayOf<IEspTpMachine> tpMachines;
fetchInstances(eqGenesisServer, serviceTree, tpMachines);
pService->setTpMachines(tpMachines);
list.append(*pService.getLink());
}
}
void CTpWrapper::getTargetClusterList(IArrayOf<IEspTpLogicalCluster>& clusters, const char* clusterType, const char* clusterName)
{
Owned<IPropertyTree> root = getEnvironment("Software");
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IPropertyTreeIterator> clusterIterator = root->getElements("Topology/Cluster");
if (clusterIterator->first())
{
do {
IPropertyTree &cluster0 = clusterIterator->query();
StringBuffer processName;
const char* clusterName0 = cluster0.queryProp("@name");
if (!clusterName0 || !*clusterName0)
continue;
bool bAdd = false;
if (!clusterType || !*clusterType)
{
bAdd = true;
}
else
{
Owned<IPropertyTreeIterator> clusters0= cluster0.getElements(clusterType);
if (clusters0->first())
{
if (!clusterName || !*clusterName)
{
IPropertyTree &cluster = clusters0->query();
const char* name = cluster.queryProp("@process");
if (name && *name)
processName.append(name);
bAdd = true;
}
else
{
do {
IPropertyTree &cluster = clusters0->query();
const char* name = cluster.queryProp("@process");
if (!name||!*name)
continue;
if (!stricmp(name, clusterName))
{
bAdd = true;
break;
}
} while (clusters0->next());
}
}
}
if (!bAdd)
continue;
IEspTpLogicalCluster* pService = createTpLogicalCluster("","");
pService->setName(clusterName0);
if (processName.length() > 0)
pService->setProcess(processName);
pService->setLanguageVersion("3.0.0");
clusters.append(*pService);
} while (clusterIterator->next());
}
}
void CTpWrapper::queryTargetClusterProcess(double version, const char* processName, const char* clusterType, IArrayOf<IConstTpCluster>& clusterList)
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root = &constEnv->getPTree();
StringBuffer xpath;
xpath.appendf("Software/%s[@name='%s']", clusterType, processName);
IPropertyTree* pClusterTree = root->queryPropTree(xpath.str());
if (!pClusterTree)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
const char* queueName = NULL;
if (processName&&(stricmp(clusterType,eqThorCluster)==0))
{
// only for multi-thor
// only list first thor cluster on queue
queueName = pClusterTree->queryProp("@queueName");
if (!queueName||!*queueName)
queueName = processName;
}
IEspTpCluster* clusterInfo = createTpCluster("","");
clusterInfo->setName(processName);
if (queueName && *queueName)
clusterInfo->setQueueName(queueName);
else
clusterInfo->setQueueName(processName);
clusterInfo->setDesc(processName);
clusterInfo->setBuild( pClusterTree->queryProp("@build") );
clusterInfo->setType(clusterType);
StringBuffer tmpPath;
StringBuffer path("/Environment/Software");
setAttPath(path, clusterType, "name", processName, tmpPath);
clusterInfo->setPath(tmpPath.str());
StringBuffer dirStr;
if (!getConfigurationDirectory(root->queryPropTree("Software/Directories"), "run", clusterType, processName, dirStr))
{
dirStr.clear().append(pClusterTree->queryProp("@directory"));
}
clusterInfo->setDirectory(dirStr.str());
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Software/Directories"), "log", clusterType, processName, tmpDir))
{
clusterInfo->setLogDirectory( tmpDir.str() );
}
else
{
const char* logDir = pClusterTree->queryProp("@logDir");
if (logDir)
clusterInfo->setLogDirectory( logDir );
}
clusterInfo->setPrefix("");
if(pClusterTree->hasProp("@dataBuild"))
clusterInfo->setDataModel(pClusterTree->queryProp("@dataBuild"));
clusterList.append(*clusterInfo);
//find out OS
OS_TYPE os = OS_WINDOWS;
unsigned int clusterTypeLen = strlen(clusterType);
const char* childType = NULL;
const char* clusterType0 = NULL;
if (clusterTypeLen > 4)
{
if (!strnicmp(clusterType, "roxie", 4))
{
childType = "RoxieServerProcess[1]";
clusterType0 = eqROXIEMACHINES;
}
else if (!strnicmp(clusterType, "thor", 4))
{
childType = "ThorMasterProcess";
clusterType0 = eqTHORMACHINES;
}
else
{
childType = "HoleControlProcess";
clusterType0 = eqHOLEMACHINES;
}
}
if (childType)
{
IPropertyTree* pChild = pClusterTree->queryPropTree(childType);
if (pChild)
{
const char* computer = pChild->queryProp("@computer");
IPropertyTree* pHardware = root->queryPropTree("Hardware");
if (computer && *computer && pHardware)
{
StringBuffer xpath;
xpath.appendf("Computer[@name='%s']/@computerType", computer);
const char* computerType = pHardware->queryProp( xpath.str() );
if (computerType && *computerType)
{
xpath.clear().appendf("ComputerType[@name='%s']/@opSys", computerType);
const char* opSys = pHardware->queryProp( xpath.str() );
if (!stricmp(opSys, "linux") || !stricmp( opSys, "solaris"))
os = OS_LINUX;
}
}
}
}
clusterInfo->setOS(os);
if (clusterType0 && *clusterType0)
{
bool hasThorSpareProcess = false;
IArrayOf<IEspTpMachine> machineList;
getClusterMachineList(version, clusterType0, tmpPath.str(), dirStr.str(), machineList, hasThorSpareProcess, processName);
if (machineList.length() > 0)
clusterInfo->setTpMachines(machineList);
if (version > 1.14)
clusterInfo->setHasThorSpareProcess(hasThorSpareProcess);
}
return;
}
void CTpWrapper::queryTargetClusters(double version, const char* clusterType, const char* clusterName, IArrayOf<IEspTpTargetCluster>& targetClusterList)
{
try
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root = &constEnv->getPTree();
Owned<IPropertyTreeIterator> clusters= root->getElements("Software/Topology/Cluster");
if (!clusters->first())
return;
do {
IPropertyTree &cluster = clusters->query();
const char* name = cluster.queryProp("@name");
if (!name||!*name)
continue;
if (clusterName && *clusterName && strcmp(clusterName, name))
continue;
const char* prefix = cluster.queryProp("@prefix");
Owned<IPropertyTreeIterator> thorClusters= cluster.getElements(eqThorCluster);
Owned<IPropertyTreeIterator> roxieClusters= cluster.getElements(eqRoxieCluster);
Owned<IPropertyTreeIterator> eclCCServerProcesses= cluster.getElements(eqEclCCServer);
Owned<IPropertyTreeIterator> eclServerProcesses= cluster.getElements(eqEclServer);
Owned<IPropertyTreeIterator> eclSchedulerProcesses= cluster.getElements(eqEclScheduler);
Owned<IPropertyTreeIterator> eclAgentProcesses= cluster.getElements(eqEclAgent);
if (clusterType && !stricmp(clusterType, eqThorCluster) && !thorClusters->first())
continue;
if (clusterType && !stricmp(clusterType, eqRoxieCluster) && !roxieClusters->first())
continue;
if (clusterType && !stricmp(clusterType, eqHoleCluster) && (roxieClusters->first() || thorClusters->first()))
continue;
IEspTpTargetCluster* clusterInfo = createTpTargetCluster("","");
clusterInfo->setName(name);
if (prefix && *prefix)
clusterInfo->setPrefix(prefix);
//Read Cluster process
clusterInfo->setType(eqHoleCluster);
IArrayOf<IConstTpCluster>& clusterList = clusterInfo->getTpClusters();
if (thorClusters->first())
{
clusterInfo->setType(eqThorCluster);
do {
IPropertyTree &thorCluster = thorClusters->query();
const char* process = thorCluster.queryProp("@process");
if (process && *process)
{
queryTargetClusterProcess(version, process, eqThorCluster, clusterList);
}
} while (thorClusters->next());
}
if (roxieClusters->first())
{
clusterInfo->setType(eqRoxieCluster);
do {
IPropertyTree &roxieCluster = roxieClusters->query();
const char* process = roxieCluster.queryProp("@process");
if (process && *process)
{
queryTargetClusterProcess(version, process, eqRoxieCluster, clusterList);
}
} while (roxieClusters->next());
}
//Read eclCCServer process
IArrayOf<IConstTpEclServer>& eclCCServerList = clusterInfo->getTpEclCCServers();
if (eclCCServerProcesses->first())
{
IPropertyTree &eclCCServerProcess = eclCCServerProcesses->query();
const char* process = eclCCServerProcess.queryProp("@process");
if (process && *process)
{
getTpEclCCServers(eclCCServerList, process);
}
}
//Read eclServer process
if ((version >= 1.19) && eclServerProcesses->first())
{
IArrayOf<IConstTpEclServer>& eclServerList = clusterInfo->getTpEclServers();
IPropertyTree &eclServerProcess = eclServerProcesses->query();
const char* process = eclServerProcess.queryProp("@process");
if (process && *process)
{
getTpEclServers(eclServerList, process);
}
}
//Read eclAgent process
IArrayOf<IConstTpEclAgent>& eclAgentList = clusterInfo->getTpEclAgents();
if (eclAgentProcesses->first())
{
IPropertyTree &eclAgentProcess = eclAgentProcesses->query();
const char* process = eclAgentProcess.queryProp("@process");
if (process && *process)
{
getTpEclAgents(eclAgentList, process);
}
}
//Read eclScheduler process
IArrayOf<IConstTpEclScheduler>& eclSchedulerList = clusterInfo->getTpEclSchedulers();
if (eclSchedulerProcesses->first())
{
IPropertyTree &eclSchedulerProcess = eclSchedulerProcesses->query();
const char* process = eclSchedulerProcess.queryProp("@process");
if (process && *process)
{
getTpEclSchedulers(eclSchedulerList, process);
}
}
targetClusterList.append(*clusterInfo);
} while (clusters->next());
}
catch(IException* e){
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...){
IWARNLOG("Unknown Exception caught within CTpWrapper::getClusterList");
}
}
void CTpWrapper::getClusterProcessList(const char* ClusterType, IArrayOf<IEspTpCluster>& clusterList, bool ignoreduplicatqueues, bool ignoreduplicategroups)
{
try
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root = &constEnv->getPTree();
IPropertyTree* pSoftware = root->queryPropTree("Software");
if (!pSoftware)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
StringArray queuesdone;
StringArray groupsdone;
Owned<IPropertyTreeIterator> clusters= pSoftware->getElements(ClusterType);
if (clusters->first()) {
do {
IPropertyTree &cluster = clusters->query();
const char* name = cluster.queryProp("@name");
if (!name||!*name)
continue;
const char* queueName = NULL;
const char* groupName = NULL;
if (name&&(stricmp(ClusterType,eqThorCluster)==0))
{
// only for multi-thor
// only list first thor cluster on queue
queueName = cluster.queryProp("@queueName");
if (!queueName||!*queueName)
queueName = name;
if (ignoreduplicatqueues)
{
bool done=false;
ForEachItemIn(i,queuesdone)
{
if (strcmp(queuesdone.item(i),queueName)==0)
{
done = true;
break;
}
}
if (done)
continue;
queuesdone.append(queueName);
}
groupName = cluster.queryProp("@nodeGroup");
if (!groupName||!*groupName)
groupName = name;
if (ignoreduplicategroups)
{
bool done=false;
ForEachItemIn(i,groupsdone)
{
if (strcmp(groupsdone.item(i),groupName)==0)
{
done = true;
break;
}
}
if (done)
continue;
groupsdone.append(groupName);
}
}
IEspTpCluster* clusterInfo = createTpCluster("","");
clusterInfo->setName(name);
if (queueName && *queueName)
clusterInfo->setQueueName(queueName);
else
clusterInfo->setQueueName(name);
clusterInfo->setDesc(name);
clusterInfo->setBuild( cluster.queryProp("@build") );
StringBuffer path("/Environment/Software");
StringBuffer tmpPath;
setAttPath(path, ClusterType, "name", name, tmpPath);
clusterInfo->setType(ClusterType);
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Software/Directories"), "run", ClusterType, name, tmpDir))
{
clusterInfo->setDirectory(tmpDir.str());
}
else
{
clusterInfo->setDirectory(cluster.queryProp("@directory"));
}
tmpDir.clear();
if (getConfigurationDirectory(root->queryPropTree("Software/Directories"), "log", ClusterType, name, tmpDir))
{
clusterInfo->setLogDirectory( tmpDir.str() );
}
else
{
const char* logDir = cluster.queryProp("@logDir");
if (logDir)
clusterInfo->setLogDirectory( logDir );
}
clusterInfo->setPath(tmpPath.str());
clusterInfo->setPrefix("");
if(cluster.hasProp("@dataBuild"))
clusterInfo->setDataModel(cluster.queryProp("@dataBuild"));
clusterList.append(*clusterInfo);
//find out OS
OS_TYPE os = OS_WINDOWS;
unsigned int clusterTypeLen = strlen(ClusterType);
const char* childType = NULL;
if (clusterTypeLen > 4)
{
if (!strnicmp(ClusterType, "roxie", 4))
childType = "RoxieServerProcess[1]";
else if (!strnicmp(ClusterType, "thor", 4))
childType = "ThorMasterProcess";
else
childType = "HoleControlProcess";
}
if (childType)
{
IPropertyTree* pChild = cluster.queryPropTree(childType);
if (pChild)
{
const char* computer = pChild->queryProp("@computer");
IPropertyTree* pHardware = root->queryPropTree("Hardware");
if (computer && *computer && pHardware)
{
StringBuffer xpath;
xpath.appendf("Computer[@name='%s']/@computerType", computer);
const char* computerType = pHardware->queryProp( xpath.str() );
if (computerType && *computerType)
{
xpath.clear().appendf("ComputerType[@name='%s']/@opSys", computerType);
const char* opSys = pHardware->queryProp( xpath.str() );
if (!stricmp(opSys, "linux") || !stricmp( opSys, "solaris"))
os = OS_LINUX;
}
}
}
}
clusterInfo->setOS(os);
} while (clusters->next());
}
}
catch(IException* e){
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...){
IWARNLOG("Unknown Exception caught within CTpWrapper::getClusterList");
}
}
void CTpWrapper::getHthorClusterList(IArrayOf<IEspTpCluster>& clusterList)
{
try
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root = &constEnv->getPTree();
IPropertyTree* pSoftware = root->queryPropTree("Software");
const char * ClusterType = "EclAgentProcess";
Owned<IPropertyTreeIterator> clusters(pSoftware->getElements(ClusterType));
ForEach(*clusters)
{
IPropertyTree &cluster = clusters->query();
const char* name = cluster.queryProp("@name");
if (!name||!*name)
continue;
unsigned ins = 0;
Owned<IPropertyTreeIterator> insts = clusters->query().getElements("Instance");
ForEach(*insts)
{
const char *na = insts->query().queryProp("@netAddress");
if (na&&*na)
{
SocketEndpoint ep(na);
if (!ep.isNull())
{
ins++;
StringBuffer gname("hthor__");
gname.append(name);
if (ins>1)
gname.append('_').append(ins);
IEspTpCluster* clusterInfo = createTpCluster("","");
clusterInfo->setName(gname.str());
clusterInfo->setQueueName(name);
clusterInfo->setDesc(cluster.queryProp("@build"));
clusterInfo->setBuild( cluster.queryProp("@description") );
StringBuffer path("/Environment/Software");
StringBuffer tmpPath;
setAttPath(path, ClusterType, "name", name, tmpPath);
clusterInfo->setType(ClusterType);
clusterInfo->setDirectory(insts->query().queryProp("@directory"));
StringBuffer tmpDir;
if (getConfigurationDirectory(root->queryPropTree("Software/Directories"), "run", ClusterType, name, tmpDir))
{
clusterInfo->setDirectory(tmpDir.str());
}
else
{
clusterInfo->setDirectory(insts->query().queryProp("@directory"));
}
clusterInfo->setPath(tmpPath.str());
clusterList.append(*clusterInfo);
//find out OS
OS_TYPE os = OS_WINDOWS;
const char* computer = insts->query().queryProp("@computer");
IPropertyTree* pHardware = root->queryPropTree("Hardware");
if (computer && *computer && pHardware)
{
StringBuffer xpath;
xpath.appendf("Computer[@name='%s']/@computerType", computer);
const char* computerType = pHardware->queryProp( xpath.str() );
if (computerType && *computerType)
{
xpath.clear().appendf("ComputerType[@name='%s']/@opSys", computerType);
const char* opSys = pHardware->queryProp( xpath.str() );
if (!stricmp(opSys, "linux") || !stricmp( opSys, "solaris"))
os = OS_LINUX;
}
}
clusterInfo->setOS(os);
}
}
}
}
}
catch(IException* e){
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...){
IWARNLOG("Unknown Exception caught within CTpWrapper::getHthorClusterList");
}
}
void CTpWrapper::getGroupList(double espVersion, const char* kindReq, IArrayOf<IEspTpGroup> &GroupList)
{
try
{
Owned<IRemoteConnection> conn = querySDS().connect("/Groups", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
Owned<IPropertyTreeIterator> groups= conn->queryRoot()->getElements("Group");
if (groups->first())
{
do
{
IPropertyTree &group = groups->query();
const char* kind = group.queryProp("@kind");
if (kindReq && *kindReq && !strieq(kindReq, kind))
continue;
IEspTpGroup* pGroup = createTpGroup("","");
const char* name = group.queryProp("@name");
pGroup->setName(name);
if (kind && *kind && (espVersion >= 1.21))
{
pGroup->setKind(kind);
pGroup->setReplicateOutputs(checkGroupReplicateOutputs(name, kind));
}
GroupList.append(*pGroup);
} while (groups->next());
}
}
catch(IException* e)
{
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...)
{
IWARNLOG("Unknown Exception caught within CTpWrapper::getGroupList");
}
}
bool CTpWrapper::checkGroupReplicateOutputs(const char* groupName, const char* kind)
{
if (strieq(kind, "Roxie") || strieq(kind, "hthor"))
return false;
Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
Owned<IConstEnvironment> environment = factory->openEnvironment();
Owned<IPropertyTree> root = &environment->getPTree();
Owned<IPropertyTreeIterator> it= root->getElements("Software/ThorCluster");
ForEach(*it)
{
StringBuffer thorClusterGroupName;
IPropertyTree& cluster = it->query();
getClusterGroupName(cluster, thorClusterGroupName);
if (thorClusterGroupName.length() && strieq(thorClusterGroupName.str(), groupName))
return cluster.getPropBool("@replicateOutputs", false);
}
return false;
}
void CTpWrapper::getMachineInfo(double clientVersion, const char* name, const char* netAddress, IEspTpMachine& machineInfo)
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IConstMachineInfo> pMachineInfo;
if (name && *name)
pMachineInfo.setown(constEnv->getMachine(name));
else if (netAddress && *netAddress)
pMachineInfo.setown(constEnv->getMachineByAddress(netAddress));
else
throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Machine not specified");
if (!pMachineInfo)
throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Machine Not Found for %s '%s'",
(name && *name)? "Name" : "Net Address", (name && *name)? name : netAddress);
setTpMachine(pMachineInfo, machineInfo);
}
void CTpWrapper::setTpMachine(IConstMachineInfo* machine, IEspTpMachine& tpMachine)
{
if (!machine)
return;
SCMStringBuffer machineName, netAddress;
machine->getName(machineName);
machine->getNetAddress(netAddress);
tpMachine.setName(machineName.str());
tpMachine.setNetaddress(netAddress.str());
tpMachine.setOS(machine->getOS());
switch(machine->getState())
{
case MachineStateAvailable:
tpMachine.setAvailable("Available");
break;
case MachineStateUnavailable:
tpMachine.setAvailable("Unavailable");
break;
case MachineStateUnknown:
tpMachine.setAvailable("Unknown");
break;
}
Owned<IConstDomainInfo> pDomain = machine->getDomain();
if (pDomain != 0)
{
SCMStringBuffer sName;
tpMachine.setDomain(pDomain->getName(sName).str());
}
}
void CTpWrapper::getMachineInfo(IEspTpMachine& machineInfo,IPropertyTree& machine,const char* ParentPath,const char* MachineType,const char* nodenametag)
{
const char* name = machine.queryProp(nodenametag);
setMachineInfo(name,MachineType,machineInfo);
StringBuffer tmpPath;
StringBuffer ppath(ParentPath);
setAttPath(ppath,machine.queryName(),"name",name,tmpPath);
machineInfo.setPath(tmpPath.str());
}
bool CTpWrapper::checkMultiSlavesFlag(const char* clusterName)
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root = &constEnv->getPTree();
VStringBuffer path("Software/ThorCluster[@name=\"%s\"]", clusterName);
Owned<IPropertyTree> cluster= root->getPropTree(path.str());
if (!cluster)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
//set this flag for legacy multi slave clusters because SwapNode made little sense in the old scheme
//This is no longer an option in new environments, but is kept for backward compatibility with old
//multi slave environments that used to list multiple slaves per node manually.
return cluster->getPropBool("@multiSlaves");
}
void CTpWrapper::appendThorMachineList(double clientVersion, IConstEnvironment* constEnv, INode& node, const char* clusterName,
const char* machineType, unsigned& processNumber, unsigned channels, const char* directory, IArrayOf<IEspTpMachine>& machineList)
{
StringBuffer netAddress;
node.endpoint().getIpText(netAddress);
if (netAddress.length() == 0)
{
OWARNLOG("Net address not found for a node of %s", clusterName);
return;
}
processNumber++;
Owned<IEspTpMachine> machineInfo = createTpMachine("","");
machineInfo->setType(machineType);
machineInfo->setNetaddress(netAddress.str());
if (!isEmptyString(directory))
machineInfo->setDirectory(directory);
Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachineByAddress(netAddress.str());
if (pMachineInfo.get())
{
setTpMachine(pMachineInfo, *machineInfo);
if (clientVersion > 1.17)
{
machineInfo->setProcessNumber(processNumber);
}
}
else
{
machineInfo->setName("external");
machineInfo->setOS(MachineOsUnknown);
}
if (clientVersion >= 1.30)
machineInfo->setChannels(channels);
machineList.append(*machineInfo.getLink());
}
void CTpWrapper::getThorSlaveMachineList(double clientVersion, const char* clusterName, const char* directory, IArrayOf<IEspTpMachine>& machineList)
{
try
{
getThorMachineList(clientVersion, clusterName, directory, true, machineList);
}
catch(IException* e)
{
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...)
{
IWARNLOG("Unknown Exception caught within CTpWrapper::getMachineList");
}
return;
}
void CTpWrapper::getThorSpareMachineList(double clientVersion, const char* clusterName, const char* directory, IArrayOf<IEspTpMachine>& machineList)
{
try
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
getThorMachineList(clientVersion, clusterName, directory, false, machineList);
}
catch(IException* e)
{
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...)
{
IWARNLOG("Unknown Exception caught within CTpWrapper::getMachineList");
}
return;
}
void CTpWrapper::getThorMachineList(double clientVersion, const char* clusterName, const char* directory,
bool slaveNode, IArrayOf<IEspTpMachine>& machineList)
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root = &constEnv->getPTree();
VStringBuffer path("Software/%s[@name=\"%s\"]", eqThorCluster, clusterName);
Owned<IPropertyTree> cluster= root->getPropTree(path.str());
if (!cluster)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
Owned<IGroup> nodeGroup;
if (slaveNode)
{
nodeGroup.setown(getClusterProcessNodeGroup(clusterName, eqThorCluster));
}
else
{
StringBuffer groupName;
getClusterSpareGroupName(*cluster, groupName);
if (groupName.length() < 1)
return;
nodeGroup.setown(queryNamedGroupStore().lookup(groupName.str()));
}
if (!nodeGroup || (nodeGroup->ordinality() == 0))
return;
unsigned processNumber = 0;
unsigned channels = cluster->getPropInt("@channelsPerSlave", 1);
Owned<INodeIterator> gi = nodeGroup->getIterator();
ForEach(*gi)
appendThorMachineList(clientVersion, constEnv, gi->query(), clusterName,
slaveNode? eqThorSlaveProcess : eqThorSpareProcess, processNumber, channels, directory, machineList);
}
void CTpWrapper::getMachineList(double clientVersion, const char* MachineType, const char* ParentPath,
const char* Status, const char* Directory, IArrayOf<IEspTpMachine>& MachineList, set<string>* pMachineNames/*=NULL*/)
{
try
{
//ParentPath=Path to parent node... normally a cluster
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
Owned<IPropertyTree> root0 = &constEnv->getPTree();
char* xpath = (char*)ParentPath;
if (!strnicmp(xpath, "/Environment/", 13))
xpath += 13;
IPropertyTree* root = root0->queryPropTree( xpath );
if (!root)
throw MakeStringExceptionDirect(ECLWATCH_CANNOT_GET_ENV_INFO, MSG_FAILED_GET_ENVIRONMENT_INFO);
bool hasPropChannelsPerNode = root->hasProp("@channelsPerNode");
int channels = root->getPropInt("@channelsPerNode");
Owned<IPropertyTreeIterator> machines= root->getElements(MachineType);
const char* nodenametag = getNodeNameTag(MachineType);
if (machines->first()) {
do {
IPropertyTree &machine = machines->query();
if (pMachineNames)//caller wishes us to avoid inserting duplicate entries for machines
{
const char* machineName = machine.queryProp(nodenametag);
if (pMachineNames->find(machineName) != pMachineNames->end())
continue;
pMachineNames->insert(machineName);
}
//load up the machines of which we do not care what status is set or we have a matching status
const char* state = machine.queryProp("@state");
if ((Status==NULL || *Status=='\0') ||
(state && strcmp(Status, state)==0))
{
IEspTpMachine & machineInfo = *(createTpMachine("",""));
getMachineInfo(machineInfo,machine,ParentPath,MachineType,nodenametag);
if (Directory && *Directory)
machineInfo.setDirectory(Directory);
if (hasPropChannelsPerNode && (clientVersion >= 1.30))
machineInfo.setChannels(channels);
MachineList.append(machineInfo);
}
} while (machines->next());
}
}
catch(IException* e){
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...){
IWARNLOG("Unknown Exception caught within CTpWrapper::getMachineList");
}
}
const char* CTpWrapper::getNodeNameTag(const char* MachineType)
{
if (strcmp(MachineType,"Computer")==0)
return "@name";
else
return "@computer";
}
void CTpWrapper::getDropZoneMachineList(double clientVersion, bool ECLWatchVisibleOnly, IArrayOf<IEspTpMachine> &MachineList)
{
try
{
IArrayOf<IConstTpDropZone> list;
getTpDropZones(clientVersion, nullptr, ECLWatchVisibleOnly, list);
ForEachItemIn(i, list)
{
IConstTpDropZone& dropZone = list.item(i);
IArrayOf<IConstTpMachine>& tpMachines = dropZone.getTpMachines();
ForEachItemIn(ii, tpMachines)
{
IConstTpMachine& tpMachine = tpMachines.item(ii);
Owned<IEspTpMachine> machine = createTpMachine();
machine->copy(tpMachine);
MachineList.append(*machine.getLink());
}
}
}
catch(IException* e)
{
EXCLOG(e);
e->Release();
}
catch(...)
{
IWARNLOG("Unknown Exception caught within CTpWrapper::getDropZoneMachineList");
}
}
//For a given dropzone or every dropzones (check ECLWatchVisible if needed), read: "@name",
// "@description", "@build", "@directory", "@ECLWatchVisible" into an IEspTpDropZone object.
//For each ServerList, read "@name" and "@server" (hostname or IP) into an IEspTpMachine object.
//Add the IEspTpMachine object into the IEspTpDropZone.
void CTpWrapper::getTpDropZones(double clientVersion, const char* name, bool ECLWatchVisibleOnly, IArrayOf<IConstTpDropZone>& list)
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
if (!isEmptyString(name))
{
Owned<IConstDropZoneInfo> pDropZoneInfo = constEnv->getDropZone(name);
if (pDropZoneInfo && (!ECLWatchVisibleOnly || pDropZoneInfo->isECLWatchVisible()))
appendTpDropZone(clientVersion, constEnv, *pDropZoneInfo, list);
}
else
{
Owned<IConstDropZoneInfoIterator> it = constEnv->getDropZoneIterator();
ForEach(*it)
{
IConstDropZoneInfo& dropZoneInfo = it->query();
if (!ECLWatchVisibleOnly || dropZoneInfo.isECLWatchVisible())
appendTpDropZone(clientVersion, constEnv, dropZoneInfo, list);
}
}
}
void CTpWrapper::appendTpDropZone(double clientVersion, IConstEnvironment* constEnv, IConstDropZoneInfo& dropZoneInfo, IArrayOf<IConstTpDropZone>& list)
{
SCMStringBuffer dropZoneName, description, directory, umask, build, computer;
dropZoneInfo.getName(dropZoneName);
dropZoneInfo.getDescription(description);
dropZoneInfo.getDirectory(directory);
dropZoneInfo.getUMask(umask);
dropZoneInfo.getComputerName(computer);
Owned<IEspTpDropZone> dropZone = createTpDropZone();
if (dropZoneName.length() > 0)
dropZone->setName(dropZoneName.str());
if (description.length() > 0)
dropZone->setDescription(description.str());
if (directory.length() > 0)
dropZone->setPath(directory.str());
if (build.length() > 0)
dropZone->setBuild(build.str());
dropZone->setECLWatchVisible(dropZoneInfo.isECLWatchVisible());
IArrayOf<IEspTpMachine> tpMachines;
Owned<IConstDropZoneServerInfoIterator> itr = dropZoneInfo.getServers();
ForEach(*itr)
{
IConstDropZoneServerInfo& dropZoneServer = itr->query();
StringBuffer name, server, networkAddress;
dropZoneServer.getName(name);
dropZoneServer.getServer(server);
if (name.isEmpty() && server.isEmpty())
continue;
Owned<IEspTpMachine> machine = createTpMachine();
if (!name.isEmpty())
machine->setName(name.str());
if (!server.isEmpty())
{
IpAddress ipAddr;
ipAddr.ipset(server.str());
ipAddr.getIpText(networkAddress);
machine->setNetaddress(networkAddress.str());
machine->setConfigNetaddress(server.str());
}
if (directory.length() > 0)
{
machine->setDirectory(directory.str());
machine->setOS(getPathSepChar(directory.str()) == '/' ? MachineOsLinux : MachineOsW2K);
}
tpMachines.append(*machine.getLink());
}
dropZone->setTpMachines(tpMachines);
list.append(*dropZone.getLink());
}
void CTpWrapper::getTpSparkThors(double clientVersion, const char* name, IArrayOf<IConstTpSparkThor>& list)
{
Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
if (!isEmptyString(name))
{
Owned<IConstSparkThorInfo> sparkThorInfo = constEnv->getSparkThor(name);
if (sparkThorInfo)
appendTpSparkThor(clientVersion, constEnv, *sparkThorInfo, list);
}
else
{
Owned<IConstSparkThorInfoIterator> it = constEnv->getSparkThorIterator();
ForEach(*it)
appendTpSparkThor(clientVersion, constEnv, it->query(), list);
}
}
void CTpWrapper::appendTpSparkThor(double clientVersion, IConstEnvironment* constEnv, IConstSparkThorInfo& sparkThorInfo, IArrayOf<IConstTpSparkThor>& list)
{
SCMStringBuffer name, build, thorClusterName;
sparkThorInfo.getName(name);
sparkThorInfo.getBuild(build);
sparkThorInfo.getThorClusterName(thorClusterName);
Owned<IEspTpSparkThor> sparkThor = createTpSparkThor();
if (name.length() > 0)
sparkThor->setName(name.str());
if (build.length() > 0)
sparkThor->setBuild(build.str());
if (thorClusterName.length() > 0)
sparkThor->setThorClusterName(thorClusterName.str());
sparkThor->setSparkExecutorCores(sparkThorInfo.getSparkExecutorCores());
sparkThor->setSparkExecutorMemory(sparkThorInfo.getSparkExecutorMemory());
sparkThor->setSparkMasterPort(sparkThorInfo.getSparkMasterPort());
sparkThor->setSparkMasterWebUIPort(sparkThorInfo.getSparkMasterWebUIPort());
sparkThor->setSparkWorkerCores(sparkThorInfo.getSparkWorkerCores());
sparkThor->setSparkWorkerMemory(sparkThorInfo.getSparkWorkerMemory());
sparkThor->setSparkWorkerPort(sparkThorInfo.getSparkWorkerPort());
//Create the Path used by the thor cluster.
StringBuffer tmpPath;
StringBuffer path("/Environment/Software");
setAttPath(path, eqThorCluster, "name", thorClusterName.str(), tmpPath);
sparkThor->setThorPath(tmpPath.str());
StringBuffer dirBuf;
Owned<IPropertyTree> root = &constEnv->getPTree();
if (getConfigurationDirectory(root->queryPropTree("Directories"), "log", "sparkthor", name.str(), dirBuf))
sparkThor->setLogDirectory(dirBuf.str());
IArrayOf<IConstTpMachine> machines;
Owned<IConstInstanceInfoIterator> instanceInfoItr = sparkThorInfo.getInstanceIterator();
ForEach(*instanceInfoItr)
appendTpMachine(clientVersion, constEnv, instanceInfoItr->query(), machines);
sparkThor->setTpMachines(machines);
list.append(*sparkThor.getLink());
}
void CTpWrapper::appendTpMachine(double clientVersion, IConstEnvironment* constEnv, IConstInstanceInfo& instanceInfo, IArrayOf<IConstTpMachine>& machines)
{
SCMStringBuffer name, networkAddress, description, directory;
Owned<IConstMachineInfo> machineInfo = instanceInfo.getMachine();
machineInfo->getName(name);
machineInfo->getNetAddress(networkAddress);
instanceInfo.getDirectory(directory);
Owned<IEspTpMachine> machine = createTpMachine();
machine->setName(name.str());
if (networkAddress.length() > 0)
{
IpAddress ipAddr;
ipAddr.ipset(networkAddress.str());
StringBuffer networkAddressStr;
ipAddr.getIpText(networkAddressStr);
machine->setNetaddress(networkAddressStr);
}
machine->setPort(instanceInfo.getPort());
machine->setOS(machineInfo->getOS());
machine->setDirectory(directory.str());
machine->setType(eqSparkThorProcess);
machines.append(*machine.getLink());
}
IEspTpMachine* CTpWrapper::createTpMachineEx(const char* name, const char* type, IConstMachineInfo* machineInfo)
{
if (!machineInfo)
return nullptr;
Owned<IEspTpMachine> machine = createTpMachine();
machine->setName(name);
machine->setType(type);
machine->setOS(machineInfo->getOS());
Owned<IConstDomainInfo> domain = machineInfo->getDomain();
if (domain)
{
SCMStringBuffer sName;
machine->setDomain(domain->getName(sName).str());
}
SCMStringBuffer netAddr;
machineInfo->getNetAddress(netAddr);
if (netAddr.length() > 0)
{
StringBuffer networkAddress;
IpAddress ipAddr;
ipAddr.ipset(netAddr.str());
ipAddr.getIpText(networkAddress);
machine->setNetaddress(networkAddress.str());
}
switch(machineInfo->getState())
{
case MachineStateAvailable:
machine->setAvailable("Available");
break;
case MachineStateUnavailable:
machine->setAvailable("Unavailable");
break;
default:
machine->setAvailable("Unknown");
break;
}
return machine.getClear();
}
void CTpWrapper::setMachineInfo(const char* name,const char* type,IEspTpMachine& machine)
{
try{
Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
Owned<IConstEnvironment> constEnv = factory->openEnvironment();
Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachine(name);
if (pMachineInfo.get())
{
SCMStringBuffer ep;
pMachineInfo->getNetAddress(ep);
const char* ip = ep.str();
if (!ip || stricmp(ip, "."))
{
machine.setNetaddress(ep.str());
machine.setConfigNetaddress(ep.str());
}
else
{
StringBuffer ipStr;
IpAddress ipaddr = queryHostIP();
ipaddr.getIpText(ipStr);
if (ipStr.length() > 0)
{
#ifdef MACHINE_IP
machine.setNetaddress(MACHINE_IP);
#else
machine.setNetaddress(ipStr.str());
#endif
machine.setConfigNetaddress(".");
}
}
machine.setOS(pMachineInfo->getOS());
switch(pMachineInfo->getState())
{
case MachineStateAvailable:
machine.setAvailable("Available");
break;
case MachineStateUnavailable:
machine.setAvailable("Unavailable");
break;
case MachineStateUnknown:
machine.setAvailable("Unknown");
break;
}
Owned<IConstDomainInfo> pDomain = pMachineInfo->getDomain();
if (pDomain != 0)
{
SCMStringBuffer sName;
machine.setDomain(pDomain->getName(sName).str());
}
}
machine.setName(name);
machine.setType(type);
}
catch(IException* e){
StringBuffer msg;
e->errorMessage(msg);
IWARNLOG("%s", msg.str());
e->Release();
}
catch(...){
IWARNLOG("Unknown Exception caught within CTpWrapper::getDropZoneList");
}
}
void CTpWrapper::setAttPath(StringBuffer& Path,const char* PathToAppend,const char* AttName,const char* AttValue,StringBuffer& returnStr)
{
Path.append("/");
Path.append(PathToAppend);
Path.append("[@");
Path.append(AttName);
Path.append("=\"");
Path.append(AttValue);
Path.append("\"]");
StringBuffer rawPath;
const void* buff = (void*)Path.str();
JBASE64_Encode(buff,Path.length(),rawPath, false);
returnStr.append(rawPath.str());
}
void CTpWrapper::getAttPath(const char* Path,StringBuffer& returnStr)
{
StringBuffer decodedStr;
JBASE64_Decode(Path, returnStr);
}
void CTpWrapper::getServices(double version, const char* serviceType, const char* serviceName, IArrayOf<IConstHPCCService>& services)
{
Owned<IPropertyTreeIterator> itr = getGlobalConfigSP()->getElements("services");
ForEach(*itr)
{
IPropertyTree& service = itr->query();
//Only show the public services for now
if (!service.getPropBool("@public"))
continue;
const char* type = service.queryProp("@type");
if (isEmptyString(type) || (!isEmptyString(serviceType) && !strieq(serviceType, type)))
continue;
const char* name = service.queryProp("@name");
if (isEmptyString(name) || (!isEmptyString(serviceName) && !strieq(serviceName, name)))
continue;
Owned<IEspHPCCService> svc = createHPCCService();
svc->setName(name);
svc->setType(type);
svc->setPort(service.getPropInt("@port"));
if (service.getPropBool("@tls"))
svc->setTLSSecure(true);
services.append(*svc.getLink());
if (!isEmptyString(serviceName))
break;
}
}
class CContainerWUClusterInfo : public CSimpleInterfaceOf<IConstWUClusterInfo>
{
StringAttr name;
StringAttr serverQueue;
StringAttr agentQueue;
StringAttr thorQueue;
ClusterType platform;
unsigned clusterWidth;
StringArray thorProcesses;
public:
CContainerWUClusterInfo(const char* _name, const char* type, unsigned _clusterWidth)
: name(_name), clusterWidth(_clusterWidth)
{
StringBuffer queue;
if (strieq(type, "thor"))
{
thorQueue.set(getClusterThorQueueName(queue.clear(), name));
platform = ThorLCRCluster;
thorProcesses.append(name);
}
else if (strieq(type, "roxie"))
{
agentQueue.set(getClusterEclAgentQueueName(queue.clear(), name));
platform = RoxieCluster;
}
else
{
agentQueue.set(getClusterEclAgentQueueName(queue.clear(), name));
platform = HThorCluster;
}
serverQueue.set(getClusterEclCCServerQueueName(queue.clear(), name));
}
virtual IStringVal& getName(IStringVal& str) const override
{
str.set(name.get());
return str;
}
virtual IStringVal& getAgentQueue(IStringVal& str) const override
{
str.set(agentQueue);
return str;
}
virtual IStringVal& getServerQueue(IStringVal& str) const override
{
str.set(serverQueue);
return str;
}
virtual IStringVal& getThorQueue(IStringVal& str) const override
{
str.set(thorQueue);
return str;
}
virtual ClusterType getPlatform() const override
{
return platform;
}
virtual unsigned getSize() const override
{
return clusterWidth;
}
virtual bool isLegacyEclServer() const override
{
return false;
}
virtual IStringVal& getScope(IStringVal& str) const override
{
UNIMPLEMENTED;
}
virtual unsigned getNumberOfSlaveLogs() const override
{
UNIMPLEMENTED;
}
virtual IStringVal & getAgentName(IStringVal & str) const override
{
UNIMPLEMENTED;
}
virtual IStringVal & getECLSchedulerName(IStringVal & str) const override
{
UNIMPLEMENTED;
}
virtual const StringArray & getECLServerNames() const override
{
UNIMPLEMENTED;
}
virtual IStringVal & getRoxieProcess(IStringVal & str) const override
{
str.set(name.get());
return str;
}
virtual const StringArray & getThorProcesses() const override
{
return thorProcesses;
}
virtual const StringArray & getPrimaryThorProcesses() const override
{
UNIMPLEMENTED;
}
virtual const SocketEndpointArray & getRoxieServers() const override
{
UNIMPLEMENTED;
}
virtual const char *getLdapUser() const override
{
UNIMPLEMENTED;
}
virtual const char *getLdapPassword() const override
{
UNIMPLEMENTED;
}
virtual unsigned getRoxieRedundancy() const override
{
return 1;
}
virtual unsigned getChannelsPerNode() const override
{
return 1;
}
virtual int getRoxieReplicateOffset() const override
{
return 0;
}
virtual const char *getAlias() const override
{
UNIMPLEMENTED;
}
};
extern TPWRAPPER_API unsigned getContainerWUClusterInfo(CConstWUClusterInfoArray& clusters)
{
Owned<IPropertyTreeIterator> queues = getComponentConfigSP()->getElements("queues");
ForEach(*queues)
{
IPropertyTree& queue = queues->query();
Owned<IConstWUClusterInfo> cluster = new CContainerWUClusterInfo(queue.queryProp("@name"),
queue.queryProp("@type"), (unsigned) queue.getPropInt("@width", 1));
clusters.append(*cluster.getClear());
}
return clusters.ordinality();
}
extern TPWRAPPER_API unsigned getWUClusterInfo(CConstWUClusterInfoArray& clusters)
{
return getEnvironmentClusterInfo(clusters);
}
static IPropertyTree * getContainerClusterConfig(const char * clusterName)
{
VStringBuffer xpath("queues[@name='%s']", clusterName);
return getComponentConfigSP()->getPropTree(xpath);
}
extern TPWRAPPER_API IConstWUClusterInfo* getWUClusterInfoByName(const char* clusterName)
{
return getTargetClusterInfo(clusterName);
}
extern TPWRAPPER_API void initContainerRoxieTargets(MapStringToMyClass<ISmartSocketFactory>& connMap)
{
Owned<IPropertyTreeIterator> services = getGlobalConfigSP()->getElements("services[@type='roxie']");
ForEach(*services)
{
IPropertyTree& service = services->query();
const char* name = service.queryProp("@name");
const char* target = service.queryProp("@target");
const char* port = service.queryProp("@port");
if (isEmptyString(target) || isEmptyString(name)) //bad config?
continue;
StringBuffer s;
s.append(name).append(':').append(port ? port : "9876");
Owned<ISmartSocketFactory> sf = new CSmartSocketFactory(s.str(), false, 60, (unsigned) -1);
connMap.setValue(target, sf.get());
}
}
extern TPWRAPPER_API unsigned getThorClusterNames(StringArray& targetNames, StringArray& queueNames)
{
StringArray thorNames, groupNames;
getEnvironmentThorClusterNames(thorNames, groupNames, targetNames, queueNames);
return targetNames.ordinality();
}
static std::set<std::string> validTargets;
static CriticalSection validTargetSect;
// called within validTargetSect lock
static void refreshValidTargets()
{
validTargets.clear();
Owned<IStringIterator> it = getTargetClusters(nullptr, nullptr);
ForEach(*it)
{
SCMStringBuffer s;
IStringVal& val = it->str(s);
if (validTargets.find(val.str()) == validTargets.end())
{
validTargets.insert(val.str());
PROGLOG("adding valid target: %s", val.str());
}
}
}
extern TPWRAPPER_API void validateTargetName(const char* target)
{
if (isEmptyString(target))
throw makeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Empty target name.");
CriticalBlock block(validTargetSect);
if (validTargets.find(target) == validTargets.end())
{
// bare metal rechecks in case env. changed since target list built
if (!validateTargetClusterName(target))
throw makeStringExceptionV(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid target name: %s", target);
refreshValidTargets();
}
}
extern TPWRAPPER_API bool validateDataPlaneName(const char * remoteDali, const char * name)
{
return isProcessCluster(remoteDali, name);
}
bool getSashaService(StringBuffer &serviceAddress, const char *serviceName, bool failIfNotFound)
{
if (!isEmptyString(serviceName))
{
// all services are on same sasha on bare-metal as far as esp services are concerned
StringBuffer sashaAddress;
IArrayOf<IConstTpSashaServer> sashaservers;
CTpWrapper dummy;
dummy.getTpSashaServers(sashaservers);
if (0 != sashaservers.ordinality())
{
// NB: this code (in bare-matal) doesn't handle >1 Sasha.
// Prior to this change, it would have failed to [try to] contact any Sasha.
IConstTpSashaServer& sashaserver = sashaservers.item(0);
IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
sashaAddress.append(sashaservermachine.item(0).getNetaddress());
if (!sashaAddress.isEmpty())
{
serviceAddress.append(sashaAddress).append(':').append(DEFAULT_SASHA_PORT);
return true;
}
}
}
if (failIfNotFound)
throw makeStringExceptionV(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND, "Sasha '%s' server not found", serviceName);
return false;
}
bool getSashaServiceEP(SocketEndpoint &serviceEndpoint, const char *service, bool failIfNotFound)
{
StringBuffer serviceAddress;
if (!getSashaService(serviceAddress, service, failIfNotFound))
return false;
serviceEndpoint.set(serviceAddress);
return true;
}
StringBuffer & getRoxieDefaultPlane(StringBuffer & plane, const char * roxieName)
{
Owned <IConstWUClusterInfo> clusterInfo(getTargetClusterInfo(roxieName));
StringBufferAdaptor process(plane);
if (clusterInfo && clusterInfo->getPlatform()==RoxieCluster)
clusterInfo->getRoxieProcess(process);
return plane;
}
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> temp;
vector<string> ans;
dfs(s, temp, ans);
return ans;
}
void dfs(string s, vector<string> &temp, vector<string> &ans) {
if (temp.size() == 4 && s.length() == 0) {
ans.push_back(temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3]);
return;
}
else if (temp.size() >= 4) {
return;
}
for(int i = 1; i <= 3 && i <= s.length(); i++) {
string t = s.substr(0, i);
if (t.length() > 1 && t[0] == '0') break;
if (stoi(t) > 255) break;
temp.push_back(t);
dfs(s.substr(i, s.length() - i), temp, ans);
temp.pop_back();
}
}
};
int main() {
string str = "010010";
Solution s;
vector<string> ret = s.restoreIpAddresses(str);
for (int i = 0; i < ret.size(); i++) {
cout << ret[i] << endl;
}
return 0;
}
|
#ifndef UTIL_LUA_STRING_EXT_HPP
#define UTIL_LUA_STRING_EXT_HPP
struct lua_State;
namespace util
{
void extendString(lua_State* plua_state);
}
#endif // UTIL_LUA_STRING_EXT_HPP
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n; cin >> n;
vector<int> a(n);
for (auto& x: a) cin >> x;
bool alleq = true;
int adjeq = -1;
for (int i = 0; i < n; i++) {
alleq &= (a[i]==a[0]);
if (a[i]==a[(i+1)%n]) adjeq = i;
}
int res = 3;
if (alleq) {
res = 1;
} else if (n % 2 == 0 || adjeq != -1) {
res = 2;
}
cout << res << '\n';
if (res == 1) {
for (int _ = 0; _ < n; _++) {
cout << "1 ";
}cout << '\n';
} else if(res==2){
if (n%2==0) {
for (int i = 0; i < n; i++) {
cout << (i&1)+1 << ' ';
}cout << '\n';
} else {
int i = adjeq;
vector<int> c(n,-1);
c[i]=c[(i+1)%n] = 1;
for (int j = (i+1)%n; (j+1)%n != i; (j+=1)%=n) {
c[(j+1)%n] = c[j]^3;
}
for (auto& x: c) {
cout << x << ' ';
}cout << '\n';
}
} else {
cout << "3 ";
for (int i = 1; i < n; i++) {
cout << (i&1)+1 << ' ';
}cout << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T; cin >> T;
for (int t = 0; t < T; t++) {
solve();
}
return 0;
}
|
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "vpu/frontend/frontend.hpp"
#include "vpu/utils/profiling.hpp"
#include "vpu/compile_env.hpp"
#include "vpu/model/data_contents/ie_blob_content.hpp"
#include <legacy/net_pass.h>
#include <atomic>
#include <memory>
#include <string>
#include <tuple>
#include <set>
#include <map>
#include <vector>
#include <utility>
#include <string>
#include <legacy/convert_function_to_cnn_network.hpp>
#include <ngraph/pass/manager.hpp>
#include <ngraph/opsets/opset3.hpp>
#include <ngraph/opsets/opset4.hpp>
#include <ngraph/opsets/opset5.hpp>
#include <ngraph/pass/constant_folding.hpp>
#include <transformations/opset_conversions/convert_opset3_to_opset2.hpp>
#include <transformations/opset_conversions/convert_opset2_to_opset1.hpp>
#include <transformations/op_conversions/convert_previous_nms_to_nms_5.hpp>
#include <transformations/op_conversions/convert_gelu.hpp>
#include <transformations/op_conversions/softplus_decomposition.hpp>
#include <transformations/op_conversions/convert_minimum_to_power_and_max.hpp>
#include <transformations/op_conversions/hswish_decomposition.hpp>
#include <transformations/op_conversions/simplify_ctc_greedy_decoder_seq_len.hpp>
#include <transformations/op_conversions/convert_gather_downgrade.hpp>
#include <vpu/ngraph/transformations/convert_gatherND8.hpp>
#include <vpu/ngraph/transformations/convert_transpose_presicion.hpp>
#include <transformations/convert_precision.hpp>
#include <legacy/transformations/convert_opset1_to_legacy/convert_opset1_to_legacy.hpp>
#include <transformations/common_optimizations/common_optimizations.hpp>
#include <transformations/common_optimizations/wrap_interpolate_into_transposes.hpp>
#include <transformations/common_optimizations/transpose_sinking.hpp>
#include <transformations/init_node_info.hpp>
#include <vpu/ngraph/transformations/convert_extract_image_patches_to_reorg_yolo.hpp>
#include <vpu/ngraph/transformations/merge_subsequent_dsr_operations.hpp>
#include "vpu/ngraph/transformations/dynamic_to_static_shape.hpp"
#include "vpu/ngraph/transformations/eliminate_shapeof_after_dsr.hpp"
#include <vpu/ngraph/operations/dynamic_shape_resolver.hpp>
#include <vpu/ngraph/utilities.hpp>
#include <legacy/ie_util_internal.hpp>
#include <legacy/transformations/convert_opset1_to_legacy/convert_gather_to_gather_ie.hpp>
#include <legacy/transformations/convert_opset1_to_legacy/convert_matmul_to_fc_or_gemm.hpp>
#include <legacy/transformations/convert_opset1_to_legacy/convert_strided_slice_to_crop.hpp>
#include <vpu/ngraph/transformations/extract_dynamic_batch/extract_dynamic_batch.hpp>
#include <vpu/ngraph/transformations/merge_gather_gather_elements.hpp>
#include <transformations/op_conversions/mvn6_decomposition.hpp>
#include <vpu/configuration/options/disable_convert_stages.hpp>
#include <vpu/configuration/options/ignore_unknown_layers.hpp>
#include <vpu/configuration/options/custom_layers.hpp>
#include <vpu/configuration/options/config_file.hpp>
#include <vpu/utils/skip_layers.hpp>
namespace vpu {
FrontEnd::FrontEnd(StageBuilder::Ptr stageBuilder, const std::shared_ptr<ie::ICore> core)
: _stageBuilder(std::move(stageBuilder)),
_core(core),
parsers{{
{"Convolution", LAYER_PARSER(parseConvolution)},
{"Pooling", LAYER_PARSER(parsePooling)},
{"ReLU", LAYER_PARSER(parseReLU)},
{"Clamp", LAYER_PARSER(parseClamp)},
{"FullyConnected", LAYER_PARSER(parseFullyConnected)},
{"SoftMax", LAYER_PARSER(parseSoftMax)},
{"GRN", LAYER_PARSER(parseGRN)},
{"MVN", LAYER_PARSER(parseMVN)},
{"Norm", LAYER_PARSER(parseNorm)},
{"Concat", LAYER_PARSER(parseConcat)},
{"Eltwise", LAYER_PARSER(parseEltwise)},
// Slice is represented as Split in VPU model
{"Split", LAYER_PARSER(parseSplit)},
{"Slice", LAYER_PARSER(parseSplit)},
{"Sigmoid", LAYER_PARSER(parseSigmoid)},
{"TanH", LAYER_PARSER(parseTanH)},
{"PReLU", LAYER_PARSER(parsePReLU)},
{"Bias", LAYER_PARSER(parseBias)},
{"BatchNormalization", LAYER_PARSER(parseBatchNorm)},
{"ScaleShift", LAYER_PARSER(parseScale)},
{"Deconvolution", LAYER_PARSER(parseDeconvolution)},
{"Power", LAYER_PARSER(parsePower)},
{"Copy", LAYER_PARSER(parseCopy)},
{"ELU", LAYER_PARSER(parseELU)},
// Flatten, Squeeze and Unsqueeze are represented as Reshape in VPU model
{"Reshape", LAYER_PARSER(parseReshape)},
{"Flatten", LAYER_PARSER(parseReshape)},
{"Squeeze", LAYER_PARSER(parseReshape)},
{"Unsqueeze", LAYER_PARSER(parseReshape)},
{"Crop", LAYER_PARSER(parseCrop)},
{"Tile", LAYER_PARSER(parseTile)},
{"Normalize", LAYER_PARSER(parseNormalize)},
{"PriorBox", LAYER_PARSER(parsePriorBox)},
{"PriorBoxClustered", LAYER_PARSER(parsePriorBoxClustered)},
{"Permute", LAYER_PARSER(parsePermute)},
{"DetectionOutput", LAYER_PARSER(parseDetectionOutput)},
{"RegionYolo", LAYER_PARSER(parseRegionYolo)},
{"ReorgYolo", LAYER_PARSER(parseReorgYolo)},
{"CTCGreedyDecoder", LAYER_PARSER(parseCTCDecoder)},
{"Proposal", LAYER_PARSER(parseProposal)},
{"ROIPooling", LAYER_PARSER(parseROIPooling)},
{"PSROIPooling", LAYER_PARSER(parsePSROIPooling)},
{"Interp", LAYER_PARSER(parseInterp)},
{"Interpolate", LAYER_PARSER(parseInterpolate)},
{"Custom", LAYER_PARSER(parseCustom)},
{"MTCNN", LAYER_PARSER(parseMTCNN)},
{"LSTMCell", LAYER_PARSER(parseLSTMCell)},
{"Pad", LAYER_PARSER(parsePad)},
{"Resample", LAYER_PARSER(parseResample)},
{"LSTMSequence", LAYER_PARSER(parseRNN)},
{"GEMM", LAYER_PARSER(parseGEMM)},
{"Log", LAYER_PARSER(parseLog)},
{"Exp", LAYER_PARSER(parseExp)},
{"ReverseSequence", LAYER_PARSER(parseReverseSequence)},
{"Gather", LAYER_PARSER(parseGather)},
{"ReduceAnd", LAYER_PARSER(parseReduce)},
{"Floor", LAYER_PARSER(parseFloor)},
{"TopK", LAYER_PARSER(parseTopK)},
{"ReduceMin", LAYER_PARSER(parseReduce)},
{"StridedSlice", LAYER_PARSER(parseStridedSlice)},
{"Select", LAYER_PARSER(parseSelect)},
{"Erf", LAYER_PARSER(parseErf)},
{"ExperimentalDetectronDetectionOutput", LAYER_PARSER(parseExpDetectionOutput)},
{"ExperimentalDetectronROIFeatureExtractor", LAYER_PARSER(parseROIFeatureExtractor)},
{"Convert", LAYER_PARSER(parseConvert)},
{"ReduceMax", LAYER_PARSER(parseReduce)},
{"ReduceSum", LAYER_PARSER(parseReduce)},
{"ReduceMean", LAYER_PARSER(parseReduce)},
{"TensorIterator", LAYER_PARSER(parseTensorIterator)},
{"OneHot", LAYER_PARSER(parseOneHot)},
{"ExperimentalDetectronPriorGridGenerator", LAYER_PARSER(parseExpPriorGridGenerator)},
{"ExperimentalDetectronGenerateProposalsSingleImage", LAYER_PARSER(parseExpGenerateProposals)},
{"ScatterUpdate", LAYER_PARSER(parseScatterUpdate)},
{"ScatterElementsUpdate", LAYER_PARSER(parseScatterElementsUpdate)},
{"ExperimentalDetectronTopKROIs", LAYER_PARSER(parseExpTopKROIs)},
{"StaticShapeNonZero", LAYER_PARSER(parseNonZero)},
{"ROIAlign", LAYER_PARSER(parseROIAlign)},
{"DynamicShapeResolver", LAYER_PARSER(parseDSR)},
{"OutShapeOfReshape", LAYER_PARSER(parseOutShapeOfReshape)},
{"StaticShapeBroadcast", LAYER_PARSER(parseBroadcast)},
{"StaticShapeNonMaxSuppression", LAYER_PARSER(parseStaticShapeNMS)},
{"StaticShapeReshape", LAYER_PARSER(parseReshape)},
{"Mish", LAYER_PARSER(parseMish)},
{"Gelu", LAYER_PARSER(parseGelu)},
{"SoftPlus", LAYER_PARSER(parseSoftPlus)},
{"Swish", LAYER_PARSER(parseSwish)},
{"Activation", LAYER_PARSER(parseActivation)},
{"GatherND", LAYER_PARSER(parseGatherND)},
{"HSwish", LAYER_PARSER(parseHSwish)},
{"Ceiling", LAYER_PARSER(parseCeiling)},
{"GatherElements", LAYER_PARSER(parseGatherElements)},
{"ExpGatherElements", LAYER_PARSER(parseGatherElements)},
{"Round", LAYER_PARSER(parseRound)},
{"CTCGreedyDecoderSeqLen", LAYER_PARSER(parseCTCGreedyDecoderSeqLen)},
{"Abs", LAYER_PARSER(parseAbs)}
}} {
VPU_THROW_UNLESS(_core != nullptr, "Argument core is null");
}
ModelPtr FrontEnd::buildInitialModel(const ie::CNNNetwork& network) {
VPU_PROFILE(buildInitialModel);
const auto& env = CompileEnv::get();
env.log->debug("FrontEnd : Build initial Model");
VPU_LOGGER_SECTION(env.log);
return runCommonPasses(network);
}
ie::CNNNetwork FrontEnd::convertNetwork(ie::CNNNetwork& network) {
auto nGraphFunc = network.getFunction();
ngraph::pass::Manager manager;
manager.register_pass<::ngraph::pass::InitNodeInfo>();
manager.register_pass<ngraph::pass::ConvertNMS1ToNMS5>();
manager.register_pass<ngraph::pass::ConvertNMS3ToNMS5>();
manager.register_pass<ngraph::pass::ConvertNMS4ToNMS5>();
manager.register_pass<ngraph::pass::ConvertGather8ToGather7>();
manager.register_pass<ngraph::pass::ConvertGather7ToGather1>();
manager.register_pass<vpu::ConvertGatherND8ToGatherND5>();
manager.register_pass<vpu::MergeGatherGatherElements>();
manager.register_pass<ngraph::pass::CommonOptimizations>();
manager.register_pass<ngraph::pass::WrapInterpolateIntoTransposes>();
manager.register_pass<ngraph::pass::TransposeSinking>();
manager.register_pass<vpu::ConvertTransposePrecision>();
manager.register_pass<vpu::ExtractBatch>(std::unordered_set<ngraph::Node::type_info_t> {
ngraph::opset5::MatMul::get_type_info_static(),
ngraph::opset5::Convolution::get_type_info_static(),
ngraph::opset5::GroupConvolution::get_type_info_static()
});
manager.register_pass<vpu::DynamicToStaticShape>();
manager.register_pass<vpu::EliminateShapeOfAfterDSR>();
manager.register_pass<vpu::ConvertExtractImagePatchesToReorgYolo>();
// ConstantFolding placed here to avoid precision type missmatch when we try to evaluate nodes with BOOL output.
// For example evaluate_greater_equal calls set_broadcast function with hardcoded BOOL precision.
// In set_broadcast function we compare original node's precision with hardcoded so we get an error if we change precision before.
manager.register_pass<ngraph::pass::ConstantFolding>();
manager.register_pass<ngraph::pass::ConvertOpSet3ToOpSet2>();
manager.register_pass<ngraph::pass::ConvertOpSet2ToOpSet1>();
// ConvertPrecision must be executed before ConvertOpSet1ToLegacy due to this pass works with operations from opsets only
static const precisions_array precisions = {
{ ngraph::element::i64, ngraph::element::i32 },
{ ngraph::element::u64, ngraph::element::i32 },
{ ngraph::element::u32, ngraph::element::i32 },
{ ngraph::element::boolean, ngraph::element::i32 }
};
manager.register_pass<ngraph::pass::ConvertPrecision>(precisions, myriadTypeToFuseMap);
manager.register_pass<ngraph::pass::ConvertOpSet1ToLegacy>();
// ConvertOpSet1ToLegacy can produce constants with I64 precision
manager.register_pass<ngraph::pass::ConvertPrecision>(precisions_array {{ ngraph::element::i64, ngraph::element::i32 }}, myriadTypeToFuseMap);
manager.register_pass<vpu::MergeSubsequentDSROperations>();
auto pass_config = manager.get_pass_config();
pass_config->disable<ngraph::pass::ConvertGatherToGatherIEMatcher>();
pass_config->disable<ngraph::pass::ConvertGELU>();
pass_config->disable<ngraph::pass::SoftPlusDecomposition>();
pass_config->disable<ngraph::pass::ConvertMinimum>();
pass_config->disable<ngraph::pass::HSwishDecomposition>();
pass_config->disable<ngraph::pass::MVN6Decomposition>();
pass_config->disable<ngraph::pass::SimplifyCTCGreedyDecoderSeqLen>();
auto transformationPredicate = [](const std::shared_ptr<const ngraph::Node>& node) -> bool {
return !!std::dynamic_pointer_cast<const ngraph::vpu::op::DynamicShapeResolver>(node->input_value(0).get_node_shared_ptr());
};
pass_config->set_callback<ngraph::pass::ConvertMatMulToFC,
ngraph::pass::ConvertStridedSliceToCropMatcher>(transformationPredicate);
manager.run_passes(nGraphFunc);
IE_SUPPRESS_DEPRECATED_START
return ie::CNNNetwork(ie::details::convertFunctionToICNNNetwork(nGraphFunc, network));
IE_SUPPRESS_DEPRECATED_END
}
std::vector<ie::CNNNetwork> FrontEnd::checkSupportedNetworks(const ie::CNNNetwork& network, std::set<std::string>& namesToExclude) {
std::vector<ie::CNNNetwork> supportedNetworks;
if (network.getFunction() && network.getFunction()->is_dynamic()) {
auto copyNetwork = InferenceEngine::details::cloneNetwork(network);
try {
convertNetwork(copyNetwork);
} catch(vpu::details::VPUException e) {
// Parsing the error message in order to get name of the node that caused the exeption.
// Error message should be in the following format:
// ".* node {name} of type {type} .*"
std::string name = e.what();
std::cout << name << "\n";
std::string nameDelimiter("node ");
name.erase(0, name.find(nameDelimiter) + nameDelimiter.length());
nameDelimiter = " of";
name.erase(name.find(nameDelimiter), name.length());
auto function = network.getFunction();
bool notFound = true;
ov::ParameterVector paramsTop;
ov::NodeVector resultsLow;
ov::NodeVector networkTop;
ov::NodeVector networkLow;
for (auto& node : function->get_ordered_ops()) {
if (node->get_friendly_name() == name) {
notFound = false;
continue;
}
if (notFound) {
networkTop.push_back(node);
continue;
}
networkLow.push_back(node);
}
if (notFound) {
throw e;
}
namesToExclude.insert(name);
if (networkTop.size() != 0) {
ov::NodeVector resultsTop;
std::map<std::string, std::shared_ptr<ov::Node>> newNodes;
for (auto& node : networkTop) {
if (strcmp(node->get_type_info().name, "Parameter") == 0) {
auto input = std::dynamic_pointer_cast<ngraph::opset3::Parameter>(node);
auto newNode = std::make_shared<ngraph::opset3::Parameter>(input->get_element_type(), input->get_partial_shape());
newNode->set_friendly_name(node->get_friendly_name());
paramsTop.push_back(newNode);
newNodes[node->get_friendly_name()] = newNode;
continue;
}
ov::OutputVector inputs;
for (auto& input : node->input_values()) {
auto& newNode = newNodes[input.get_node()->get_friendly_name()];
inputs.push_back(ov::Output<ov::Node>(newNode));
}
auto nodeCopy = node->copy_with_new_inputs(inputs);
nodeCopy->set_friendly_name(node->get_friendly_name());
newNodes[node->get_friendly_name()] = nodeCopy;
if (strcmp(node->get_type_info().name, "Result") == 0) {
resultsLow.push_back(std::dynamic_pointer_cast<ngraph::opset3::Result>(nodeCopy));
continue;
}
for (size_t i = 0; i < node->get_output_size(); ++i) {
const auto& set = node->get_output_target_inputs(i);
for (auto& setEl : set) {
auto el = setEl.get_node();
if (std::find(networkTop.begin(), networkTop.end(), std::shared_ptr<ov::Node>(el)) != networkTop.end()) {
auto result = std::make_shared<ngraph::opset3::Result>(nodeCopy);
result->set_friendly_name(el->get_friendly_name());
newNodes[el->get_friendly_name()] = result;
resultsTop.push_back(result);
}
}
}
}
auto modelTop = std::make_shared<ov::Model>(resultsTop, paramsTop, "networkTop");
auto supportTop = checkSupportedNetworks(ie::CNNNetwork(modelTop), namesToExclude);
supportedNetworks.insert(supportedNetworks.end(), supportTop.begin(), supportTop.end());
}
if (networkLow.size() != 0) {
std::map<std::string, std::shared_ptr<ov::Node>> newNodes;
ov::ParameterVector paramsLow;
for (auto& node : networkLow) {
if (strcmp(node->get_type_info().name, "Parameter") == 0) {
auto input = std::dynamic_pointer_cast<ngraph::opset3::Parameter>(node);
auto newNode = std::make_shared<ngraph::opset3::Parameter>(input->get_element_type(), input->get_partial_shape());
newNode->set_friendly_name(node->get_friendly_name());
paramsLow.push_back(newNode);
newNodes[node->get_friendly_name()] = newNode;
continue;
}
ov::OutputVector inputs;
for (auto& input : node->input_values()) {
if (newNodes.count(input.get_node()->get_friendly_name()) == 0) {
if (strcmp(input.get_node()->get_type_info().name, "Constant") == 0) {
const auto& constant = dynamic_cast<ngraph::opset3::Constant*>(input.get_node());
const auto& subConstant = std::make_shared<ngraph::opset3::Constant>(
constant->get_element_type(),
constant->get_shape(),
constant->get_value_strings());
subConstant->set_friendly_name(input.get_node()->get_friendly_name());
inputs.push_back(ov::Output<ov::Node>(subConstant));
newNodes[input.get_node()->get_friendly_name()] = subConstant;
continue;
}
const auto& parameter = std::make_shared<ngraph::opset3::Parameter>(
input.get_element_type(),
input.get_partial_shape().get_max_shape());
parameter->set_friendly_name(input.get_node()->get_friendly_name());
input.get_node()->set_friendly_name(parameter->get_friendly_name());
paramsLow.push_back(parameter);
inputs.push_back(parameter);
newNodes[parameter->get_friendly_name()] =
std::dynamic_pointer_cast<ov::Node>(parameter);
} else {
auto& newNode = newNodes[input.get_node()->get_friendly_name()];
inputs.push_back(ov::Output<ov::Node>(newNode));
}
}
auto nodeCopy = node->copy_with_new_inputs(inputs);
nodeCopy->set_friendly_name(node->get_friendly_name());
newNodes[node->get_friendly_name()] = nodeCopy;
if (strcmp(node->get_type_info().name, "Result") == 0) {
resultsLow.push_back(std::dynamic_pointer_cast<ngraph::opset3::Result>(nodeCopy));
continue;
}
}
auto modelLow = std::make_shared<ov::Model>(resultsLow, paramsLow, "networkLow");
auto supportLow = checkSupportedNetworks(ie::CNNNetwork(modelLow), namesToExclude);
supportedNetworks.insert(supportedNetworks.end(), supportLow.begin(), supportLow.end());
}
return supportedNetworks;
}
}
supportedNetworks.push_back(network);
return supportedNetworks;
}
std::set<std::string> FrontEnd::checkSupportedLayers(const ie::CNNNetwork& network, const std::set<std::string>& namesToExclude) {
VPU_PROFILE(checkSupportedLayers);
const auto& env = CompileEnv::get();
env.log->debug("FrontEnd : Check supported layers");
VPU_LOGGER_SECTION(env.log);
std::set<std::string> supportedLayers;
const auto onSupportedLayer = [&supportedLayers](const ie::CNNLayerPtr& layer) {
supportedLayers.insert(layer->name);
};
const auto onUnsupportedLayer = [this](
const Model& model,
const ie::CNNLayerPtr& layer,
const DataVector& inputs,
const DataVector& outputs,
const std::string& /*extraMsg*/) {
_stageBuilder->addNoneStage(model, layer->name, layer, inputs, outputs);
};
runCommonPasses(cloneNetwork(network), onUnsupportedLayer, onSupportedLayer);
for (auto name : namesToExclude) {
supportedLayers.erase(name);
}
return supportedLayers;
}
namespace {
std::atomic<int> g_counter(0);
} // namespace
CustomLayer::Ptr FrontEnd::getSuitableCustomLayer(const std::vector<CustomLayer::Ptr>& customLayers,
const ie::CNNLayerPtr& cnnLayer) {
const auto& env = CompileEnv::get();
env.log->trace("Check for suitable custom implementation for layer %s:%s",
cnnLayer->name, cnnLayer->type);
VPU_LOGGER_SECTION(env.log);
const auto cnnInputs = [&] {
auto inputs = SmallVector<CustomDataFormat>{};
inputs.reserve(cnnLayer->insData.size());
for (const auto& input : cnnLayer->insData) {
const auto layout = input.lock()->getLayout();
const auto format = CustomLayer::formatFromLayout(layout);
inputs.push_back(format);
}
return inputs;
}();
const auto cnnOutputs = [&] {
auto outputs = SmallVector<CustomDataFormat>{};
outputs.reserve(cnnLayer->outData.size());
for (const auto& output : cnnLayer->outData) {
const auto layout = output->getLayout();
const auto format = CustomLayer::formatFromLayout(layout);
outputs.push_back(format);
}
return outputs;
}();
const auto isSuitableLayer = [&env, &cnnLayer](const CustomLayer::Ptr& customLayer) {
env.log->trace("Check next custom layer : %v", customLayer->layerName());
VPU_LOGGER_SECTION(env.log);
if (!customLayer->meetsWhereRestrictions(cnnLayer->params)) {
env.log->trace("Where restrictions are not met");
return false;
}
for (const auto& kernel : customLayer->kernels()) {
const auto& gws = kernel.globalGridSizeRules();
const auto& lws = kernel.localGridSizeRules();
const auto validSizeRule = [&](const std::string& rule) {
return CustomLayer::isLegalSizeRule(rule, cnnLayer->params);
};
const auto validGridSizes = std::all_of(begin(gws), end(gws), validSizeRule) &&
std::all_of(begin(lws), end(lws), validSizeRule);
if (!validGridSizes) {
env.log->trace("Work group grid sizes are not valid");
return false;
}
}
return true;
};
auto suitableCustomLayers = SmallVector<CustomLayer::Ptr>{};
std::copy_if(begin(customLayers), end(customLayers),
back_inserter(suitableCustomLayers), isSuitableLayer);
if (suitableCustomLayers.empty()) {
return nullptr;
}
const auto inputsLayoutMatch = [&](const SmallVector<CustomDataFormat>& cnnEdges,
const std::map<int, CustomDataFormat>& clEdges) {
for (const auto clEdge : clEdges) {
const auto port = clEdge.first;
VPU_THROW_UNLESS(port < cnnEdges.size(),
"Can't bind custom layer edge with port '%s' to CNNNetwork layer", port);
const auto clFormat = clEdge.second;
const auto cnnFormat = cnnEdges[port];
if (cnnFormat != clFormat &&
cnnFormat != CustomDataFormat::Any &&
clFormat != CustomDataFormat::Any) {
return false;
}
}
return true;
};
for (const auto& customLayer : suitableCustomLayers) {
const auto clInputs = customLayer->inputs();
if (inputsLayoutMatch(cnnInputs, clInputs)) {
env.log->trace("Found suitable '%s' custom layer", customLayer->layerName());
return customLayer;
}
}
const auto firstGoodLayer = suitableCustomLayers.front();
env.log->trace("Found suitable custom layer '%s', but input layouts "
"have not matched with what CNNNetwork expected",
firstGoodLayer->layerName());
return firstGoodLayer;
}
void FrontEnd::parseLayer(const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs) {
parseLayer(model, layer, inputs, outputs,
[this](const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs,
const std::string& extraMessage)
{ defaultOnUnsupportedLayerCallback(model, layer, inputs, outputs, extraMessage); });
}
void FrontEnd::parseLayer(const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs,
const FrontEnd::UnsupportedLayerCallback& onUnsupported, const FrontEnd::SupportedLayerCallback& onSupported) {
const auto customLayer = _customLayers.find(layer->type);
const bool isCustomLayer = customLayer != _customLayers.end() && getSuitableCustomLayer(customLayer->second, layer);
const auto& type = isCustomLayer ? "Custom" : layer->type;
if (parsers.count(type) == 0) {
if (onUnsupported) {
onUnsupported(model, layer, inputs, outputs, formatString("unsupported layer type \"%v\"", type));
}
return;
}
try {
parsers.at(type)(model, layer, inputs, outputs);
if (onSupported) {
onSupported(layer);
}
} catch (const details::UnsupportedLayerException&) {
throw;
} catch (const std::exception& error) {
if (onUnsupported) {
onUnsupported(model, layer, inputs, outputs, error.what());
}
}
}
void FrontEnd::processTrivialCases(const Model& model) {
std::unordered_map<ie::DataPtr, std::pair<Data, Data>> ieDataToTrivialCase;
for (const auto& data : model->datas()) {
const auto& origData = data->origData();
if (origData == nullptr) {
continue;
}
auto& trivialCase = ieDataToTrivialCase[origData];
auto& destination = data->usage() == DataUsage::Output ? trivialCase.second : trivialCase.first;
VPU_THROW_UNLESS(ieDataToTrivialCase.count(origData) == 0 || destination == nullptr,
"Encountered IE data object {} which has two vpu data objects {} and {} of the same type {} associated with it, while only one is permitted",
origData->getName(), destination->name(), data->name(), destination->usage());
destination = data;
}
for (const auto& trivialCase : ieDataToTrivialCase) {
const auto& trivialCasePair = trivialCase.second;
const auto& unconnectedInput = trivialCasePair.first;
const auto& unconnectedOutput = trivialCasePair.second;
if (!unconnectedInput || !unconnectedOutput) {
continue;
}
_stageBuilder->addCopyStage(
model,
unconnectedInput->name() + "@copy",
nullptr,
{unconnectedInput},
{unconnectedOutput},
"processTrivialCase");
}
}
void FrontEnd::defaultOnUnsupportedLayerCallback(const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs,
const std::string& extraMessage) {
const auto& env = CompileEnv::get();
VPU_THROW_UNSUPPORTED_LAYER_UNLESS(env.config.get<IgnoreUnknownLayersOption>(), "Failed to compile layer \"%v\": %v", layer->name, extraMessage);
_stageBuilder->addNoneStage(model, layer->name, layer, inputs, outputs);
}
ModelPtr FrontEnd::runCommonPasses(const ie::CNNNetwork& network) {
return runCommonPasses(cloneNetwork(network),
[this](const Model& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs, const std::string& extraMessage) {
defaultOnUnsupportedLayerCallback(model, layer, inputs, outputs, extraMessage);});
}
ModelPtr FrontEnd::runCommonPasses(ie::CNNNetwork network,
const UnsupportedLayerCallback& unsupportedLayer, const SupportedLayerCallback& supportedLayer) {
const auto& env = CompileEnv::get();
//
// Clear Front-end state
//
_ieParsedNetwork = {};
_unbatchedOutputs.clear();
_ieToVpuMap.clear();
_customLayers.clear();
_kernelNodes.clear();
_lstmWeights.clear();
_lstmBiases.clear();
//
// Parse custom layers
//
auto customLayers = env.config.get<CustomLayersOption>().empty()
? env.config.get<ConfigFileOption>() : env.config.get<CustomLayersOption>();
if (!customLayers.empty()) {
env.log->trace("Parse custom layers : %s", customLayers);
VPU_LOGGER_SECTION(env.log);
_customLayers = CustomLayer::loadFromFile(customLayers);
}
//
// Create new VPU model
//
auto model = std::make_shared<ModelObj>(network.getName());
model->attrs().set<int>("index", g_counter.fetch_add(1));
model->attrs().set<Resources>("resources", env.resources);
// Transmitting Information about the parameters/results of the network for
// the possibility of importing it
if (network.getFunction() != nullptr) {
model->attrs().set<ov::ParameterVector>(
"networkParameters", network.getFunction()->get_parameters());
model->attrs().set<ov::ResultVector>(
"networkResults", network.getFunction()->get_results());
}
//
// Update IE Network
//
{
env.log->trace("Update IE Network");
VPU_LOGGER_SECTION(env.log);
detectNetworkBatch(network, model);
if (network.getFunction()) {
network = convertNetwork(network);
}
const std::vector<std::pair<ngraph::element::Type, ngraph::element::Type>> convert_precision_list {
{ngraph::element::i64, ngraph::element::i32},
{ngraph::element::u64, ngraph::element::i32},
{ngraph::element::u32, ngraph::element::i32},
{ngraph::element::boolean, ngraph::element::i32},
};
// WA: after conversion to CNNNetwork user precision can redefine input/output precisions
// so we need to apply additional precision conversion but only for inputs and outputs
// This method should be removed #-48878
for (const auto& precision : convert_precision_list) {
ie::NetPass::ConvertIOPrecision(network,
InferenceEngine::details::convertPrecision(precision.first),
InferenceEngine::details::convertPrecision(precision.second));
}
removeConstLayers(network);
unrollLoops(network);
}
//
// Parse IR Network
//
_ieParsedNetwork = parseNetwork(network);
//
// Process internal VPU Model
//
{
env.log->trace("Process internal VPU Model");
VPU_LOGGER_SECTION(env.log);
parseInputAndOutputData(model);
//
// Process trivial cases like `input->output`, `const->output`
//
processTrivialCases(model);
if (!CompileEnv::get().config.get<DisableConvertStagesOption>()) {
addDataTypeConvertStages(model);
}
addPreProcessStages(model);
}
//
// Parse original layers
//
env.log->trace("Parse original layers");
DataVector inputs, outputs;
for (const auto& layer : origLayers()) {
VPU_LOGGER_SECTION(env.log);
env.log->trace("Try to parse layer %s:%s", layer->name, layer->type);
VPU_LOGGER_SECTION(env.log);
getInputAndOutputData(model, layer, inputs, outputs);
if (skipAllLayers(env.config) || skipLayerType(env.config, layer->type)) {
_stageBuilder->addNoneStage(model, layer->name, layer, inputs, outputs);
supportedLayer(layer);
continue;
}
parseLayer(model, layer, inputs, outputs, unsupportedLayer, supportedLayer);
}
//
// Clean up internal VPU Model
//
{
env.log->trace("Clean up internal VPU Model");
VPU_LOGGER_SECTION(env.log);
model->cleanUp();
}
return model;
}
Data FrontEnd::getVpuData(const ie::DataPtr& ieData) const {
IE_ASSERT(ieData != nullptr);
const auto it = _ieToVpuMap.find(ieData);
if (it == _ieToVpuMap.end()) {
return nullptr;
}
return it->second;
}
void FrontEnd::bindData(const Data& data, const ie::DataPtr& ieData) {
_ieToVpuMap[ieData] = data;
data->setOrigData(ieData);
}
void FrontEnd::getInputAndOutputData(
const Model& model,
const ie::CNNLayerPtr& layer,
DataVector& inputs,
DataVector& outputs) {
IE_ASSERT(layer != nullptr);
inputs.resize(layer->insData.size());
for (size_t i = 0; i < layer->insData.size(); ++i) {
const auto layerInput = layer->insData[i].lock();
IE_ASSERT(layerInput != nullptr);
inputs[i] = getVpuData(layerInput);
IE_ASSERT(inputs[i] != nullptr);
}
outputs.resize(layer->outData.size());
for (size_t i = 0; i < layer->outData.size(); ++i) {
const auto layerOutput = layer->outData[i];
IE_ASSERT(layerOutput != nullptr);
if (const auto data = getVpuData(layerOutput)) {
outputs[i] = data;
} else {
DataDesc dataDesc(layerOutput->getTensorDesc());
if (dataDesc.type() == DataType::FP32) {
// To infer the same FP32 models on different devices (CPU, GPU, VPU and so on)
dataDesc.setType(DataType::FP16);
}
// Skip adding data if it not utilized
const bool isNetworkOutput = _ieParsedNetwork.networkOutputs.count(layerOutput->getName()) > 0;
const auto isLeaf = getInputTo(layerOutput).empty();
if (!isNetworkOutput && isLeaf) {
outputs[i] = nullptr;
continue;
}
outputs[i] = model->addNewData(
layerOutput->getName(),
dataDesc);
bindData(outputs[i], layerOutput);
}
}
}
std::tuple<Data, Data> FrontEnd::getWeightsAndBiases(const Model& model, const ie::CNNLayerPtr& layer) const {
const auto baseLayer = std::dynamic_pointer_cast<ie::WeightableLayer>(layer);
IE_ASSERT(baseLayer != nullptr);
const auto origWeights = baseLayer->_weights;
VPU_THROW_UNLESS(origWeights != nullptr, "Layer %s has no weights", layer->name);
const auto weights = model->addConstData(
layer->name + "@weights",
DataDesc({origWeights->size()}),
ieBlobContent(origWeights));
const auto origBiases = baseLayer->_biases;
Data biases;
if (origBiases == nullptr) {
biases = model->addFakeData();
} else {
biases = model->addConstData(
layer->name + "@biases",
DataDesc({origBiases->size()}),
ieBlobContent(origBiases));
}
return std::make_tuple(weights, biases);
}
} // namespace vpu
|
#ifdef COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4;-*-
$CXXX $CXXFLAGS $0 -o $0.$X -lboost_unit_test_framework&&$0.$X&&rm $0.$X;exit
#endif
// © Alfredo A. Correa 2019-2020
#ifndef MULTI_ADAPTORS_BLAS_NUMERIC_HPP
#define MULTI_ADAPTORS_BLAS_NUMERIC_HPP
#include "../../memory/pointer_traits.hpp"
#include "../../array_ref.hpp"
#include "../../complex.hpp"
#include "numeric/is_complex.hpp"
namespace boost{
namespace multi{
namespace blas{
template<class T> struct Complex_{T real; T imag;};
template<class A, typename T=typename std::decay_t<A>::element_type::value_type, typename C_=Complex_<T>>
auto real_aux(A&& a, std::complex<T> const&)
->decltype(std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::real)){
return std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::real);}
template<class A, typename Complex, typename T=typename std::decay_t<A>::element_type::value_type, typename C_=Complex_<T>, class=std::enable_if_t<blas::numeric::is_complex_of<Complex, T>::value>>
auto real_aux(A&& a, Complex const&)
->decltype(std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::real)){
return std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::real);}
template<class A, class T>
auto real_aux(A&& a, T const&)
->decltype(std::forward<A>(a).template member_cast<T>(&T::real)){
return std::forward<A>(a).template member_cast<T>(&T::real);}
template<class A>
auto real(A&& a)
->decltype(real_aux(std::forward<A>(a), typename std::decay_t<A>::element_type{})){
return real_aux(std::forward<A>(a), typename std::decay_t<A>::element_type{});}
template<class A, typename T=typename std::decay_t<A>::element_type::value_type, typename C_=Complex_<T>>
auto imag_aux(A&& a, std::complex<T> const&)
->decltype(std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::imag)){
return std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::imag);}
template<class A, class Complex, typename T=typename std::decay_t<A>::element_type::value_type, typename C_=Complex_<T>, class=std::enable_if_t<blas::numeric::is_complex_of<Complex, T>::value>
>
auto imag_aux(A&& a, Complex const&)
->decltype(std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::imag)){
return std::forward<A>(a).template reinterpret_array_cast<C_>().template member_cast<T>(&C_::imag);}
template<class A, class T>
auto imag_aux(A&& a, T const&)
->decltype(std::forward<A>(a).template member_cast<T>(&T::imag)){
return std::forward<A>(a).template member_cast<T>(&T::imag);}
template<class A>
auto imag(A&& a)
->decltype(imag_aux(std::forward<A>(a), typename std::decay_t<A>::element_type{})){
return imag_aux(std::forward<A>(a), typename std::decay_t<A>::element_type{});}
template<class Ref, class Involution> class involuted;
template<class It, class F, class Reference = involuted<typename std::iterator_traits<It>::reference, F> > class involuter;
template<class Ref, class Involution>
class involuted{
protected:
Ref r_; // [[no_unique_address]]
Involution f_;
public:
using decay_type =std::decay_t<decltype(std::declval<Involution>()(std::declval<Ref>()))>;
explicit constexpr involuted(Ref r, Involution f = {}) : r_{std::forward<Ref>(r)}, f_{f}{}
involuted& operator=(involuted const& other)=delete;//{r_ = other.r_; return *this;}
public:
involuted(involuted const&) = delete;
involuted(involuted&&) = default; // for C++14
decay_type decay() const&{return f_(r_);}
constexpr operator decay_type() const&{return f_(r_);}
constexpr operator decay_type() &&{return f_(r_);}
decltype(auto) operator&()&&{return involuter<decltype(&std::declval<Ref>()), Involution>{&r_, f_};}
// template<class DecayType>
// auto operator=(DecayType&& other)&&
// ->decltype(r_=f_(std::forward<DecayType>(other)), *this){
// return r_=f_(std::forward<DecayType>(other)), *this;}
template<class DecayType>
auto operator=(DecayType&& other)&
->decltype(r_=f_(std::forward<DecayType>(other)), *this){
return r_=f_(std::forward<DecayType>(other)), *this;}
// template<class OtherRef>
// auto operator=(involuted<OtherRef, Involution> const& o)&
// ->decltype(r_=f_==o.f_?std::forward<decltype(o.r_)>(o.r_):f_(o), *this){
// return r_=f_==o.f_?std::forward<decltype(o.r_)>(o.r_):f_(o), *this;}
template<class DecayType>
auto operator==(DecayType&& other) const
->decltype(this->operator decay_type()==other){
return this->operator decay_type()==other;}
template<class DecayType>
auto operator!=(DecayType&& other) const
->decltype(this->operator decay_type()!=other){
return this->operator decay_type()!=other;}
template<class DecayType, std::enable_if_t<not std::is_base_of<involuted, DecayType>{}, int> =0>
friend auto operator==(DecayType&& other, involuted const& self){
return other == self.operator decay_type();}
template<class DecayType, std::enable_if_t<not std::is_base_of<involuted, DecayType>{}, int> =0>
friend auto operator!=(DecayType&& other, involuted const& self){
return other != self.operator decay_type();}
// auto imag() const{return static_cast<decay_type>(*this).imag();}
template<class Any> friend Any& operator<<(Any&& a, involuted const& self)
// ->decltype(a << self.operator decay_type())
{
return a << self.operator decay_type();}
auto conj() const&{return adl_conj(operator decay_type());}
template<class T = void*>
friend auto imag(involuted const& self, T = nullptr)
->decltype(adl_imag(std::declval<decay_type>())){
return adl_imag(self.operator decay_type());}
};
#if defined(__cpp_deduction_guides)
template<class T, class F> involuted(T&&, F)->involuted<T const, F>;
//template<class T, class F> involuted(T&, F)->involuted<T&, F>;
//template<class T, class F> involuted(T const&, F)->involuted<T const&, F>;
#endif
//template<class It, class F>
//class involuter;
template<class It, class F>
auto get_allocator(involuter<It, F> const& s);
template<class It, class F>
auto default_allocator_of(involuter<It, F> const& iv){
return default_allocator_of(iv.it_);
}
template<class It, class F, class Reference>
class involuter{// : public std::iterator_traits<It>{
It it_; // [[no_unique_address]]
F f_;
template<class, class, class> friend class involuter;
public:
using difference_type = typename std::iterator_traits<It>::difference_type;
using value_type = typename std::iterator_traits<It>::value_type;
using pointer = involuter<It, F>;//svoid; // typename std::iterator_traits<It>::pointer
using reference = Reference;
using iterator_category = typename std::iterator_traits<It>::iterator_category;
using element_type = typename std::pointer_traits<It>::element_type;
template<class U> using rebind = involuter<typename std::pointer_traits<It>::template rebind<U>, F>;
involuter() = default;
explicit involuter(It it, F f = {}) : it_{std::move(it)}, f_{std::move(f)}{}
involuter(involuter const& other) = default;
// template<class Other, > constexpr involuter(Other const& other) : it_{other.it_}, f_{other.f_}{}
template<class Other, typename = decltype(_implicit_cast<It>(typename Other::underlying_type{}))>
constexpr involuter(Other const& o) : it_{o.it_}, f_{o.f_}{}
template<class Other, typename = decltype(_explicit_cast<It>(typename Other::underlying_type{}))>
explicit constexpr involuter(Other const& o, int = 0) : it_{o.it_}, f_{o.f_}{}
constexpr auto operator*() const {return reference{*it_, f_};}
bool operator==(involuter const& o) const{return it_==o.it_;}
bool operator!=(involuter const& o) const{return it_!=o.it_;}
constexpr involuter& operator+=(typename involuter::difference_type n){it_+=n; return *this;}
constexpr auto operator+(typename involuter::difference_type n) const{return involuter{it_+n, f_};}
// decltype(auto) operator->() const{
// return &const_cast<reference&>(reinterpret_cast<reference const&>(*this));
// return reference{*it_, f_};
// return involuter<typename std::iterator_traits<It>::pointer, F>{&*it_, f_};
// }
auto operator-(involuter const& other) const{return it_-other.it_;}
explicit operator bool() const{return it_;}
using underlying_type = It;
friend constexpr underlying_type underlying(involuter const& self){return self.it_;}
constexpr explicit operator It() const {return underlying(*this);}
template<class Itt, class FF> friend auto get_allocator(involuter<Itt, FF> const&);
friend auto default_allocator_of(involuter const& inv){
using multi::default_allocator_of;
return default_allocator_of(inv.it_);
}
using default_allocator_type = typename multi::pointer_traits<It>::default_allocator_type;
friend auto get_allocator(involuter const& inv){
using boost::multi::get_allocator;
return get_allocator(inv.it_);
}
};
template<class It, class F>
auto get_allocator(involuter<It, F> const& inv){
using multi::get_allocator;
return get_allocator(inv.it_);
}
template<class Ref> using negated = involuted<Ref, std::negate<>>;
template<class It> using negater = involuter<It, std::negate<>>;
#if 1
struct conjugate{
template<class T>
decltype(auto) operator()(T&& a) const{
// using std::conj; /*for doubles?*/
// using std::conj;
// std::complex<double> A = static_cast<std::complex<double>>(a);
return multi::adl_conj(std::forward<T>(a)); // this is needed by icc
}
};
#endif
#if 0
namespace detail{
template<class Ref> struct conjugated : involuted<Ref, conjugate>{
using involuted<Ref, conjugate>::involuted;
template<class Other>
conjugated(conjugated<Other> const& other) : involuted<Ref, conjugate>{static_cast<involuted<Ref, conjugate> const&>(other)}{}
auto real() const{return static_cast<typename conjugated::decay_type>(*this).real();}
auto imag() const{return static_cast<typename conjugated::decay_type>(*this).imag();}
friend auto imag(conjugated const& self){return self.imag();}
friend auto real(conjugated const& self){return self.real();}
public:
decltype(auto) operator->() const{return this;}
// friend auto conj(conjugated const& self){
// return conjugate{}(static_cast<typename conjugated::decay_type>(self));
// }
};
}
#endif
template<class Ref> using conjugated = involuted<Ref, conjugate>;
template<class It> using conjugater = involuter<It, conjugate>;//, conjugated<typename std::iterator_traits<It>::reference> >;
template<class It> auto make_conjugater(It it){return conjugater<It>{it};}
template<class It> It make_conjugater(conjugater<It> it){return underlying(it);}
template<class T> auto imag(involuted<T, conjugate> const& inv){return inv.decay().imag();}
template<class T> auto real(involuted<T, conjugate> const& inv){return inv.decay().real();}
template<class T> auto has_imag_fun_aux(T const& t)->decltype(imag(t), std::true_type {});
auto has_imag_fun_aux(... )->decltype( std::false_type{});
template<class T> struct has_imag_fun : decltype(has_imag_fun_aux(std::declval<T>())){};
template<class T> auto has_imag_mem_aux(T const& t)->decltype(t.imag(), std::true_type {});
auto has_imag_mem_aux(... )->decltype( std::false_type{});
template<class T> struct has_imag_mem : decltype(has_imag_mem_aux(std::declval<T>())){};
template<class T> struct has_imag : std::integral_constant<bool, (has_imag_fun<T>{} or has_imag_mem<T>{})>{};
template<class A = void> struct is_complex_array{
template<class T> static auto _(T const& t) -> has_imag<T>;
constexpr operator bool() const{return decltype(_(*base(std::declval<A>()))){};}
template<class AA> constexpr auto operator()(AA&&){return _(*base(std::declval<A>()));}
};
template<class A = void> struct is_conjugated{
template<class It> static std::true_type _(conjugater<It> a);
static std::false_type _(... );
constexpr operator bool() const{return decltype(_(base(std::declval<A>()))){};}
template<class AA> constexpr auto operator()(AA&&){return _(base(std::declval<A>()));}
};
template<class A, class D = std::decay_t<A>, typename Elem=typename D::element_type, typename Ptr=typename D::element_ptr,
std::enable_if_t<not is_complex_array<A>{}, int> =0>
A&& conj(A&& a){
// return multi::static_array_cast<Elem, conjugater<Ptr>>(a);
return std::forward<A>(a);
}
template<class A, class D = std::decay_t<A>, typename Elem=typename D::element_type, typename Ptr=typename D::element_ptr,
std::enable_if_t<not is_conjugated<A>{} and is_complex_array<A>{}, int> =0>
decltype(auto) conj(A&& a){
// return multi::static_array_cast<Elem, conjugater<Ptr>>(a);
return std::forward<A>(a).template static_array_cast<Elem, conjugater<Ptr>>();
}
template<class A, class D = std::decay_t<A>, typename Elem=typename D::element_type, typename Ptr=typename D::element_ptr::underlying_type,
std::enable_if_t< is_conjugated<A>{}, int> =0>
auto conj(A&& a)
->decltype(std::forward<A>(a).template static_array_cast<Elem, Ptr>()){
return std::forward<A>(a).template static_array_cast<Elem, Ptr>();}
// return multi::static_array_cast<Elem, Ptr>(a);}
// return multi::static_array_cast<Elem, Ptr>(a);}
}
template<class It, class F, class Reference>
auto default_allocator_of(blas::involuter<It, F, Reference> it){
return multi::default_allocator_of(underlying(it));
}
}
}
namespace std{
template<> struct is_convertible<boost::multi::blas::Complex_<double>*, std::complex<double>*> : std::true_type{};
template<class T> struct is_convertible<boost::multi::blas::Complex_<double>*, T*> : boost::multi::blas::numeric::is_complex_of<T, double>{};
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#if not __INCLUDE_LEVEL__ // _TEST_MULTI_ADAPTORS_BLAS_NUMERIC
#define BOOST_TEST_MODULE "C++ Unit Tests for Multi BLAS numeric"
#define BOOST_TEST_DYN_LINK
#include<boost/test/unit_test.hpp>
//#include "../blas/gemm.hpp"
#include "../../array.hpp"
#include "../../utility.hpp"
//#include<thrust/complex.h>
//#include "../../adaptors/cuda.hpp"
#include<cassert>
#include<iostream>
namespace multi = boost::multi;
template<class M> decltype(auto) print(M const& C){
using std::cout;
using boost::multi::size;
for(int i = 0; i != size(C); ++i){
for(int j = 0; j != size(C[i]); ++j) cout<< C[i][j] <<' ';
cout<<std::endl;
}
return cout<<std::endl;
}
BOOST_AUTO_TEST_CASE(multi_blas_numeric_real_imag_part){
using complex = std::complex<double>; complex const I{0, 1};
multi::array<double, 2> A = {
{1., 3., 4.},
{9., 7., 1.}
};
multi::array<complex, 2> Acplx = A;
multi::array<complex, 2> B = {
{1. - 3.*I, 6. + 2.*I},
{8. + 2.*I, 2. + 4.*I},
{2. - 1.*I, 1. + 1.*I}
};
multi::array<double, 2> Breal = {
{1., 6.},
{8., 2.},
{2., 1.}
};
multi::array<double, 2> Bimag = {
{-3., +2.},
{+2., +4.},
{-1., +1.}
};
using multi::blas::real;
using multi::blas::imag;
BOOST_REQUIRE( Breal == real(B) );
BOOST_REQUIRE( real(B) == Breal );
BOOST_REQUIRE( imag(B) == Bimag );
BOOST_REQUIRE( B[1][0] == 8. + 2.*I );
BOOST_REQUIRE( B[1][0].imag() == 2. );
// using multi::blas::hermitized;
// BOOST_REQUIRE( hermitized(B)[0][1] == 8. - 2.*I );
// BOOST_REQUIRE( imag(hermitized(B)[0][1]) == -2. );
}
BOOST_AUTO_TEST_CASE(multi_blas_numeric_real_conjugated){
using complex = std::complex<double>; complex const I{0, 1};
multi::array<complex, 2> B = {
{1. - 3.*I, 6. + 2.*I},
{8. + 2.*I, 2. + 4.*I},
{2. - 1.*I, 1. + 1.*I}
};
BOOST_REQUIRE( B[0][0] == 1. - 3.*I );
multi::array<complex, 2> const Bconst = {
{1. - 3.*I, 6. + 2.*I},
{8. + 2.*I, 2. + 4.*I},
{2. - 1.*I, 1. + 1.*I}
};
BOOST_REQUIRE( Bconst[0][0] == 1. - 3.*I );
auto BdataC = multi::blas::make_conjugater(B.data_elements());
auto BconstdataC = multi::blas::make_conjugater(Bconst.data_elements());
decltype(BconstdataC) ppp = BdataC;
ppp = BdataC;
BOOST_REQUIRE( *BdataC == 1. + 3.*I );
// static_assert( multi::blas::is_complex_array<multi::array<thrust::complex<double>, 2>>{}, "!");
static_assert( multi::blas::is_complex_array<decltype(B)>{}, "!");
static_assert(not multi::blas::is_conjugated<decltype(B)>{}, "!");
auto&& Bconj = multi::blas::conj(B);
static_assert(multi::blas::is_conjugated<decltype(Bconj)>{}, "!");
BOOST_REQUIRE( Bconj[0][0] == 1. + 3.*I );
BOOST_TEST_REQUIRE( imag(*base(Bconj)) == +3 );
// BOOST_TEST_REQUIRE( base(Bconj)->imag() == +3 );
BOOST_REQUIRE( rotated(Bconj)[1][0] == Bconj[0][1] );
// BOOST_REQUIRE( base(Bconj) == -3.*I );
static_assert(multi::blas::is_complex_array<decltype(Bconj)>{}, "!");
BOOST_REQUIRE( conj(Bconj) == B );
#if 0
BOOST_REQUIRE( base(conj(Bconj)) == base(B) );
BOOST_REQUIRE( base(conj(Bconj))->imag() == -3. );
// BOOST_REQUIRE( base(conjugated(Bconj))->imag() == -3. );
#endif
BOOST_REQUIRE( multi::blas::conj(B)[1][0] == std::conj(B[1][0]) );
}
#if 0
namespace cuda = multi::cuda;
{
cuda::array<complex, 2> Bgpu = B;
using multi::blas::imag;
BOOST_REQUIRE( imag(Bgpu)[1][1] == imag(B)[1][1] );
BOOST_REQUIRE( real(Bgpu)[1][1] == real(B)[1][1] );
}
{
cuda::managed::array<complex, 2> Bgpu = B;
using multi::blas::imag;
BOOST_REQUIRE( imag(Bgpu)[1][1] == imag(B)[1][1] );
BOOST_REQUIRE( real(Bgpu)[1][1] == real(B)[1][1] );
}
multi::array_ref<double, 2> rB(reinterpret_cast<double*>(data_elements(B)), {size(B), 2*size(*begin(B))});
auto&& Bconj = multi::static_array_cast<complex, multi::blas::detail::conjugater<complex*>>(B);
assert( size(Bconj) == size(B) );
assert( conj(B[1][2]) == Bconj[1][2] );
// auto&& BH = multi::blas::hermitized(B);
// assert( BH[1][2] == conj(B[2][1]) );
// std::cout << BH[1][2] << " " << B[2][1] << std::endl;
// auto&& BH1 = multi::static_array_cast<complex, multi::blas::detail::conjugater<complex*>>(rotated(B));
// auto&& BH2 = rotated(multi::static_array_cast<complex, multi::blas::detail::conjugater<complex*>>(B));
// what( BH1, BH2 );
// using multi::blas::imag;
// assert( real(A)[1][2] == 1. );
// assert( imag(A)[1][2] == -3. );
// print(A) <<"--\n";
// print(real(A)) <<"--\n";
// print(imag(A)) <<"--\n";
multi::array<complex, 2> C({2, 2});
multi::array_ref<double, 2> rC(reinterpret_cast<double*>(data_elements(C)), {size(C), 2*size(*begin(C))});
// gemm('T', 'T', 1., A, B, 0., C);
// gemm('T', 'T', 1., A, B, 0., C);
// gemm('T', 'T', 1., real(A), B, 0., C);
}
#endif
#endif
#endif
|
// Copyright (C) 2014-2015 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#if !defined(HPX_UNORDERED_MAP_NOV_11_2014_0857PM)
#define HPX_UNORDERED_MAP_NOV_11_2014_0857PM
#include <hpx/components/containers/unordered/unordered_map.hpp>
#endif
|
#include<cstdio>
#include<cstring>
#include<cmath>
int val[500],xval[500];
char str[500];
void prepare() {
for(int i = 0,j = 0;i < strlen(str);i++,j++) {
if(str[i] == '.') {
j--;
continue;
}
xval[j] = str[i] - '0';
}
}
bool compare() {
for(int i = 0;i < 500;) {
if(val[i] == xval[i]) {
i++;
}else if(val[i] > xval[i]) {
return true;
}else{
return false;
}
}
return true;
}
void trans(long long key) {
long long father = 1;
for(int i = 0;i < 500;i++) {
val[i] = val[i] + (father / key);
father = (father % key) * 10;
}
for(int i = 499;i > 0;i--) {
if(val[i] > 9) {
val[i - 1] = val[i - 1] + val[i] / 10;
val[i] = val[i] % 10;
}
}
}
int main() {
long long pre = -1;
while(scanf("%s",str) == 1) {
memset(val,0,sizeof val);
memset(xval,0,sizeof xval);
prepare();
long long k = 0;
while(!compare()) {
trans(++k + 1);
}
if(k == 0)
break;
printf("%lld\n",pre == 9 && k == 6 ? 5 : k);//恐怕数据有错吧。。。
pre = k;
}
return 0;
}
|
#include <winapi/gui/windowing-support/Window_owner_handle.hpp>
|
#ifndef OCCA_LANG_PARSER_HEADER
#define OCCA_LANG_PARSER_HEADER
#include <map>
#include <vector>
#include <occa/tools/properties.hpp>
#include <occa/lang/kernelMetadata.hpp>
#include <occa/lang/keyword.hpp>
#include <occa/lang/loaders.hpp>
#include <occa/lang/preprocessor.hpp>
#include <occa/lang/processingStages.hpp>
#include <occa/lang/statement.hpp>
#include <occa/lang/transforms/exprTransform.hpp>
#include <occa/lang/transforms/statementTransform.hpp>
#include <occa/lang/tokenizer.hpp>
#include <occa/lang/tokenContext.hpp>
#include <occa/lang/statementContext.hpp>
#include <occa/lang/statementPeeker.hpp>
#include <occa/lang/variable.hpp>
namespace occa {
namespace lang {
class parser_t;
typedef stream<token_t*> tokenStream;
typedef statement_t* (parser_t::*statementLoader_t)(attributeTokenMap &smntAttributes);
typedef std::map<int, statementLoader_t> statementLoaderMap;
class parser_t {
public:
//---[ Stream ]-------------------
tokenStream stream;
tokenizer_t tokenizer;
preprocessor_t preprocessor;
stringTokenMerger stringMerger;
externTokenMerger externMerger;
newlineTokenFilter newlineFilter;
unknownTokenFilter unknownFilter;
//================================
//---[ Status ]-------------------
blockStatement root;
keywords_t keywords;
statementLoaderMap statementLoaders;
nameToAttributeMap attributeMap;
tokenContext_t tokenContext;
statementContext_t smntContext;
statementPeeker_t smntPeeker;
int loadingStatementType;
bool checkSemicolon;
unknownToken defaultRootToken;
statementPtrVector comments;
attributeTokenMap attributes;
bool success;
//================================
//---[ Misc ]---------------------
occa::properties settings;
qualifier_t *restrictQualifier;
//================================
parser_t(const occa::properties &settings_ = occa::properties());
virtual ~parser_t();
//---[ Customization ]------------
template <class attributeType>
void addAttribute();
virtual void onClear();
virtual void beforePreprocessing();
virtual void beforeParsing();
virtual void afterParsing();
//================================
//---[ Public ]-------------------
virtual bool succeeded() const;
std::string toString() const;
void toString(std::string &s) const;
void writeToFile(const std::string &filename) const;
void setSourceMetadata(sourceMetadata_t &sourceMetadata) const;
//================================
//---[ Setup ]--------------------
void clear();
void clearAttributes();
void clearAttributes(attributeTokenMap &attrs);
void addSettingDefines();
void parseSource(const std::string &source);
void parseFile(const std::string &filename);
void setSource(const std::string &source,
const bool isFile);
void setupLoadTokens();
void loadTokens();
void parseTokens();
//================================
//---[ Helper Methods ]-----------
keyword_t& getKeyword(token_t *token);
keyword_t& getKeyword(const std::string &name);
exprNode* getExpression();
exprNode* getExpression(const int start,
const int end);
void loadComments();
void loadComments(const int start,
const int end);
void pushComments();
void loadAttributes(attributeTokenMap &attrs);
attribute_t* getAttribute(const std::string &name);
void addAttributesTo(attributeTokenMap &attrs,
statement_t *smnt);
void loadBaseType(vartype_t &vartype);
void loadType(vartype_t &vartype);
vartype_t loadType();
bool isLoadingVariable();
bool isLoadingFunction();
bool isLoadingFunctionPointer();
void loadVariable(variable_t &var);
variable_t loadVariable();
void loadVariable(vartype_t &vartype,
variable_t &var);
void loadFunction(function_t &func);
int peek();
//================================
//---[ Type Loaders ]-------------
variableDeclaration loadVariableDeclaration(attributeTokenMap &smntAttributes,
const vartype_t &baseType);
void applyDeclarationSmntAttributes(attributeTokenMap &smntAttributes,
variable_t &var);
int declarationNextCheck(const opType_t opCheck);
void loadDeclarationBitfield(variableDeclaration &decl);
void loadDeclarationAssignment(variableDeclaration &decl);
void loadDeclarationBraceInitializer(variableDeclaration &decl);
//================================
//---[ Statement Loaders ]--------
bool isEmpty();
void loadAllStatements();
statement_t* loadNextStatement();
statement_t* getNextStatement();
statement_t* loadBlockStatement(attributeTokenMap &smntAttributes);
statement_t* loadEmptyStatement(attributeTokenMap &smntAttributes);
statement_t* loadExpressionStatement(attributeTokenMap &smntAttributes);
statement_t* loadDeclarationStatement(attributeTokenMap &smntAttributes);
statement_t* loadNamespaceStatement(attributeTokenMap &smntAttributes);
statement_t* loadFunctionStatement(attributeTokenMap &smntAttributes);
void checkIfConditionStatementExists();
void loadConditionStatements(statementPtrVector &statements,
const int expectedCount);
statement_t* loadConditionStatement();
statement_t* loadIfStatement(attributeTokenMap &smntAttributes);
statement_t* loadElifStatement(attributeTokenMap &smntAttributes);
statement_t* loadElseStatement(attributeTokenMap &smntAttributes);
statement_t* loadForStatement(attributeTokenMap &smntAttributes);
statement_t* loadWhileStatement(attributeTokenMap &smntAttributes);
statement_t* loadDoWhileStatement(attributeTokenMap &smntAttributes);
statement_t* loadSwitchStatement(attributeTokenMap &smntAttributes);
statement_t* loadCaseStatement(attributeTokenMap &smntAttributes);
statement_t* loadDefaultStatement(attributeTokenMap &smntAttributes);
statement_t* loadContinueStatement(attributeTokenMap &smntAttributes);
statement_t* loadBreakStatement(attributeTokenMap &smntAttributes);
statement_t* loadReturnStatement(attributeTokenMap &smntAttributes);
statement_t* loadClassAccessStatement(attributeTokenMap &smntAttributes);
statement_t* loadDirectiveStatement(attributeTokenMap &smntAttributes);
statement_t* loadPragmaStatement(attributeTokenMap &smntAttributes);
statement_t* loadGotoStatement(attributeTokenMap &smntAttributes);
statement_t* loadGotoLabelStatement(attributeTokenMap &smntAttributes);
//================================
};
}
}
#include "parser.tpp"
#endif
|
#include <iostream>
#include <thread>
#include "main.hpp"
int main() {
std::vector<std::vector<int> > a = readImage();
std::vector<std::vector<int> > b = a;
std::vector<std::vector<int> > c = a;
std::vector<std::vector<int> > d = a;
std::vector<std::vector<int> > e = a;
std::vector<std::vector<int> > f = a;
invert(a);
std::thread t1(writeImage, std::ref(a), "invert.pgm");
invert_half(b);
std::thread t2(writeImage, std::ref(b), "inverthalf.pgm");
box(c);
std::thread t3(writeImage, std::ref(c), "box.pgm");
frame(d);
std::thread t4(writeImage, std::ref(d), "frame.pgm");
scale(e);
std::thread t5(writeImage, std::ref(e), "scale.pgm");
pixelate(f);
std::thread t6(writeImage, std::ref(f), "pixel.pgm");
t1.join();
std::cout << "invert.pgm";
std::cout << std::endl;
t2.join();
std::cout << "inverthalf.pgm";
std::cout << std::endl;
t3.join();
std::cout << "box.pgm";
std::cout << std::endl;
t4.join();
std::cout << "frame.pgm";
std::cout << std::endl;
t5.join();
std::cout << "scale.pgm";
std::cout << std::endl;
t6.join();
std::cout << "pixel.pgm";
std::cout << std::endl;
return 0;
}
|
#include "exception.hpp"
#include "basic_types.hpp"
#include <sstream>
namespace bias {
RuntimeError::RuntimeError( const unsigned int error_id, const std::string &what_arg)
: std::runtime_error(what_arg)
{
error_id_ = error_id;
}
unsigned int RuntimeError::id()
{
return error_id_;
}
void throw_ERROR_NO_FC2(std::string prettyFunctionStr)
{
std::stringstream ssError;
ssError << prettyFunctionStr;
ssError << ": FlyCapure2 libary not present";
throw RuntimeError(ERROR_NO_FC2, ssError.str());
}
void throw_ERROR_NO_DC1394(std::string prettyFunctionStr)
{
std::stringstream ssError;
ssError << prettyFunctionStr;
ssError << ": libdc1394 libary not present";
throw RuntimeError(ERROR_NO_DC1394, ssError.str());
}
void throw_ERROR_NO_SPIN(std::string prettyFunctionStr)
{
std::stringstream ssError;
ssError << prettyFunctionStr;
ssError << ": FlyCapure2 libary not present";
throw RuntimeError(ERROR_NO_SPIN, ssError.str());
}
}
|
#pragma once
#include "ParserAction.hpp"
namespace axis { namespace services { namespace language { namespace actions {
class NopAction : public ParserAction
{
public:
virtual void Run( const axis::services::language::parsing::ParseResult& result ) const;
virtual ParserAction& Clone( void ) const;
};
} } } } // namespace axis::services::language::actions
|
#include "delay.h"
#include <chrono>
#include <thread>
void dpsoDelay(int milliseconds)
{
std::this_thread::sleep_for(
std::chrono::milliseconds(milliseconds));
}
|
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/*
* Copyright 2020 Stephane Cuillerdier (aka Aiekick)
*
* 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 "GuiLayout.h"
#include <FileHelper.h>
#include "MainFrame.h"
#include "Res/CustomFont.h"
#include "Gui/ImGuiWidgets.h"
#include "Project/ProjectFile.h"
#include "Panes/OptimizerPane.h"
#include "Panes/SourcePane.h"
#include "Panes/TargetPane.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui_internal.h"
PaneFlags GuiLayout::m_Pane_Shown = PANE_ALLS;
GuiLayout::GuiLayout() = default;
GuiLayout::~GuiLayout() = default;
void GuiLayout::Init()
{
if (!FileHelper::Instance()->IsFileExist("imgui.ini"))
{
m_FirstLayout = true; // need default layout
}
OptimizerPane::Instance()->Init();
SourcePane::Instance()->Init();
TargetPane::Instance()->Init();
}
void GuiLayout::InitAfterFirstDisplay(ImVec2 vSize)
{
if (m_FirstLayout)
{
ApplyInitialDockingLayout(vSize);
m_FirstLayout = false;
}
if (m_FirstStart)
{
// focus after start on "Source Fonts" pane
auto win = ImGui::FindWindowByName(SOURCE_PANE);
if (win)
ImGui::FocusWindow(win);
m_FirstStart = false;
}
}
void GuiLayout::StartDockPane()
{
m_DockSpaceID = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(m_DockSpaceID, ImVec2(0, 0), ImGuiDockNodeFlags_PassthruCentralNode);
}
void GuiLayout::ApplyInitialDockingLayout(ImVec2 vSize)
{
ImGui::DockBuilderRemoveNode(m_DockSpaceID); // Clear out existing layout
ImGui::DockBuilderAddNode(m_DockSpaceID, ImGuiDockNodeFlags_DockSpace); // Add empty node
ImGui::DockBuilderSetNodeSize(m_DockSpaceID, vSize);
float leftWidth = 350.0f;
ImGuiID dockMainID = m_DockSpaceID; // This variable will track the document node, however we are not using it here as we aren't docking anything into it.
ImGuiID dockOptimizerID = ImGui::DockBuilderSplitNode(dockMainID, ImGuiDir_Left, leftWidth / vSize.x, nullptr, &dockMainID);
ImGuiID dockRightID = ImGui::DockBuilderSplitNode(dockMainID, ImGuiDir_Right, 0.5f, nullptr, &dockMainID);
ImGui::DockBuilderDockWindow(OPTIMIZER_PANE, dockOptimizerID);
ImGui::DockBuilderDockWindow(SOURCE_PANE, dockMainID);
ImGui::DockBuilderDockWindow(TARGET_PANE, dockRightID);
ImGui::DockBuilderFinish(m_DockSpaceID);
ShowAndFocusPane(PaneFlags::PANE_SOURCE);
m_Pane_Shown = PaneFlags::PANE_ALLS;
}
void GuiLayout::DisplayMenu(ImVec2 vSize)
{
if (ImGui::BeginMenu(ICON_IGFS_LAYOUT " Layout"))
{
if (ImGui::MenuItem("Default Layout"))
{
ApplyInitialDockingLayout(vSize);
}
ImGui::Separator();
ImGui::MenuItem<PaneFlags>("Show/Hide Optimizer Pane", "", &m_Pane_Shown, PaneFlags::PANE_OPTIMIZER);
ImGui::MenuItem<PaneFlags>("Show/Hide Source Pane", "", &m_Pane_Shown, PaneFlags::PANE_SOURCE);
ImGui::MenuItem<PaneFlags>("Show/Hide Target Pane", "", &m_Pane_Shown, PaneFlags::PANE_TARGET);
ImGui::EndMenu();
}
}
int GuiLayout::DisplayPanes(ProjectFile *vProjectFile, int vWidgetId)
{
vWidgetId = SourcePane::Instance()->DrawPane(vProjectFile, vWidgetId);
vWidgetId = TargetPane::Instance()->DrawPane(vProjectFile, vWidgetId);
vWidgetId = OptimizerPane::Instance()->DrawPane(vProjectFile, vWidgetId);
return vWidgetId;
}
void GuiLayout::ShowAndFocusPane(PaneFlags vPane)
{
m_Pane_Shown = (PaneFlags)(m_Pane_Shown | vPane);
if (vPane == PaneFlags::PANE_OPTIMIZER) ActivePane(OPTIMIZER_PANE);
else if (vPane == PaneFlags::PANE_SOURCE) ActivePane(SOURCE_PANE);
else if (vPane == PaneFlags::PANE_TARGET) ActivePane(TARGET_PANE);
}
bool GuiLayout::IsPaneActive(PaneFlags vPane)
{
if (vPane == PaneFlags::PANE_OPTIMIZER) return IsPaneActive(OPTIMIZER_PANE);
else if (vPane == PaneFlags::PANE_SOURCE) return IsPaneActive(SOURCE_PANE);
else if (vPane == PaneFlags::PANE_TARGET) return IsPaneActive(TARGET_PANE);
return false;
}
bool GuiLayout::IsPaneActive(const char *vlabel)
{
ImGuiWindow* window = ImGui::FindWindowByName(vlabel);
if (window)
{
return window->DockTabIsVisible;
}
return false;
}
void GuiLayout::ActivePane(const char *vlabel)
{
ImGuiWindow* window = ImGui::FindWindowByName(vlabel);
if (window)
{
if(!window->DockTabIsVisible)
ImGui::FocusWindow(window);
}
}
///////////////////////////////////////////////////////
//// CONFIGURATION ////////////////////////////////////
///////////////////////////////////////////////////////
std::string GuiLayout::getXml(const std::string& vOffset)
{
std::string str;
str += vOffset + "<layout>\n";
str += vOffset + "\t<panes value=\"" + ct::ivariant(m_Pane_Shown).getS() + "\"/>\n";
str += vOffset + "</layout>\n";
return str;
}
void GuiLayout::setFromXml(tinyxml2::XMLElement* vElem, tinyxml2::XMLElement* vParent)
{
// The value of this child identifies the name of this element
std::string strName = "";
std::string strValue = "";
std::string strParentName = "";
strName = vElem->Value();
if (vElem->GetText())
strValue = vElem->GetText();
if (vParent != 0)
strParentName = vParent->Value();
if (strParentName == "layout")
{
auto att = vElem->FirstAttribute();
if (att && std::string(att->Name()) == "value")
{
strValue = att->Value();
if (strName == "panes") m_Pane_Shown = (PaneFlags)ct::ivariant(strValue).getI();
}
}
}
|
/*
* Hamiltonian.cpp
*
* Created on: Oct 9, 2016
* Author: zxi
*/
#include "GraphTSP.h"
#include <iostream>
#include <fstream>
#include <assert.h>
#include <random> // std::default_random_engine
#include <map>
#include <sstream>
#include <cstdlib>
//#include <opencv2/imgproc.hpp>
using namespace std;
//#include "mathtool/Box.h"
#include "tsp_writer.h"
int TSP_SEED=0;
void GraphTSP::FindTSPConcorde(vector< vector< int > > & matrix, //the graph
vector<GraphTSP::TSPPath> &paths, //output
const int max_paths)
{
vector<string> path_strings;
const string tsp_file_path = "pcover.tsp";
TSPWriter tsp_writer;
tsp_writer.WriteTSP(tsp_file_path,matrix);
string binary_posfix;
#ifdef _WIN32
binary_posfix = ".exe";
#elif __APPLE__
binary_posfix = ".osx";
#elif __linux__
binary_posfix = ".linux64";
#endif
const string path_to_solver = "./tsp/concorde/concorde" + binary_posfix;
const int max_failed_attempts=500;
int failed_attempts=0;
srand(TSP_SEED);
for (int i = 0; i < 100 * max_paths; ++i)
{
if(failed_attempts>=max_failed_attempts) break;
const string clock_str = std::to_string(std::rand()); //clock());
//cout<<"clock_str="<<clock_str<<endl;
const string solution_path = "tsp_solution_" + clock_str + ".txt";
const string cmd_output = "tsp_solution_" + clock_str + "_dump.txt";
const string init_upper_bound = std::to_string(matrix.size());
const map<string, string> args = { /***** {Key, Value} ******/
//{ "-q", "" }, /* do not cut the root lp */
{ "-x", "" }, /* delete files on completion (sav pul mas) */
{ "-V", "" }, /* just run fast cuts */
{ "-u", init_upper_bound }, /* init upperbound */
{ "-s", clock_str }, /* random seed */
{ "-o", solution_path } /* solution pah */
};
string paramters;
for (const auto& kv : args) {
paramters += kv.first + " " + kv.second + " ";
}
paramters += tsp_file_path;
string command = path_to_solver + " " + paramters;
//cerr << "[concorde] Running command: " << command << endl;
// Run external solver
command=command+" &> "+cmd_output;
int rtn = system(command.c_str());
std::remove(cmd_output.c_str());
ifstream in(solution_path);
if (!in.good()) {
cerr << "[concorde] !Error: Failed to solve the TSP problem!" << endl;
continue;
}
int n;
in >> n;
assert(n == matrix.size());
int node;
TSPPath path;
for (int i = 0; i < n; ++i) {
in >> node;
path.push_back( make_pair(node,0) );
}
//update weights
for(auto it=path.begin(); it!=path.end(); it++)
{
auto next=it; next++;
if(next==path.end()) next=path.begin();
it->second = matrix[it->first][next->first];
}
//check if the path is unique
string ps = toString(path);
//cout<<"ps="<<ps<<endl;
bool found=false;
for(string & ps2 : path_strings)
{
if(ps2==ps){ found=true; break; }
}
// Delete the solution file.
std::remove(solution_path.c_str());
if(found) {
//cout<<"- found duplicates: "<<ps<<endl;
failed_attempts++;
continue; //duplicated path
}
cout<<"."<<flush;
paths.push_back(path);
path_strings.push_back(ps);
failed_attempts=0;
if (paths.size() >= max_paths)
break;
}
cout<<endl;
//std::remove(tsp_file_path.c_str());
//cout<<"TSP DONE: "<<paths.size()<<" paths found"<<endl;
return;
}
string GraphTSP::toString(GraphTSP::TSPPath& path)
{
std::stringstream ss;
for(auto& n : path) ss<<n.first<<"-";
return ss.str();
}
///////////////////////////////////////////////////
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<cstdlib>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#define ri register int
#define ll long long
using namespace std;
int T;
ll n,Min;
inline int getint()
{
int num=0,bj=1;
char c=getchar();
while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(isdigit(c))num=num*10+c-'0',c=getchar();
return num*bj;
}
inline ll getll()
{
ll num=0;int bj=1;
char c=getchar();
while(!isdigit(c))bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(isdigit(c))num=num*10+c-'0',c=getchar();
return num*bj;
}
inline ll gcd(ll a,ll b){return (!b)?a:gcd(b,a%b);}
inline ll Multi(ll a,ll b,ll Mod)
{
ll ret=0,base=a;
while(b)
{
if(b&1)ret=(ret+base)%Mod;
base=(base+base)%Mod;
b>>=1;
}
return ret;
}
inline ll Pow(ll a,ll b,ll Mod)
{
ll ret=1,base=a;
while(b)
{
if(b&1)ret=Multi(ret,base,Mod)%Mod;
base=Multi(base,base,Mod)%Mod;
b>>=1;
}
return ret;
}
inline ll Sec_Det(ll a,ll n)
{
ll d=n-1,cnt=0;//d为偶数
while(!(d&1))d>>=1,cnt++;//直到d为奇数
ll x=Pow(a,d,n);
if(x==1||x==n-1)return 0;
for(ll i=1;i<=cnt;i++)
{
x=Multi(x,x,n);
if(x==n-1)return 0;
}
return 1;
}
inline bool Miller_Rabin(ll n)
{
if(n==2)return 1;
if(n==1||!(n&1))return 0;
for(ri i=1;i<=5;i++)
{
ll a=(ll)(rand()%(n-1)+1);
if(Sec_Det(a,n))return 0;
}
return 1;
}
inline ll Pollard_Rho(ll n,int c)
{
ll x,y,d,k=2;
x=rand()%(n-1)+1,y=x;
for(ll i=1;;i++)
{
x=(Multi(x,x,n)+c)%n;
d=gcd(y-x,n);
if(1<d&&d<n)return d;
if(y==x)return n;//找到循环,x选择失败
if(i==k)y=x,k<<=1;//优化
}
}
inline void FindFac(ll n,int k)
{
if(n==1)return;
if(Miller_Rabin(n))
{
Min=n<Min?n:Min;
return;
}
ll p=n;
while(p>=n)p=Pollard_Rho(p,k--);
FindFac(p,k);
FindFac(n/p,k);
}
int main()
{
srand(time(NULL));
T=getint();
while(T--)
{
Min=n=getll();
if(Miller_Rabin(n))printf("Prime\n");
else
{
FindFac(n,10007);
printf("%lld\n",Min);
}
}
return 0;
}
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace game {
enum class GodModeType : uint32_t
{
Invulnerable = 0,
Immortal = 1,
Mortal = 3,
};
} // namespace game
} // namespace RED4ext
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pubkey.h"
#include "eccryptoverify.h"
#ifdef USE_SECP256K1
#include <secp256k1.h>
#else
#include "ecwrapper.h"
#endif
bool CPubKey::Verify(const uint256& hash, const std::vector<unsigned char>& vchSig) const
{
if (!IsValid())
return false;
#ifdef USE_SECP256K1
if (secp256k1_ecdsa_verify((const unsigned char*)&hash, 32, &vchSig[0], vchSig.size(), begin(), size()) != 1)
return false;
#else
CECKey key;
if (!key.SetPubKey(begin(), size()))
return false;
if (!key.Verify(hash, vchSig))
return false;
#endif
return true;
}
bool CPubKey::RecoverCompact(const uint256& hash, const std::vector<unsigned char>& vchSig)
{
if (vchSig.size() != 65)
return false;
int recid = (vchSig[0] - 27) & 3;
bool fComp = ((vchSig[0] - 27) & 4) != 0;
#ifdef USE_SECP256K1
int pubkeylen = 65;
if (!secp256k1_ecdsa_recover_compact((const unsigned char*)&hash, 32, &vchSig[1], (unsigned char*)begin(), &pubkeylen, fComp, recid))
return false;
assert((int)size() == pubkeylen);
#else
CECKey key;
if (!key.Recover(hash, &vchSig[1], recid))
return false;
std::vector<unsigned char> pubkey;
key.GetPubKey(pubkey, fComp);
Set(pubkey.begin(), pubkey.end());
#endif
return true;
}
bool CPubKey::IsFullyValid() const
{
if (!IsValid())
return false;
#ifdef USE_SECP256K1
if (!secp256k1_ecdsa_pubkey_verify(begin(), size()))
return false;
#else
CECKey key;
if (!key.SetPubKey(begin(), size()))
return false;
#endif
return true;
}
bool CPubKey::Decompress()
{
if (!IsValid())
return false;
#ifdef USE_SECP256K1
int clen = size();
int ret = secp256k1_ecdsa_pubkey_decompress((unsigned char*)begin(), &clen);
assert(ret);
assert(clen == (int)size());
#else
CECKey key;
if (!key.SetPubKey(begin(), size()))
return false;
std::vector<unsigned char> pubkey;
key.GetPubKey(pubkey, false);
Set(pubkey.begin(), pubkey.end());
#endif
return true;
}
bool CPubKey::Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const
{
assert(IsValid());
assert((nChild >> 31) == 0);
assert(begin() + 33 == end());
unsigned char out[64];
BIP32Hash(cc, nChild, *begin(), begin() + 1, out);
memcpy(ccChild, out + 32, 32);
#ifdef USE_SECP256K1
pubkeyChild = *this;
bool ret = secp256k1_ecdsa_pubkey_tweak_add((unsigned char*)pubkeyChild.begin(), pubkeyChild.size(), out);
#else
CECKey key;
bool ret = key.SetPubKey(begin(), size());
ret &= key.TweakPublic(out);
std::vector<unsigned char> pubkey;
key.GetPubKey(pubkey, true);
pubkeyChild.Set(pubkey.begin(), pubkey.end());
#endif
return ret;
}
void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
{
code[0] = nDepth;
memcpy(code + 1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF;
code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF;
code[8] = (nChild >> 0) & 0xFF;
memcpy(code + 9, vchChainCode, 32);
assert(pubkey.size() == 33);
memcpy(code + 41, pubkey.begin(), 33);
}
void CExtPubKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
{
nDepth = code[0];
memcpy(vchFingerprint, code + 1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(vchChainCode, code + 9, 32);
pubkey.Set(code + 41, code + 74);
}
bool CExtPubKey::Derive(CExtPubKey& out, unsigned int nChild) const
{
out.nDepth = nDepth + 1;
CKeyID id = pubkey.GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = nChild;
return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode);
}
|
/*
* Copyright 2012 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
/*
* This class gathers together all the test cases for the gr-filter
* directory into a single test suite. As you create new test cases,
* add them here.
*/
#include "qa_deinterleaver.h"
CppUnit::TestSuite *
qa_deinterleaver::suite()
{
CppUnit::TestSuite *s = new CppUnit::TestSuite("deinterleaver");
return s;
}
|
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> m;
bool saw_single_char = false;
int total = 0;
for(char ch: s) m[ch]++;
for(auto &x: m) {
if(x.second % 2 == 0) total += x.second;
else {
total += x.second - 1;
saw_single_char = true;
}
}
return saw_single_char ? total + 1 : total;
}
};
|
#include "cross_validation.h"
#include "train_model.h"
#include "preprocess.h"
#include <catboost/libs/algo/train.h>
#include <catboost/libs/algo/helpers.h>
#include <catboost/libs/metrics/metric.h>
#include <catboost/libs/loggers/logger.h>
#include <catboost/libs/helpers/data_split.h>
#include <catboost/libs/helpers/query_info_helper.h>
#include <catboost/libs/helpers/element_range.h>
#include <catboost/libs/helpers/binarize_target.h>
#include <catboost/libs/helpers/restorable_rng.h>
#include <catboost/libs/helpers/permutation.h>
#include <catboost/libs/helpers/vector_helpers.h>
#include <catboost/libs/overfitting_detector/error_tracker.h>
#include <catboost/libs/options/plain_options_helper.h>
#include <util/random/shuffle.h>
#include <limits>
#include <cmath>
static TVector<TVector<size_t>> GetSplittedDocs(const TVector<std::pair<size_t, size_t>>& startEnd) {
TVector<TVector<size_t>> result(startEnd.ysize());
for (int fold = 0; fold < result.ysize(); ++fold) {
int foldStartIndex = startEnd[fold].first;
int foldEndIndex = startEnd[fold].second;
result[fold].reserve(foldEndIndex - foldStartIndex);
for (int idx = foldStartIndex; idx < foldEndIndex; ++idx) {
result[fold].push_back(idx);
}
}
return result;
}
static TVector<TVector<size_t>> CalcTrainDocs(const TVector<TVector<size_t>>& testDocs, int docCount) {
TVector<TVector<size_t>> result(testDocs.size());
for (int fold = 0; fold < result.ysize(); ++fold) {
result[fold].reserve(docCount - testDocs[fold].ysize());
for (int testFold = 0; testFold < testDocs.ysize(); ++testFold) {
if (testFold == fold) {
continue;
}
for (auto doc : testDocs[testFold]) {
result[fold].push_back(doc);
}
}
}
return result;
}
static void PopulateData(const TPool& pool,
const TVector<size_t>& indices,
TDataset* learnOrTestData) {
auto& data = *learnOrTestData;
const TDocumentStorage& docStorage = pool.Docs;
data.Target.yresize(indices.size());
data.Weights.yresize(indices.size());
for (size_t i = 0; i < indices.size(); ++i) {
data.Target[i] = docStorage.Target[indices[i]];
data.Weights[i] = docStorage.Weight[indices[i]];
}
for (int dim = 0; dim < docStorage.GetBaselineDimension(); ++dim) {
data.Baseline[dim].yresize(indices.size());
for (size_t i = 0; i < indices.size(); ++i) {
data.Baseline[dim][i] = docStorage.Baseline[dim][indices[i]];
}
}
if (!docStorage.QueryId.empty()) {
data.QueryId.yresize(indices.size());
for (size_t i = 0; i < indices.size(); ++i) {
data.QueryId[i] = docStorage.QueryId[indices[i]];
}
}
if (!docStorage.SubgroupId.empty()) {
data.SubgroupId.yresize(indices.size());
for (size_t i = 0; i < indices.size(); ++i) {
data.SubgroupId[i] = docStorage.SubgroupId[indices[i]];
}
}
UpdateQueriesInfo(data.QueryId, data.SubgroupId, 0, data.GetSampleCount(), &data.QueryInfo);
};
static void PrepareFolds(
const NCatboostOptions::TLossDescription& lossDescription,
const TPool& pool,
const TVector<THolder<TLearnContext>>& contexts,
const TCrossValidationParams& cvParams,
TVector<TDataset>* folds,
TVector<TDataset>* testFolds
) {
bool hasQuery = !pool.Docs.QueryId.empty();
if (hasQuery) {
CB_ENSURE(!cvParams.Stratified, "Stratified cross validation is not supported for datasets with query id.");
}
TVector<TVector<size_t>> docsInTest;
TVector<std::pair<size_t, size_t>> testDocsStartEndIndices;
if (cvParams.Stratified) {
CB_ENSURE(!IsQuerywiseError(lossDescription.GetLossFunction()), "Stratified CV isn't supported for querywise errors");
docsInTest = StratifiedSplit(pool.Docs.Target, cvParams.FoldCount);
} else {
testDocsStartEndIndices = hasQuery
? Split(pool.Docs.GetDocCount(), pool.Docs.QueryId, cvParams.FoldCount)
: Split(pool.Docs.GetDocCount(), cvParams.FoldCount);
docsInTest = GetSplittedDocs(testDocsStartEndIndices);
}
const int docCount = pool.Docs.GetDocCount();
TVector<TVector<size_t>> docsInTrain = CalcTrainDocs(docsInTest, docCount);
if (cvParams.Inverted) {
docsInTest.swap(docsInTrain);
}
TVector<size_t> docIndices;
docIndices.reserve(docCount);
for (size_t foldIdx = 0; foldIdx < cvParams.FoldCount; ++foldIdx) {
TDataset learnData;
TDataset testData;
docIndices.clear();
docIndices.insert(docIndices.end(), docsInTrain[foldIdx].begin(), docsInTrain[foldIdx].end());
docIndices.insert(docIndices.end(), docsInTest[foldIdx].begin(), docsInTest[foldIdx].end());
PopulateData(pool, docsInTrain[foldIdx], &learnData);
PopulateData(pool, docsInTest[foldIdx], &testData);
if (!pool.Pairs.empty()) {
int testDocsBegin = testDocsStartEndIndices[foldIdx].first;
int testDocsEnd = testDocsStartEndIndices[foldIdx].second;
SplitPairsAndReindex(pool.Pairs, testDocsBegin, testDocsEnd, &learnData.Pairs, &testData.Pairs);
}
UpdateQueriesPairs(learnData.Pairs, /*invertedPermutation=*/{}, &learnData.QueryInfo);
UpdateQueriesPairs(testData.Pairs, /*invertedPermutation=*/{}, &testData.QueryInfo);
const TVector<float>& classWeights = contexts[foldIdx]->Params.DataProcessingOptions->ClassWeights;
Preprocess(lossDescription, classWeights, learnData);
Preprocess(lossDescription, classWeights, testData);
PrepareAllFeaturesLearn(
contexts[foldIdx]->CatFeatures,
contexts[foldIdx]->LearnProgress.FloatFeatures,
contexts[foldIdx]->Params.DataProcessingOptions->IgnoredFeatures,
/*ignoreRedundantFeatures=*/true,
(size_t)contexts[foldIdx]->Params.CatFeatureParams->OneHotMaxSize,
contexts[foldIdx]->Params.DataProcessingOptions->FloatFeaturesBinarization->NanMode,
/*clearPool=*/false,
contexts[foldIdx]->LocalExecutor,
docsInTrain[foldIdx],
&pool.Docs,
&learnData.AllFeatures
);
PrepareAllFeaturesTest(
contexts[foldIdx]->CatFeatures,
contexts[foldIdx]->LearnProgress.FloatFeatures,
learnData.AllFeatures,
contexts[foldIdx]->Params.DataProcessingOptions->FloatFeaturesBinarization->NanMode,
/*clearPool=*/false,
contexts[foldIdx]->LocalExecutor,
docsInTest[foldIdx],
&pool.Docs,
&testData.AllFeatures
);
CheckConsistency(lossDescription, learnData, testData);
folds->push_back(learnData);
testFolds->push_back(testData);
}
}
static double ComputeStdDev(const TVector<double>& values, double avg) {
double sqrSum = 0.0;
for (double value : values) {
sqrSum += Sqr(value - avg);
}
return std::sqrt(sqrSum / (values.size() - 1));
}
static TCVIterationResults ComputeIterationResults(
const TVector<double>& trainErrors,
const TVector<double>& testErrors,
size_t foldCount
) {
TCVIterationResults cvResults;
cvResults.AverageTrain = Accumulate(trainErrors.begin(), trainErrors.end(), 0.0) / foldCount;
cvResults.StdDevTrain = ComputeStdDev(trainErrors, cvResults.AverageTrain);
cvResults.AverageTest = Accumulate(testErrors.begin(), testErrors.end(), 0.0) / foldCount;
cvResults.StdDevTest = ComputeStdDev(testErrors, cvResults.AverageTest);
return cvResults;
}
static TVector<const TLearnContext*> GetRawPointers(const TVector<THolder<TLearnContext>>& contexts) {
TVector<const TLearnContext*> pointerContexts;
pointerContexts.reserve(contexts.size());
for (auto& ctx : contexts) {
pointerContexts.push_back(ctx.Get());
}
return pointerContexts;
}
void CrossValidate(
const NJson::TJsonValue& plainJsonParams,
const TMaybe<TCustomObjectiveDescriptor>& objectiveDescriptor,
const TMaybe<TCustomMetricDescriptor>& evalMetricDescriptor,
TPool& pool,
const TCrossValidationParams& cvParams,
TVector<TCVResult>* results
) {
NJson::TJsonValue jsonParams;
NJson::TJsonValue outputJsonParams;
NCatboostOptions::PlainJsonToOptions(plainJsonParams, &jsonParams, &outputJsonParams);
NCatboostOptions::TOutputFilesOptions outputFileOptions(ETaskType::CPU);
outputFileOptions.Load(outputJsonParams);
CB_ENSURE(pool.Docs.GetDocCount() != 0, "Pool is empty");
CB_ENSURE(pool.Docs.GetDocCount() > cvParams.FoldCount, "Pool is too small to be split into folds");
const int featureCount = pool.Docs.GetFactorsCount();
TVector<THolder<TLearnContext>> contexts;
contexts.reserve(cvParams.FoldCount);
for (size_t idx = 0; idx < cvParams.FoldCount; ++idx) {
contexts.emplace_back(new TLearnContext(
jsonParams,
objectiveDescriptor,
evalMetricDescriptor,
outputFileOptions,
featureCount,
pool.CatFeatures,
pool.FeatureId,
"fold_" + ToString(idx) + "_"
));
}
// TODO(kirillovs): All contexts are created equally, the difference is only in
// learn progress. Its better to have TCommonContext as a field in TLearnContext
// without fields duplication.
auto& ctx = contexts.front();
SetLogingLevel(ctx->Params.LoggingLevel);
auto loggingGuard = Finally([&] { SetSilentLogingMode(); });
if (IsMultiClassError(ctx->Params.LossFunctionDescription->GetLossFunction())) {
for (const auto& context : contexts) {
context->LearnProgress.ApproxDimension = GetClassesCount(
pool.Docs.Target,
static_cast<int>(context->Params.DataProcessingOptions->ClassesCount)
);
}
}
TVector<THolder<IMetric>> metrics = CreateMetrics(
ctx->Params.LossFunctionDescription,
ctx->Params.MetricOptions,
ctx->EvalMetricDescriptor,
ctx->LearnProgress.ApproxDimension
);
bool hasQuerywiseMetric = false;
for (const auto& metric : metrics) {
if (metric.Get()->GetErrorType() == EErrorType::QuerywiseError) {
hasQuerywiseMetric = true;
}
}
if (hasQuerywiseMetric) {
CB_ENSURE(pool.Docs.QueryId.size() == pool.Docs.Target.size(), "Query ids not provided for querywise metric.");
}
TRestorableFastRng64 rand(cvParams.PartitionRandSeed);
TVector<ui64> indices(pool.Docs.GetDocCount(), 0);
std::iota(indices.begin(), indices.end(), 0);
if (cvParams.Shuffle) {
Shuffle(pool.Docs.QueryId, rand, &indices);
}
ApplyPermutation(InvertPermutation(indices), &pool, &ctx->LocalExecutor);
auto permutationGuard = Finally([&] { ApplyPermutation(indices, &pool, &ctx->LocalExecutor); });
TVector<TFloatFeature> floatFeatures;
GenerateBorders(pool, ctx.Get(), &floatFeatures);
for (size_t i = 0; i < cvParams.FoldCount; ++i) {
contexts[i]->LearnProgress.FloatFeatures = floatFeatures;
}
TVector<TDataset> learnFolds;
TVector<TDataset> testFolds;
PrepareFolds(ctx->Params.LossFunctionDescription.Get(), pool, contexts, cvParams, &learnFolds, &testFolds);
for (size_t foldIdx = 0; foldIdx < learnFolds.size(); ++foldIdx) {
contexts[foldIdx]->InitContext(learnFolds[foldIdx], &testFolds[foldIdx]);
}
for (size_t foldIdx = 0; foldIdx < learnFolds.size(); ++foldIdx) {
TLearnContext& ctx = *contexts[foldIdx];
if (IsSamplingPerTree(ctx.Params.ObliviousTreeOptions.Get())) {
ctx.SmallestSplitSideDocs.Create(ctx.LearnProgress.Folds);
ctx.PrevTreeLevelStats.Create(
ctx.LearnProgress.Folds,
CountNonCtrBuckets(CountSplits(ctx.LearnProgress.FloatFeatures), learnFolds[foldIdx].AllFeatures.OneHotValues),
static_cast<int>(ctx.Params.ObliviousTreeOptions->MaxDepth)
);
}
ctx.SampledDocs.Create(
ctx.LearnProgress.Folds,
GetBernoulliSampleRate(ctx.Params.ObliviousTreeOptions->BootstrapConfig)
); // TODO(espetrov): create only if sample rate < 1
}
EMetricBestValue bestValueType;
float bestPossibleValue;
metrics.front()->GetBestValue(&bestValueType, &bestPossibleValue);
TErrorTracker errorTracker = BuildErrorTracker(bestValueType, bestPossibleValue, /* hasTest */ true, ctx.Get());
results->reserve(metrics.size());
for (const auto& metric : metrics) {
TCVResult result;
result.Metric = metric->GetDescription();
results->push_back(result);
}
TLogger logger;
TString learnToken = "learn";
TString testToken = "test";
if (ctx->OutputOptions.AllowWriteFiles()) {
TVector<TString> learnSetNames, testSetNames;
for (const auto& x : GetRawPointers(contexts)) {
learnSetNames.push_back(x->Files.NamesPrefix + learnToken);
testSetNames.push_back(x->Files.NamesPrefix + testToken);
}
AddFileLoggers(
/*detailedProfile=*/false,
ctx->Files.LearnErrorLogFile,
ctx->Files.TestErrorLogFile,
ctx->Files.TimeLeftLogFile,
ctx->Files.JsonLogFile,
ctx->Files.ProfileLogFile,
ctx->OutputOptions.GetTrainDir(),
GetJsonMeta(
ctx->Params.BoostingOptions->IterationCount.Get(),
ctx->OutputOptions.GetName(),
GetConstPointers(metrics),
learnSetNames,
testSetNames,
ELaunchMode::CV),
ctx->OutputOptions.GetMetricPeriod(),
&logger
);
}
AddConsoleLogger(
learnToken,
testToken,
/*hasTrain=*/true,
/*hasTest=*/true,
ctx->OutputOptions.GetMetricPeriod(),
&logger
);
TProfileInfo& profile = ctx->Profile;
for (ui32 iteration = 0; iteration < ctx->Params.BoostingOptions->IterationCount; ++iteration) {
profile.StartNextIteration();
for (size_t foldIdx = 0; foldIdx < learnFolds.size(); ++foldIdx) {
TrainOneIteration(learnFolds[foldIdx], &testFolds[foldIdx], contexts[foldIdx].Get());
CalcErrors(learnFolds[foldIdx], testFolds[foldIdx], metrics, contexts[foldIdx].Get());
}
TOneInterationLogger oneIterLogger(logger);
for (size_t metricIdx = 0; metricIdx < metrics.size(); ++metricIdx) {
const auto& metric = metrics[metricIdx];
TVector<double> trainFoldsMetric;
TVector<double> testFoldsMetric;
for (size_t foldIdx = 0; foldIdx < learnFolds.size(); ++foldIdx) {
trainFoldsMetric.push_back(contexts[foldIdx]->LearnProgress.LearnErrorsHistory.back()[metricIdx]);
oneIterLogger.OutputMetric(
contexts[foldIdx]->Files.NamesPrefix + learnToken,
TMetricEvalResult(metric->GetDescription(), trainFoldsMetric.back(), metricIdx == 0)
);
testFoldsMetric.push_back(contexts[foldIdx]->LearnProgress.TestErrorsHistory.back()[metricIdx]);
oneIterLogger.OutputMetric(
contexts[foldIdx]->Files.NamesPrefix + testToken,
TMetricEvalResult(metric->GetDescription(), testFoldsMetric.back(), metricIdx == 0)
);
}
TCVIterationResults cvResults = ComputeIterationResults(trainFoldsMetric, testFoldsMetric, learnFolds.size());
(*results)[metricIdx].AppendOneIterationResults(cvResults);
if (metricIdx == 0) {
TVector<double> valuesToLog;
errorTracker.AddError(cvResults.AverageTest, iteration, &valuesToLog);
}
oneIterLogger.OutputMetric(learnToken, TMetricEvalResult(metric->GetDescription(), cvResults.AverageTrain, metricIdx == 0));
oneIterLogger.OutputMetric(
testToken,
TMetricEvalResult(
metric->GetDescription(),
cvResults.AverageTest,
errorTracker.GetBestError(),
errorTracker.GetBestIteration(),
metricIdx == 0
)
);
}
profile.FinishIteration();
oneIterLogger.OutputProfile(profile.GetProfileResults());
if (errorTracker.GetIsNeedStop()) {
MATRIXNET_NOTICE_LOG << "Stopped by overfitting detector "
<< " (" << errorTracker.GetOverfittingDetectorIterationsWait() << " iterations wait)" << Endl;
break;
}
}
}
|
#include <iostream>
#include <stdlib.h>
using namespace std;
extern void productosOptica(int opcion);
extern void imprimirFactura();
void menu(){
system("color F2");
cout << endl;
cout << "\t\t\t\t===============================" << endl;
cout << "\t\t\t\t\tOPTICA OMEGA VISION" << endl;
cout << "\t\t\t\t===============================" << endl;
cout << "Bienvenido al menu de opciones. Por favor elegir una opcion. " << endl;
int opcion = 0;
cout << endl;
while(true){
system("cls");
cout << endl;
cout << "\t\t\t\t-----------------------------" << endl;
cout << "\t\t\t\t1- Aros." << endl;
cout << "\t\t\t\t2- Lentes Graduados." << endl;
cout << "\t\t\t\t3- Estuches." << endl;
cout << "\t\t\t\t4- Lentes de Contacto." << endl;
cout << "\t\t\t\t5- Pedir Factura." << endl;
cout << "\t\t\t\t6- Salir del sistema." << endl;
cout << "\t\t\t\t-----------------------------" << endl;
cout << endl;
cout << "\t\t\tDigite la opcion con su numero correspondiente = "; cin >> opcion;
cout << endl;
if (opcion == 5){
imprimirFactura();
break;
}
if(opcion == 6){
cout << "Gracias Por Visitarnos! Por Favor Vuelva Pronto :D" << endl;
break;
}
else{
productosOptica(opcion);
}
}
}
|
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
#include <QRegExp>
#include <QRegExpValidator>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
// this->setStyleSheet("background-color: #ceffee;");
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
ui->tabWindow->setVisible(false);
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting OperaCoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting OperaCoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
|
/**
* Copyright (C) 2016-2019 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://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.
*/
/**
* Copyright (C) 2015 Xilinx, Inc
*/
#include "shim.h"
#include "core/common/system.h"
#include "core/common/device.h"
xclDeviceHandle xclOpen(unsigned deviceIndex, const char *logfileName, xclVerbosityLevel level)
{
xclDeviceInfo2 info;
std::strcpy(info.mName, "xilinx:pcie-hw-em:7v3:1.0");
info.mMagic = 0X586C0C6C;
info.mHALMajorVersion = XCLHAL_MAJOR_VER;
info.mHALMinorVersion = XCLHAL_MINOR_VER;
info.mMinTransferSize = 32;
info.mVendorId = 0x10ee;
info.mDeviceId = 0x0000;
info.mSubsystemId = 0xffff;
info.mSubsystemVendorId = 0x0000;
info.mDeviceVersion = 0x0000;
info.mDDRSize = xclemulation::MEMSIZE_4G;
info.mDataAlignment = DDR_BUFFER_ALIGNMENT;
info.mDDRBankCount = 1;
for(unsigned int i = 0; i < 4 ;i++)
info.mOCLFrequency[i] = 200;
#if defined(__aarch64__)
info.mNumCDMA = 1;
#else
info.mNumCDMA = 0;
#endif
std::string deviceName("edge");
std::ifstream mVBNV;
mVBNV.open("/etc/xocl.txt");
if (mVBNV.is_open()) {
mVBNV >> deviceName;
}
mVBNV.close();
std::size_t length = deviceName.copy(info.mName, deviceName.length(), 0);
info.mName[length] = '\0';
std::list<xclemulation::DDRBank> DDRBankList;
xclemulation::DDRBank bank;
bank.ddrSize = xclemulation::MEMSIZE_4G;
DDRBankList.push_back(bank);
FeatureRomHeader fRomHeader;
std::memset(&fRomHeader, 0, sizeof(FeatureRomHeader));
xclcpuemhal2::CpuemShim *handle = nullptr;
bool bDefaultDevice = false;
std::map<unsigned int, xclcpuemhal2::CpuemShim*>::iterator it = xclcpuemhal2::devices.find(deviceIndex);
if(it != xclcpuemhal2::devices.end())
{
handle = (*it).second;
}
else
{
handle = new xclcpuemhal2::CpuemShim(deviceIndex,info,DDRBankList,false,false,fRomHeader);
bDefaultDevice = true;
}
if (!xclcpuemhal2::CpuemShim::handleCheck(handle)) {
delete handle;
handle = 0;
}
if (handle) {
handle->xclOpen(logfileName);
if (bDefaultDevice)
{
std::string sDummyDeviceMsg = "INFO: [SW-EM 09-0] Unable to find emconfig.json. Using default device.";
if (xclemulation::config::getInstance()->isInfosToBePrintedOnConsole())
std::cout << sDummyDeviceMsg << std::endl;
}
}
return (xclDeviceHandle *)handle;
}
void xclClose(xclDeviceHandle handle)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return ;
drv->xclClose();
if (xclcpuemhal2::CpuemShim::handleCheck(handle) && xclcpuemhal2::devices.size() == 0) {
delete ((xclcpuemhal2::CpuemShim*)handle);
}
}
int xclGetDeviceInfo2(xclDeviceHandle handle, xclDeviceInfo2 *info)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclGetDeviceInfo2(info);
}
int xclLoadXclBin(xclDeviceHandle handle, const xclBin *buffer)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
auto ret = drv->xclLoadXclBin(buffer);
if (!ret) {
auto device = xrt_core::get_userpf_device(drv);
device->register_axlf(buffer);
if (xclemulation::is_sw_emulation() && xrt_core::config::get_flag_kds_sw_emu())
ret = xrt_core::scheduler::init(handle, buffer);
}
return ret;
}
uint64_t xclAllocDeviceBuffer(xclDeviceHandle handle, size_t size)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclAllocDeviceBuffer(size);
}
uint64_t xclAllocDeviceBuffer2(xclDeviceHandle handle, size_t size, xclMemoryDomains domain,
unsigned flags)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
bool p2pBuffer = false;
std::string fileName("");
return drv->xclAllocDeviceBuffer2(size, domain, flags,p2pBuffer,fileName);
}
void xclFreeDeviceBuffer(xclDeviceHandle handle, uint64_t buf)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return;
return drv->xclFreeDeviceBuffer(buf);
}
size_t xclCopyBufferHost2Device(xclDeviceHandle handle, uint64_t dest, const void *src, size_t size, size_t seek)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclCopyBufferHost2Device(dest, src, size, seek);
}
size_t xclCopyBufferDevice2Host(xclDeviceHandle handle, void *dest, uint64_t src, size_t size, size_t skip)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclCopyBufferDevice2Host(dest, src, size, skip);
}
size_t xclWrite(xclDeviceHandle handle, xclAddressSpace space, uint64_t offset, const void *hostBuf, size_t size)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclWrite(space, offset, hostBuf, size);
}
size_t xclRead(xclDeviceHandle handle, xclAddressSpace space, uint64_t offset, void *hostBuf, size_t size)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclRead(space, offset, hostBuf, size);
}
int xclUpgradeFirmware(xclDeviceHandle handle, const char *fileName)
{
return 0;
}
int xclBootFPGA(xclDeviceHandle handle)
{
return 0;
}
int xclResetDevice(xclDeviceHandle handle, xclResetKind kind)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
drv->resetProgram();
return 0;
}
int xclReClock2(xclDeviceHandle handle, unsigned short region, const unsigned short *targetFreqMHz)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
drv->resetProgram();
return 0;
}
int xclLockDevice(xclDeviceHandle handle)
{
return 0;
}
int xclUnlockDevice(xclDeviceHandle handle)
{
return 0;
}
size_t xclPerfMonStartCounters(xclDeviceHandle handle, xclPerfMonType type)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
size_t xclPerfMonStopCounters(xclDeviceHandle handle, xclPerfMonType type)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
size_t xclPerfMonReadCounters(xclDeviceHandle handle, xclPerfMonType type, xclCounterResults& counterResults)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
size_t xclDebugReadIPStatus(xclDeviceHandle handle, xclDebugReadType type, void* debugResults)
{
return 0;
}
size_t xclPerfMonClockTraining(xclDeviceHandle handle, xclPerfMonType type)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
size_t xclPerfMonStartTrace(xclDeviceHandle handle, xclPerfMonType type, uint32_t startTrigger)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
size_t xclPerfMonStopTrace(xclDeviceHandle handle, xclPerfMonType type)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
uint32_t xclPerfMonGetTraceCount(xclDeviceHandle handle, xclPerfMonType type)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
size_t xclPerfMonReadTrace(xclDeviceHandle handle, xclPerfMonType type, xclTraceResultsVector& traceVector)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return 0;
}
double xclGetDeviceClockFreqMHz(xclDeviceHandle handle)
{
// xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
// if (!drv)
// return 0.0;
return 0.0;
}
double xclGetReadMaxBandwidthMBps(xclDeviceHandle handle)
{
// xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
// if (!drv)
// return 0.0;
return 0.0;
}
double xclGetWriteMaxBandwidthMBps(xclDeviceHandle handle)
{
// xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
// if (!drv)
// return 0.0;
return 0.0;
}
size_t xclGetDeviceTimestamp(xclDeviceHandle handle)
{
return 0;
}
void xclSetProfilingNumberSlots(xclDeviceHandle handle, xclPerfMonType type, uint32_t numSlots)
{
return;
}
uint32_t xclGetProfilingNumberSlots(xclDeviceHandle handle, xclPerfMonType type)
{
return 0;
}
void xclGetProfilingSlotName(xclDeviceHandle handle, xclPerfMonType type, uint32_t slotnum,
char* slotName, uint32_t length)
{
return;
}
unsigned xclProbe()
{
if(!xclemulation::isXclEmulationModeHwEmuOrSwEmu())
{
std::string initMsg ="ERROR: [SW-EM 09] Please set XCL_EMULATION_MODE to \"sw_emu\" to run software emulation. ";
std::cout<<initMsg<<std::endl;
return 0;
}
unsigned int deviceIndex = 0;
std::vector<std::tuple<xclDeviceInfo2,std::list<xclemulation::DDRBank> ,bool, bool, FeatureRomHeader> > devicesInfo;
getDevicesInfo(devicesInfo);
if(devicesInfo.size() == 0)
return 1;
for(auto &it: devicesInfo)
{
xclDeviceInfo2 info = std::get<0>(it);
std::list<xclemulation::DDRBank> DDRBankList = std::get<1>(it);
bool bUnified = std::get<2>(it);
bool bXPR = std::get<3>(it);
FeatureRomHeader fRomHeader = std::get<4>(it);
xclcpuemhal2::CpuemShim *handle = new xclcpuemhal2::CpuemShim(deviceIndex,info,DDRBankList, bUnified, bXPR, fRomHeader);
xclcpuemhal2::devices[deviceIndex++] = handle;
}
return deviceIndex;
}
//########################################## HAL2 START ##########################################
unsigned int xclVersion ()
{
return 2;
}
int xclExportBO(xclDeviceHandle handle, unsigned int boHandle)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclExportBO(boHandle);
}
unsigned int xclImportBO(xclDeviceHandle handle, int boGlobalHandle,unsigned flags)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclImportBO(boGlobalHandle,flags);
}
int xclCopyBO(xclDeviceHandle handle, unsigned int dst_boHandle, unsigned int src_boHandle, size_t size, size_t dst_offset, size_t src_offset)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclCopyBO(dst_boHandle, src_boHandle, size, dst_offset, src_offset) : -ENODEV;
}
size_t xclReadBO(xclDeviceHandle handle, unsigned int boHandle, void *dst,
size_t size, size_t skip)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -EINVAL;
return drv->xclReadBO(boHandle, dst, size, skip);
}
unsigned int xclAllocUserPtrBO(xclDeviceHandle handle, void *userptr, size_t size, unsigned flags)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return mNullBO;
return drv->xclAllocUserPtrBO(userptr,size,flags);
}
unsigned int xclAllocBO(xclDeviceHandle handle, size_t size, int unused, unsigned flags)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -EINVAL;
return drv->xclAllocBO(size, unused, flags);
}
void *xclMapBO(xclDeviceHandle handle, unsigned int boHandle, bool write)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return nullptr;
return drv->xclMapBO(boHandle, write);
}
int xclUnmapBO(xclDeviceHandle handle, unsigned int boHandle, void* addr)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -EINVAL;
return drv->xclUnmapBO(boHandle, addr);
}
int xclSyncBO(xclDeviceHandle handle, unsigned int boHandle, xclBOSyncDirection dir, size_t size, size_t offset)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -EINVAL;
return drv->xclSyncBO(boHandle, dir , size, offset);
}
size_t xclWriteBO(xclDeviceHandle handle, unsigned int boHandle, const void *src,
size_t size, size_t seek)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -EINVAL;
return drv->xclWriteBO(boHandle, src, size, seek);
}
void xclFreeBO(xclDeviceHandle handle, unsigned int boHandle)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return;
drv->xclFreeBO(boHandle);
}
int xclGetBOProperties(xclDeviceHandle handle, unsigned int boHandle, xclBOProperties *properties)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
if (!drv)
return -1;
return drv->xclGetBOProperties(boHandle, properties);
}
//QDMA Support
int xclCreateWriteQueue(xclDeviceHandle handle, xclQueueContext *q_ctx, uint64_t *q_hdl)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclCreateWriteQueue(q_ctx, q_hdl) : -ENODEV;
}
int xclCreateReadQueue(xclDeviceHandle handle, xclQueueContext *q_ctx, uint64_t *q_hdl)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclCreateReadQueue(q_ctx, q_hdl) : -ENODEV;
}
int xclDestroyQueue(xclDeviceHandle handle, uint64_t q_hdl)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclDestroyQueue(q_hdl) : -ENODEV;
}
void *xclAllocQDMABuf(xclDeviceHandle handle, size_t size, uint64_t *buf_hdl)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclAllocQDMABuf(size, buf_hdl) : nullptr;
}
int xclFreeQDMABuf(xclDeviceHandle handle, uint64_t buf_hdl)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclFreeQDMABuf(buf_hdl) : -ENODEV;
}
ssize_t xclWriteQueue(xclDeviceHandle handle, uint64_t q_hdl, xclQueueRequest *wr)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclWriteQueue(q_hdl, wr) : -ENODEV;
}
ssize_t xclReadQueue(xclDeviceHandle handle, uint64_t q_hdl, xclQueueRequest *wr)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclReadQueue(q_hdl, wr) : -ENODEV;
}
int xclPollCompletion(xclDeviceHandle handle, int min_compl, int max_compl, xclReqCompletion *comps, int* actual, int timeout)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclPollCompletion(min_compl, max_compl, comps, actual, timeout) : -ENODEV;
}
ssize_t xclUnmgdPread(xclDeviceHandle handle, unsigned flags, void *buf, size_t count, uint64_t offset)
{
return 0;
}
/*
* API to get number of live processes.
* Applicable only for System Flow as it supports Multiple processes on same device.
* For CPU emulation, return 0
*/
uint32_t xclGetNumLiveProcesses(xclDeviceHandle handle)
{
return 0;
}
int xclGetDebugIPlayoutPath(xclDeviceHandle handle, char* layoutPath, size_t size)
{
return -1;
}
int xclGetTraceBufferInfo(xclDeviceHandle handle, uint32_t nSamples, uint32_t& traceSamples, uint32_t& traceBufSz)
{
return -1;
}
int xclReadTraceData(xclDeviceHandle handle, void* traceBuf, uint32_t traceBufSz, uint32_t numSamples, uint64_t ipBaseAddress, uint32_t& wordsPerSample)
{
return -1;
}
int xclLogMsg(xclDeviceHandle handle, xrtLogMsgLevel level, const char* tag, const char* format, ...)
{
va_list args;
va_start(args, format);
int ret = xclcpuemhal2::CpuemShim::xclLogMsg(handle, level, tag, format, args);
va_end(args);
return ret;
}
//Added below calls as a fix for CR-1034151
int xclOpenContext(xclDeviceHandle handle, uuid_t xclbinId, unsigned int ipIndex, bool shared)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclOpenContext(xclbinId, ipIndex, shared) : -ENODEV;
}
int xclExecWait(xclDeviceHandle handle, int timeoutMilliSec)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclExecWait(timeoutMilliSec) : -ENODEV;
}
int xclExecBuf(xclDeviceHandle handle, unsigned int cmdBO)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclExecBuf(cmdBO) : -ENODEV;
}
int xclCloseContext(xclDeviceHandle handle, uuid_t xclbinId, unsigned ipIndex)
{
xclcpuemhal2::CpuemShim *drv = xclcpuemhal2::CpuemShim::handleCheck(handle);
return drv ? drv->xclCloseContext(xclbinId, ipIndex) : -ENODEV;
}
// Restricted read/write on IP register space
int xclRegWrite(xclDeviceHandle, uint32_t, uint32_t, uint32_t)
{
return 1;
}
int xclRegRead(xclDeviceHandle, uint32_t, uint32_t, uint32_t*)
{
return 1;
}
int xclCreateProfileResults(xclDeviceHandle handle, ProfileResults** results)
{
return 0;
}
int xclGetProfileResults(xclDeviceHandle handle, ProfileResults* results)
{
return 0;
}
int xclDestroyProfileResults(xclDeviceHandle handle, ProfileResults* results)
{
return 0;
}
void
xclGetDebugIpLayout(xclDeviceHandle hdl, char* buffer, size_t size, size_t* size_ret)
{
if(size_ret)
*size_ret = 0;
return;
}
int xclGetSubdevPath(xclDeviceHandle handle, const char* subdev,
uint32_t idx, char* path, size_t size)
{
return 0;
}
|
/*Exercise 3 - Repeatition
Convert the C program given below which calculates the Factorial of a number that you input from the keyboard to a C++ program.
Please Note that the input command in C++ is std::cin. This is a representation of the Keyboard.*/
#include <iostream>
int main()
{
int no;
long fac;
std::cout<<"Enter a Number : ";
std::cin>>no;
fac = 1;
for (int r=no; r >= 1; r--) {
fac = fac * r;
}
std::cout<<"Factorial of "<< no <<" is " <<fac;
return 0;
}
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMembershipFunctionBaseTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkMembershipFunctionBase.h"
#include "itkObjectFactory.h"
namespace itk {
namespace Statistics {
namespace MembershipFunctionBaseTest {
template <class TMeasurementVector>
class MyMembershipFunctionBase : public MembershipFunctionBase< TMeasurementVector >
{
public:
/** Standard class typedef. */
typedef MyMembershipFunctionBase Self;
typedef MembershipFunctionBase< TMeasurementVector > Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Standard macros */
itkTypeMacro(MyMembershipFunctionBase, MembershipFunctionBase);
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Evaluate membership score */
double Evaluate(const TMeasurementVector & ) const
{
double score;
score = 1;
return score;
}
typename MembershipFunctionBase< TMeasurementVector >::Pointer Clone()
{
Pointer memberFunction = MyMembershipFunctionBase< TMeasurementVector >::New();
return memberFunction.GetPointer();
}
};
}
}
}
int itkMembershipFunctionBaseTest(int, char* [] )
{
const unsigned int MeasurementVectorSize = 17;
typedef itk::FixedArray<
float, MeasurementVectorSize > MeasurementVectorType;
typedef itk::Statistics::MembershipFunctionBaseTest::MyMembershipFunctionBase<
MeasurementVectorType > MembershipFunctionBaseType;
MembershipFunctionBaseType::Pointer function = MembershipFunctionBaseType::New();
std::cout << function->GetNameOfClass() << std::endl;
std::cout << function->MembershipFunctionBaseType::Superclass::GetNameOfClass() << std::endl;
function->Print(std::cout);
function->SetMeasurementVectorSize( MeasurementVectorSize ); // for code coverage
if( function->GetMeasurementVectorSize() != MeasurementVectorSize )
{
std::cerr << "GetMeasurementVectorSize() Failed !" << std::endl;
return EXIT_FAILURE;
}
//Test if an exception will be thrown if we try to resize the measurement vector
//size
try
{
function->SetMeasurementVectorSize( MeasurementVectorSize + 1 );
std::cerr << "Exception should have been thrown since we are trying to resize\
non-resizeable measurement vector type " << std::endl;
return EXIT_FAILURE;
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Caughted expected exception: " << excp << std::endl;
}
return EXIT_SUCCESS;
}
|
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
const int maxn = 1000005;
const int mod = 1000000007;
int a[maxn], n, t, impar[maxn], par[maxn];
int main() {
ifstream fin("azerah.in");
ofstream fout("azerah.out");
fin >> t;
while(t -- ) {
fin >> n;
for(int i = 1 ; i <= n ; ++ i)
fin >> a[i];
if(a[1] % 2 == 0) {
par[1] = 1;
impar[1] = 0;
}
else {
par[1] = 0;
impar[1] = 1;
}
for(int i = 2 ; i <= n ; ++ i) {
if(a[i] % 2 == 0) {
impar[i] = (impar[i - 1] + impar[i - 1]) % mod;
par[i] = (1 + par[i - 1] + par[i - 1]) % mod;
}
else {
impar[i] = (1 + impar[i - 1] + par[i - 1]) % mod;
par[i] = (par[i - 1] + impar[i - 1]) % mod;
}
}
fout << par[n] << '\n';
}
}
|
/**
* The date June l0, 1960 is special because when we write it in the following format, the month times the day equals
* the year.
*
* 6/10/60
*
* Write a program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program should then determine whether the month times the day is equal to the year.
*/
#include <cstdlib>
// TODO: Add any additional libraries needed to compile your project.
// TODO: Add any needed function prototypes here.
int main() {
return EXIT_SUCCESS;
}
// TODO: Implement the function prototypes here
|
/*
* Copyright(c) 2019 Intel Corporation
* SPDX - License - Identifier: BSD - 2 - Clause - Patent
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// workaround to eliminate the compiling warning on linux
// The macro will conflict with definition in gtest.h
#ifdef __USE_GNU
#undef __USE_GNU // defined in EbThreads.h
#endif
#ifdef _GNU_SOURCE
#undef _GNU_SOURCE // defined in EbThreads.h
#endif
#include "aom_dsp_rtcd.h"
#include "EbDefinitions.h"
#include "EbUnitTestUtility.h"
#include "EbTransforms.h"
#include "random.h"
#include "util.h"
#include "transpose_avx2.h"
#include "transpose_sse2.h"
namespace {
static INLINE void transpose_8bit_16x16_c(const uint8_t *const in,
uint8_t *const out) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
out[16 * j + i] = in[16 * i + j];
}
}
}
class TransposeTest : public ::testing::Test {
public:
~TransposeTest();
void SetUp() {
rnd_ = new svt_av1_test_tool::SVTRandom(0, (1 << 16) - 1);
}
void TearDown() {
aom_clear_system_state();
}
protected:
void RunCheckOutput();
void RunSpeedTest();
uint8_t in_[256];
uint8_t out_c_[256];
uint8_t out_o_[256];
svt_av1_test_tool::SVTRandom *rnd_;
};
TransposeTest::~TransposeTest() {
}
void TransposeTest::RunCheckOutput() {
__m128i in[16], out[16];
for (int i = 0; i < 256; ++i) {
in_[i] = rnd_->Rand8();
}
transpose_8bit_16x16_c(in_, out_c_);
for (int i = 0; i < 16; i++)
in[i] = _mm_loadu_si128((__m128i *)(in_ + 16 * i));
transpose_8bit_16x16_reg128bit_avx2(in, out);
for (int i = 0; i < 16; i++)
_mm_storeu_si128((__m128i *)(out_o_ + 16 * i), out[i]);
for (int i = 0; i < 256; ++i)
ASSERT_EQ(out_c_[i], out_o_[i]) << "[" << i << "]";
}
void TransposeTest::RunSpeedTest() {
const int num_loops = 100000000;
__m128i in[16], out_c[16], out_o[16];
double time_c, time_o;
uint64_t start_time_seconds, start_time_useconds;
uint64_t middle_time_seconds, middle_time_useconds;
uint64_t finish_time_seconds, finish_time_useconds;
for (int i = 0; i < 256; ++i) {
in_[i] = rnd_->Rand8();
}
for (int i = 0; i < 16; i++)
in[i] = _mm_loadu_si128((__m128i *)(in_ + 16 * i));
EbStartTime(&start_time_seconds, &start_time_useconds);
for (int i = 0; i < num_loops; ++i) {
transpose_8bit_16x16_sse2(in, out_c);
}
EbStartTime(&middle_time_seconds, &middle_time_useconds);
for (int i = 0; i < num_loops; ++i) {
transpose_8bit_16x16_reg128bit_avx2(in, out_o);
}
EbStartTime(&finish_time_seconds, &finish_time_useconds);
for (int i = 0; i < 16; i++) {
_mm_storeu_si128((__m128i *)(out_c_ + 16 * i), out_c[i]);
_mm_storeu_si128((__m128i *)(out_o_ + 16 * i), out_o[i]);
}
for (int i = 0; i < 256; ++i)
ASSERT_EQ(out_c_[i], out_o_[i]) << "[" << i << "]";
EbComputeOverallElapsedTimeMs(start_time_seconds,
start_time_useconds,
middle_time_seconds,
middle_time_useconds,
&time_c);
EbComputeOverallElapsedTimeMs(middle_time_seconds,
middle_time_useconds,
finish_time_seconds,
finish_time_useconds,
&time_o);
printf("Average Nanoseconds per Function Call\n");
printf(" transpose_8bit_16x16 (SSE2) : %6.2f\n",
1000000 * time_c / num_loops);
printf(
" transpose_8bit_16x16 (AVX2) : %6.2f (Comparison: "
"%5.2fx)\n",
1000000 * time_o / num_loops,
time_c / time_o);
}
TEST_F(TransposeTest, CheckOutput) {
RunCheckOutput();
}
TEST_F(TransposeTest, DISABLED_Speed) {
RunSpeedTest();
}
}; // namespace
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/notification_display_queue.h"
#include <algorithm>
#include <utility>
#include "chrome/browser/notifications/notification_display_service.h"
namespace {
bool IsWebNotification(NotificationHandler::Type notification_type) {
return notification_type == NotificationHandler::Type::WEB_PERSISTENT ||
notification_type == NotificationHandler::Type::WEB_NON_PERSISTENT ||
notification_type == NotificationHandler::Type::EXTENSION;
}
} // namespace
NotificationDisplayQueue::NotificationDisplayQueue(
NotificationDisplayService* notification_display_service)
: notification_display_service_(notification_display_service) {}
NotificationDisplayQueue::~NotificationDisplayQueue() = default;
void NotificationDisplayQueue::OnBlockingStateChanged() {
MaybeDisplayQueuedNotifications();
}
bool NotificationDisplayQueue::ShouldEnqueueNotification(
NotificationHandler::Type notification_type,
const message_center::Notification& notification) const {
return IsWebNotification(notification_type) &&
IsAnyNotificationBlockerActive(notification);
}
void NotificationDisplayQueue::EnqueueNotification(
NotificationHandler::Type notification_type,
const message_center::Notification& notification,
std::unique_ptr<NotificationCommon::Metadata> metadata) {
bool replaced =
DoRemoveQueuedNotification(notification.id(), /*notify=*/false);
queued_notifications_.emplace_back(notification_type, notification,
std::move(metadata));
// Notify blockers that a new notification has been blocked.
for (auto& blocker : blockers_) {
if (blocker->ShouldBlockNotification(notification))
blocker->OnBlockedNotification(notification, replaced);
}
}
void NotificationDisplayQueue::RemoveQueuedNotification(
const std::string& notification_id) {
DoRemoveQueuedNotification(notification_id, /*notify=*/true);
}
std::set<std::string> NotificationDisplayQueue::GetQueuedNotificationIds()
const {
std::set<std::string> notification_ids;
for (const QueuedNotification& queued : queued_notifications_)
notification_ids.insert(queued.notification.id());
return notification_ids;
}
void NotificationDisplayQueue::SetNotificationBlockers(
NotificationBlockers blockers) {
// Remove old blockers from the observer.
for (auto& blocker : blockers_)
notification_blocker_observer_.Remove(blocker.get());
// Add new blockers and observe them.
blockers_ = std::move(blockers);
for (auto& blocker : blockers_)
notification_blocker_observer_.Add(blocker.get());
// Update new state with new blockers.
MaybeDisplayQueuedNotifications();
}
void NotificationDisplayQueue::AddNotificationBlocker(
std::unique_ptr<NotificationBlocker> blocker) {
notification_blocker_observer_.Add(blocker.get());
blockers_.push_back(std::move(blocker));
}
bool NotificationDisplayQueue::DoRemoveQueuedNotification(
const std::string& notification_id,
bool notify) {
auto it =
std::find_if(queued_notifications_.begin(), queued_notifications_.end(),
[¬ification_id](const QueuedNotification& queued) {
return queued.notification.id() == notification_id;
});
if (it == queued_notifications_.end())
return false;
if (notify) {
for (auto& blocker : blockers_) {
if (blocker->ShouldBlockNotification(it->notification))
blocker->OnClosedNotification(it->notification);
}
}
queued_notifications_.erase(it);
return true;
}
void NotificationDisplayQueue::MaybeDisplayQueuedNotifications() {
auto show_begin = std::stable_partition(
queued_notifications_.begin(), queued_notifications_.end(),
[&](const QueuedNotification& queued) {
return IsAnyNotificationBlockerActive(queued.notification);
});
std::vector<QueuedNotification> notifications;
notifications.insert(notifications.end(), std::make_move_iterator(show_begin),
std::make_move_iterator(queued_notifications_.end()));
queued_notifications_.erase(show_begin, queued_notifications_.end());
for (QueuedNotification& queued : notifications) {
notification_display_service_->Display(queued.notification_type,
queued.notification,
std::move(queued.metadata));
}
}
bool NotificationDisplayQueue::IsAnyNotificationBlockerActive(
const message_center::Notification& notification) const {
return std::any_of(
blockers_.begin(), blockers_.end(),
[¬ification](const std::unique_ptr<NotificationBlocker>& blocker) {
return blocker->ShouldBlockNotification(notification);
});
}
NotificationDisplayQueue::QueuedNotification::QueuedNotification(
NotificationHandler::Type notification_type,
const message_center::Notification& notification,
std::unique_ptr<NotificationCommon::Metadata> metadata)
: notification_type(notification_type),
notification(notification),
metadata(std::move(metadata)) {}
NotificationDisplayQueue::QueuedNotification::QueuedNotification(
QueuedNotification&&) = default;
NotificationDisplayQueue::QueuedNotification&
NotificationDisplayQueue::QueuedNotification::operator=(QueuedNotification&&) =
default;
NotificationDisplayQueue::QueuedNotification::~QueuedNotification() = default;
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/tc-internal.h"
#include "hphp/runtime/vm/jit/tc.h"
#include "hphp/runtime/base/init-fini-node.h"
#include "hphp/runtime/base/perf-warning.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/stats.h"
#include "hphp/runtime/base/bespoke/layout.h"
#include "hphp/runtime/vm/debug/debug.h"
#include "hphp/runtime/vm/vm-regs.h"
#include "hphp/runtime/vm/workload-stats.h"
#include "hphp/runtime/vm/jit/code-cache.h"
#include "hphp/runtime/vm/jit/guard-type-profile.h"
#include "hphp/runtime/vm/jit/mcgen-translate.h"
#include "hphp/runtime/vm/jit/mcgen.h"
#include "hphp/runtime/vm/jit/perf-counters.h"
#include "hphp/runtime/vm/jit/prof-data.h"
#include "hphp/runtime/vm/jit/relocation.h"
#include "hphp/runtime/vm/jit/service-requests.h"
#include "hphp/runtime/vm/jit/srcdb.h"
#include "hphp/runtime/vm/jit/tc-prologue.h"
#include "hphp/runtime/vm/jit/tc-record.h"
#include "hphp/runtime/vm/jit/timer.h"
#include "hphp/runtime/vm/jit/trans-db.h"
#include "hphp/runtime/vm/jit/unique-stubs.h"
#include "hphp/runtime/vm/jit/unwind-itanium.h"
#include "hphp/runtime/vm/jit/vasm-emit.h"
#include "hphp/runtime/vm/jit/write-lease.h"
#include "hphp/util/disasm.h"
#include "hphp/util/logger.h"
#include "hphp/util/mutex.h"
#include "hphp/util/rds-local.h"
#include "hphp/util/trace.h"
#include <tbb/concurrent_hash_map.h>
#include <atomic>
extern "C" _Unwind_Reason_Code
__gxx_personality_v0(int, _Unwind_Action, uint64_t, _Unwind_Exception*,
_Unwind_Context*);
TRACE_SET_MOD(mcg);
namespace HPHP::jit::tc {
__thread bool tl_is_jitting = false;
CodeCache* g_code{nullptr};
SrcDB g_srcDB;
UniqueStubs g_ustubs;
///////////////////////////////////////////////////////////////////////////////
namespace {
const StaticString s_AlwaysInterp("__ALWAYS_INTERP");
std::atomic<uint64_t> s_numTrans;
SimpleMutex s_codeLock{false, RankCodeCache};
SimpleMutex s_metadataLock{false, RankCodeMetadata};
RDS_LOCAL_NO_CHECK(size_t, s_initialTCSize);
bool shouldPGOFunc(const Func* func) {
return profData() != nullptr;
}
// A code reuse block owns temporary code blocks used to emit into a reused
// segment of another view.
struct CodeReuseBlock {
CodeBlock reusedMain, reusedCold, reusedFrozen;
// Get a view into possibly reused code blocks (if there is space, and
// reusable TC is enabled).
CodeCache::View getMaybeReusedView(CodeCache::View& src,
const TransRange& range) {
if (!RuntimeOption::EvalEnableReusableTC) return src;
auto main = &src.main();
auto cold = &src.cold();
auto frozen = &src.frozen();
auto const pad = RuntimeOption::EvalReusableTCPadding;
size_t mainSize = range.main.size() + pad;
size_t coldSize = range.cold.size() + pad;
size_t frozenSize = range.frozen.size() + pad;
if (auto const s = (TCA)main->allocInner(mainSize)) {
reusedMain.init(s, mainSize, "Reused main");
main = &reusedMain;
}
if (auto const s = (TCA)cold->allocInner(coldSize)) {
reusedCold.init(s, coldSize, "Reused cold");
cold = &reusedCold;
}
if (cold != frozen) {
if (auto const s = (TCA)frozen->allocInner(frozenSize)) {
reusedFrozen.init(s, frozenSize, "Reused frozen");
frozen = &reusedFrozen;
}
}
return CodeCache::View(*main, *cold, *frozen, src.data(), false);
}
};
}
///////////////////////////////////////////////////////////////////////////////
TransLoc TransRange::loc() const {
TransLoc loc;
loc.setMainStart(main.begin());
loc.setColdStart(cold.begin() - sizeof(uint32_t));
loc.setFrozenStart(frozen.begin() - sizeof(uint32_t));
loc.setMainSize(main.size());
assertx(loc.coldCodeSize() == cold.size());
assertx(loc.frozenCodeSize() == frozen.size());
return loc;
}
bool canTranslate() {
return s_numTrans.load(std::memory_order_relaxed) <
RuntimeOption::EvalJitGlobalTranslationLimit;
}
using FuncCounterMap = tbb::concurrent_hash_map<FuncId, uint32_t,
FuncIdHashCompare>;
static FuncCounterMap s_func_counters;
using SrcKeyCounters = tbb::concurrent_hash_map<SrcKey, uint32_t,
SrcKey::TbbHashCompare>;
static SrcKeyCounters s_sk_counters;
static RDS_LOCAL_NO_CHECK(bool, s_jittingTimeLimitExceeded);
TranslationResult::Scope shouldTranslateNoSizeLimit(SrcKey sk, TransKind kind) {
// If we've hit Eval.JitGlobalTranslationLimit, then we stop translating.
if (!canTranslate()) return TranslationResult::Scope::Process;
if (*s_jittingTimeLimitExceeded) return TranslationResult::Scope::Request;
auto const maxTransTime = RuntimeOption::EvalJitMaxRequestTranslationTime;
if (maxTransTime >= 0 && RuntimeOption::ServerExecutionMode()) {
auto const transCounter = Timer::CounterValue(Timer::mcg_translate);
if (transCounter.wall_time_elapsed >= maxTransTime) {
if (Trace::moduleEnabledRelease(Trace::mcg, 1)) {
Trace::traceRelease("Skipping translation. "
"Time budget of %" PRId64 " exceeded. "
"%" PRId64 "us elapsed. "
"%" PRId64 " translations completed\n",
maxTransTime,
transCounter.wall_time_elapsed,
transCounter.count);
}
*s_jittingTimeLimitExceeded = true;
return TranslationResult::Scope::Request;
}
}
auto const func = sk.func();
if (!RO::EvalHHIRAlwaysInterpIgnoreHint &&
func->userAttributes().count(s_AlwaysInterp.get())) {
SKTRACE(2, sk,
"punting because function is annotated with __ALWAYS_INTERP\n");
return TranslationResult::Scope::Process;
}
// Do not translate functions from units marked as interpret-only.
if (func->unit()->isInterpretOnly()) {
return TranslationResult::Scope::Transient;
}
// Refuse to JIT Live translations if Eval.JitPGOOnly is enabled.
if (RuntimeOption::EvalJitPGOOnly &&
(kind == TransKind::Live || kind == TransKind::LivePrologue)) {
return TranslationResult::Scope::Transient;
}
// Refuse to JIT Live / Profile translations for a function until
// Eval.JitLiveThreshold / Eval.JitProfileThreshold is hit.
auto const isLive = kind == TransKind::Live ||
kind == TransKind::LivePrologue;
auto const isProf = kind == TransKind::Profile ||
kind == TransKind::ProfPrologue;
if (isLive || isProf) {
uint32_t skCount = 1;
if (RuntimeOption::EvalJitSrcKeyThreshold > 1) {
SrcKeyCounters::accessor acc;
if (!s_sk_counters.insert(acc, SrcKeyCounters::value_type(sk, 1))) {
skCount = ++acc->second;
}
}
{
FuncCounterMap::accessor acc;
if (!s_func_counters.insert(acc, {func->getFuncId(), 1})) ++acc->second;
auto const funcThreshold = isLive ? RuntimeOption::EvalJitLiveThreshold
: RuntimeOption::EvalJitProfileThreshold;
if (acc->second < funcThreshold) {
return TranslationResult::Scope::Transient;
}
}
if (skCount < RuntimeOption::EvalJitSrcKeyThreshold) {
return TranslationResult::Scope::Transient;
}
}
return TranslationResult::Scope::Success;
}
static std::atomic_flag s_did_log = ATOMIC_FLAG_INIT;
static std::atomic<bool> s_TCisFull{false};
TranslationResult::Scope shouldTranslate(SrcKey sk, TransKind kind) {
if (s_TCisFull.load(std::memory_order_relaxed)) {
return TranslationResult::Scope::Process;
}
if (*s_jittingTimeLimitExceeded) {
return TranslationResult::Scope::Request;
}
const bool reachedMaxLiveMainLimit =
getLiveMainUsage() >= RuntimeOption::EvalJitMaxLiveMainUsage;
auto const main_under = code().main().used() < CodeCache::AMaxUsage;
auto const cold_under = code().cold().used() < CodeCache::AColdMaxUsage;
auto const froz_under = code().frozen().used() < CodeCache::AFrozenMaxUsage;
if (!reachedMaxLiveMainLimit && main_under && cold_under && froz_under) {
return shouldTranslateNoSizeLimit(sk, kind);
}
// Set a flag so we quickly bail from trying to generate new
// translations next time.
s_TCisFull.store(true, std::memory_order_relaxed);
Treadmill::enqueue([] { s_sk_counters.clear(); });
if (main_under && !s_did_log.test_and_set() &&
RuntimeOption::EvalProfBranchSampleFreq == 0) {
// If we ran out of TC space in cold or frozen but not in main,
// something unexpected is happening and we should take note of
// it. We skip this logging if TC branch profiling is on, since
// it fills up code and frozen at a much higher rate.
if (!cold_under) {
logPerfWarning("cold_full", 1, [] (StructuredLogEntry&) {});
}
if (!froz_under) {
logPerfWarning("frozen_full", 1, [] (StructuredLogEntry&) {});
}
}
return TranslationResult::Scope::Process;
}
bool newTranslation() {
if (s_numTrans.fetch_add(1, std::memory_order_relaxed) >=
RuntimeOption::EvalJitGlobalTranslationLimit) {
return false;
}
return true;
}
std::unique_lock<SimpleMutex> lockCode(bool lock) {
if (lock) return std::unique_lock<SimpleMutex>{ s_codeLock };
return std::unique_lock<SimpleMutex>{s_codeLock, std::defer_lock};
}
std::unique_lock<SimpleMutex> lockMetadata(bool lock) {
if (lock) return std::unique_lock<SimpleMutex>{s_metadataLock};
return std::unique_lock<SimpleMutex>{s_metadataLock, std::defer_lock};
}
CodeMetaLock::CodeMetaLock(bool f) :
m_code(lockCode(f)),
m_meta(lockMetadata(f)) {
}
void CodeMetaLock::lock() {
m_code.lock();
m_meta.lock();
}
void CodeMetaLock::unlock() {
m_meta.unlock();
m_code.unlock();
}
void assertOwnsCodeLock(OptView v) {
if (!v || !v->isLocal()) s_codeLock.assertOwnedBySelf();
}
void assertOwnsMetadataLock() { s_metadataLock.assertOwnedBySelf(); }
void requestInit() {
regState() = VMRegState::CLEAN;
Timer::RequestInit();
memset(rl_perf_counters.getCheck(), 0, sizeof(PerfCounters));
Stats::init();
requestInitProfData();
*s_initialTCSize.getCheck() = g_code->totalUsed();
assertx(!g_unwind_rds.isInit());
memset(g_unwind_rds.get(), 0, sizeof(UnwindRDS));
g_unwind_rds.markInit();
*s_jittingTimeLimitExceeded.getCheck() = false;
}
void requestExit() {
Stats::dump();
Stats::clear();
if (RuntimeOption::EvalJitProfileGuardTypes) {
logGuardProfileData();
}
Timer::RequestExit();
if (profData()) profData()->maybeResetCounters();
requestExitProfData();
reportJitMaturity();
if (Trace::moduleEnabledRelease(Trace::mcgstats, 1)) {
Trace::traceRelease("MCGenerator perf counters for %s:\n",
g_context->getRequestUrl(50).c_str());
for (int i = 0; i < tpc_num_counters; i++) {
Trace::traceRelease("%-20s %10" PRId64 "\n",
kPerfCounterNames[i], rl_perf_counters[i]);
}
Trace::traceRelease("\n");
}
}
void codeEmittedThisRequest(size_t& requestEntry, size_t& now) {
requestEntry = *s_initialTCSize;
now = g_code->totalUsed();
}
void processInit() {
auto codeLock = lockCode();
auto metaLock = lockMetadata();
g_code = new(low_malloc(sizeof(CodeCache))) CodeCache();
g_ustubs.emitAll(*g_code, *Debug::DebugInfo::Get());
// Write an .eh_frame section that covers the JIT portion of the TC.
initUnwinder(g_code->base(), g_code->tcSize(),
tc_unwind_personality);
if (auto cti_cap = g_code->bytecode().capacity()) {
// write an .eh_frame for cti code using default personality
initUnwinder(g_code->bytecode().base(), cti_cap, __gxx_personality_v0);
}
Disasm::ExcludedAddressRange(g_code->base(), g_code->codeSize());
recycleInit();
}
void processExit() {
recycleStop();
}
bool isValidCodeAddress(TCA addr) {
return g_code->isValidCodeAddress(addr);
}
void checkFreeProfData() {
// In PGO mode, we free all the profiling data once the main code area reaches
// its maximum usage.
//
// However, we keep the data around indefinitely in a few special modes:
// * Eval.EnableReusableTC
// * TC dumping enabled (Eval.DumpTC/DumpIR/etc.)
//
// Finally, when the RetranslateAll mode is enabled, the ProfData is discarded
// via a different mechanism, after all the optimized translations are
// generated.
if (profData() &&
!RuntimeOption::EvalEnableReusableTC &&
(code().main().used() >= CodeCache::AMaxUsage ||
getLiveMainUsage() >= RuntimeOption::EvalJitMaxLiveMainUsage) &&
!transdb::enabled() &&
!mcgen::retranslateAllEnabled()) {
discardProfData();
}
}
bool shouldProfileNewFuncs() {
if (profData() == nullptr) return false;
// We have two knobs to control the number of functions we're allowed to
// profile: Eval.JitProfileRequests and Eval.JitProfileBCSize. We profile new
// functions until either of these limits is exceeded. In practice, we expect
// to hit the bytecode size limit first, but we keep the request limit around
// as a safety net.
return profData()->profilingBCSize() < RuntimeOption::EvalJitProfileBCSize &&
requestCount() < RuntimeOption::EvalJitProfileRequests;
}
bool profileFunc(const Func* func) {
// If retranslateAll has been scheduled (including cases when it is going on,
// or has finished), we can't emit more Profile translations. This is to
// ensure that, when retranslateAll() runs, no more Profile translations are
// being added to ProfData.
if (mcgen::retranslateAllScheduled()) return false;
if (code().main().used() >= CodeCache::AMaxUsage) return false;
if (getLiveMainUsage() >= RuntimeOption::EvalJitMaxLiveMainUsage) {
return false;
}
if (!shouldPGOFunc(func)) return false;
if (profData()->optimized(func->getFuncId())) return false;
// If we already started profiling `func', then we return true and skip the
// other checks below.
if (profData()->profiling(func->getFuncId())) return true;
return shouldProfileNewFuncs();
}
///////////////////////////////////////////////////////////////////////////////
LocalTCBuffer::LocalTCBuffer(Address start, size_t initialSize) {
TCA fakeStart = code().threadLocalStart();
auto const sz = initialSize / 4;
auto initBlock = [&] (DataBlock& block, size_t mxSz, const char* nm) {
always_assert(sz <= mxSz);
block.init(fakeStart, start, sz, mxSz, nm);
fakeStart += mxSz;
start += sz;
};
initBlock(m_main, RuntimeOption::EvalThreadTCMainBufferSize,
"thread local main");
initBlock(m_cold, RuntimeOption::EvalThreadTCColdBufferSize,
"thread local cold");
initBlock(m_frozen, RuntimeOption::EvalThreadTCFrozenBufferSize,
"thread local frozen");
initBlock(m_data, RuntimeOption::EvalThreadTCDataBufferSize,
"thread local data");
}
OptView LocalTCBuffer::view() {
if (!valid()) return std::nullopt;
return CodeCache::View(m_main, m_cold, m_frozen, m_data, true);
}
////////////////////////////////////////////////////////////////////////////////
// Translator internals
Translator::Translator(SrcKey sk, TransKind kind)
: sk(sk), kind(kind), unit(), vunit()
{}
Translator::~Translator() = default;
Optional<TranslationResult>
Translator::acquireLeaseAndRequisitePaperwork() {
computeKind();
// Avoid a race where we would create a Live translation while
// retranslateAll is in flight and we haven't generated an
// Optimized translation yet.
auto const shouldEmitLiveTranslation = [&] {
if (mcgen::retranslateAllPending() && !isProfiling(kind) && profData()) {
// When bespokes are enabled, we can't emit live translations until the
// bespoke hierarchy is finalized.
if (allowBespokeArrayLikes() && !bespoke::Layout::HierarchyFinalized()) {
return false;
}
// Functions that are marked as being profiled or marked as having been
// optimized are about to have their translations invalidated during the
// publish phase of retranslate all. Don't allow live translations to be
// emitted in this scenario.
auto const fid = sk.func()->getFuncId();
return !profData()->profiling(fid) &&
!profData()->optimized(fid);
}
return true;
};
if (!shouldEmitLiveTranslation()) {
return TranslationResult::failTransiently();
}
if (auto const p = getCached()) return *p;
// Acquire the appropriate lease otherwise bail to a fallback
// execution mode (eg. interpreter) by returning a nullptr
// translation address.
m_lease.emplace(sk.func(), kind);
if (!(*m_lease)) return TranslationResult::failTransiently();
computeKind(); // Recompute the kind in case we are no longer profiling.
if (!m_lease->checkKind(kind)) return TranslationResult::failTransiently();
// Check again if we can emit live translations for the given
// func now that we have the lock.
if (!shouldEmitLiveTranslation()) {
return TranslationResult::failTransiently();
}
if (auto const s = shouldTranslate();
s != TranslationResult::Scope::Success) {
if (s == TranslationResult::Scope::Process) setCachedForProcessFail();
return TranslationResult{s};
}
if (UNLIKELY(RID().isJittingDisabled())) {
TRACE(2, "punting because jitting code was disabled\n");
return TranslationResult::failTransiently();
}
// Check for cached one last time since we have all the locks now.
return getCached();
}
TranslationResult::Scope Translator::shouldTranslate(bool noSizeLimit) {
if (kind == TransKind::Invalid) computeKind();
if (noSizeLimit) {
return shouldTranslateNoSizeLimit(sk, kind);
}
return ::HPHP::jit::tc::shouldTranslate(sk, kind);
}
Optional<TranslationResult>
Translator::translate(Optional<CodeCache::View> view) {
// If the TransDB is enabled, we allocate TransIDs for all translations in
// ProfData to keep each translation's ID the same in both ProfData and
// TransDB.
if (profData() && (isProfiling(kind) || transdb::enabled())) {
transId = profData()->allocTransID();
}
if (!newTranslation()) return TranslationResult::failForProcess();
WorkloadStats::EnsureInit();
WorkloadStats guard(WorkloadStats::InTrans);
SCOPE_EXIT {
unit.reset();
vunit.reset();
};
{
tl_is_jitting = true;
this->gen();
SCOPE_EXIT {
tl_is_jitting = false;
};
}
// Check for translation failure.
// TODO: categorize failure
if (!vunit) return TranslationResult::failTransiently();
Timer timer(Timer::mcg_finishTranslation);
tracing::Block _b{
"emit-translation",
[&] {
return traceProps(*vunit);
}
};
auto codeLock = lockCode(false);
if (!view.has_value()) {
if (RuntimeOption::EvalEnableReusableTC) {
auto const initialSize = 256;
m_localBuffer = std::make_unique<uint8_t[]>(initialSize);
m_localTCBuffer =
std::make_unique<LocalTCBuffer>(m_localBuffer.get(), initialSize);
view = m_localTCBuffer->view();
} else {
// Using the global TC view. Better lock things.
codeLock.lock();
}
}
// Tag the translation start, and build the trans meta.
// Generate vasm into the code view, retrying if we fill hot.
while (true) {
if (!view.has_value() || !view->isLocal()) {
view.emplace(code().view(kind));
}
CGMeta fixups;
TransLocMaker maker{*view};
const bool align = isPrologue(kind);
try {
view->alignForTranslation(align);
maker.markStart();
emitVunit(*vunit, unit.get(), *view, fixups,
mcgen::dumpTCAnnotation(kind) ? getAnnotations()
: nullptr);
} catch (const DataBlockFull& dbFull) {
// Rollback so the area can be used by something else.
auto const range = maker.rollback();
auto const bytes = range.main.size() + range.cold.size() +
range.frozen.size();
// There should be few of these. They mean there is wasted work
// performing translation for functions that don't have space in the TC.
logPerfWarning("translation_overflow", 1, [&] (StructuredLogEntry& e) {
e.setStr("kind", show(kind));
e.setStr("srckey", show(sk));
e.setStr("data_block", dbFull.name);
e.setInt("bytes_dropped", bytes);
});
if (RuntimeOption::ServerExecutionMode()) {
Logger::Warning("TC area %s filled up!", dbFull.name.c_str());
}
reset();
return TranslationResult::failForProcess();
}
transMeta.emplace(*view);
transMeta->fixups = std::move(fixups);
transMeta->range = maker.markEnd();
break;
}
if (isProfiling(kind)) {
profData()->setProfiling(sk.func());
}
Timer metaTimer(Timer::mcg_finishTranslation_metadata);
if (unit && unit->logEntry()) {
auto metaLock = lockMetadata();
logTranslation(this, transMeta->range);
}
if (!RuntimeOption::EvalJitLogAllInlineRegions.empty()) {
logFrames(*vunit);
}
return std::nullopt;
}
bool Translator::translateSuccess() const {
return transMeta.has_value();
}
Optional<TranslationResult> Translator::relocate(bool alignMain) {
assertx(transMeta.has_value());
// Code emitted directly is relocated during emission (or emitted
// directly in place).
if (!transMeta->view.isLocal()) {
assertx(!RuntimeOption::EvalEnableReusableTC);
return std::nullopt;
}
WorkloadStats::EnsureInit();
WorkloadStats guard(WorkloadStats::InTrans);
auto const& range = transMeta->range;
auto& fixups = transMeta->fixups;
RelocationInfo rel;
{
auto codeLock = lockCode();
while (true) {
auto finalView = code().view(kind);
CodeReuseBlock crb;
auto dstView = crb.getMaybeReusedView(finalView, range);
auto& srcView = transMeta->view;
TransLocMaker maker{dstView};
try {
dstView.alignForTranslation(alignMain);
maker.markStart();
auto origin = range.data;
if (!origin.empty()) {
dstView.data().bytes(origin.size(),
srcView.data().toDestAddress(origin.begin()));
auto dest = maker.dataRange();
auto oAddr = origin.begin();
auto dAddr = dest.begin();
while (oAddr != origin.end()) {
assertx(dAddr != dest.end());
rel.recordAddress(oAddr++, dAddr++, 0);
}
}
jit::relocate(rel, dstView.main(), range.main.begin(), range.main.end(),
srcView.main(), fixups, nullptr, AreaIndex::Main);
jit::relocate(rel, dstView.cold(), range.cold.begin(), range.cold.end(),
srcView.cold(), fixups, nullptr, AreaIndex::Cold);
if (&srcView.cold() != &srcView.frozen()) {
jit::relocate(rel, dstView.frozen(), range.frozen.begin(),
range.frozen.end(), srcView.frozen(), fixups, nullptr,
AreaIndex::Frozen);
}
} catch (const DataBlockFull& dbFull) {
// Rollback so the area can be used by something else.
maker.rollback();
auto const bytes = range.main.size() + range.cold.size() +
range.frozen.size();
// There should be few of these. They mean there is wasted work
// performing translation for functions that don't have space in the TC.
logPerfWarning("translation_overflow", 1, [&] (StructuredLogEntry& e) {
e.setStr("kind", show(kind));
e.setStr("srckey", show(sk));
e.setStr("data_block", dbFull.name);
e.setInt("bytes_dropped", bytes);
});
reset();
return TranslationResult::failForProcess();
}
transMeta->range = maker.markEnd();
transMeta->view = finalView;
break;
}
}
adjustForRelocation(rel);
adjustMetaDataForRelocation(rel, nullptr, fixups);
adjustCodeForRelocation(rel, fixups);
return std::nullopt;
}
Optional<TranslationResult> Translator::bindOutgoingEdges() {
assertx(transMeta.has_value());
auto& meta = transMeta->fixups;
for (auto& b : meta.smashableBinds) {
// We can't bind to fallback translations, so use the stub. they do not
// exist yet outside of retranslate all, which has a different mechanism
// to achieve that.
if (b.fallback) {
auto const stub = svcreq::getOrEmitStub(
svcreq::StubType::Retranslate, b.sk, b.spOff);
if (stub == nullptr) {
reset();
return TranslationResult::failForProcess();
}
b.smashable.patch(stub);
continue;
}
auto sr = createSrcRec(b.sk, b.spOff);
if (sr == nullptr) {
reset();
return TranslationResult::failForProcess();
}
// If the target is translated, bind it.
if (sr->getTopTranslation()) {
auto srLock = sr->writelock();
if (sr->getTopTranslation()) {
sr->chainFrom(b.smashable);
continue;
}
}
// May need a stub, so create it.
auto const stub = svcreq::getOrEmitStub(
svcreq::StubType::Translate, b.sk, b.spOff);
if (stub == nullptr) {
reset();
return TranslationResult::failForProcess();
}
auto srLock = sr->writelock();
sr->chainFrom(b.smashable, stub);
}
return std::nullopt;
}
TranslationResult Translator::publish() {
assertx(transMeta.has_value());
auto codeLock = lockCode();
auto metaLock = lockMetadata();
publishMetaInternal();
publishCodeInternal();
return TranslationResult{transMeta->range.loc().entry()};
}
void Translator::publishMetaInternal() {
assertx(transMeta.has_value());
this->publishMetaImpl();
}
void Translator::publishCodeInternal() {
assertx(transMeta.has_value());
this->publishCodeImpl();
updateCodeSizeCounters();
}
////////////////////////////////////////////////////////////////////////////////
}
|
#include <gtest/gtest.h>
#include "example.h"
TEST(example, subtract) {
double res;
res = subtract_numbers(1.0, 2.0);
ASSERT_NEAR(res, -1.0, 1.0e-11);
}
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// 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 "td/telegram/DialogId.h"
#include "td/telegram/MessageId.h"
#include "td/telegram/MessagesDb.h"
#include "td/telegram/NotificationId.h"
#include "td/telegram/ServerMessageId.h"
#include "td/telegram/UserId.h"
#include "td/actor/ConcurrentScheduler.h"
#include "td/actor/PromiseFuture.h"
#include "td/db/SqliteConnectionSafe.h"
#include "td/db/SqliteDb.h"
#include "td/utils/benchmark.h"
#include "td/utils/buffer.h"
#include "td/utils/common.h"
#include "td/utils/logging.h"
#include "td/utils/Random.h"
#include "td/utils/Status.h"
#include <memory>
namespace td {
static Status init_db(SqliteDb &db) {
TRY_STATUS(db.exec("PRAGMA encoding=\"UTF-8\""));
TRY_STATUS(db.exec("PRAGMA synchronous=NORMAL"));
TRY_STATUS(db.exec("PRAGMA journal_mode=WAL"));
TRY_STATUS(db.exec("PRAGMA temp_store=MEMORY"));
TRY_STATUS(db.exec("PRAGMA secure_delete=1"));
return Status::OK();
}
class MessagesDbBench : public Benchmark {
public:
string get_description() const override {
return "MessagesDb";
}
void start_up() override {
LOG(ERROR) << "START UP";
do_start_up().ensure();
scheduler_->start();
}
void run(int n) override {
auto guard = scheduler_->get_main_guard();
for (int i = 0; i < n; i += 20) {
auto dialog_id = DialogId{UserId{Random::fast(1, 100)}};
auto message_id_raw = Random::fast(1, 100000);
for (int j = 0; j < 20; j++) {
auto message_id = MessageId{ServerMessageId{message_id_raw + j}};
auto unique_message_id = ServerMessageId{i + 1};
auto sender_user_id = UserId{Random::fast(1, 1000)};
auto random_id = i + 1;
auto ttl_expires_at = 0;
auto data = BufferSlice(Random::fast(100, 299));
// use async on same thread.
messages_db_async_->add_message({dialog_id, message_id}, unique_message_id, sender_user_id, random_id,
ttl_expires_at, 0, 0, "", NotificationId(), MessageId(), std::move(data),
Promise<>());
}
}
}
void tear_down() override {
scheduler_->run_main(0.1);
{
auto guard = scheduler_->get_main_guard();
sql_connection_.reset();
messages_db_sync_safe_.reset();
messages_db_async_.reset();
}
scheduler_->finish();
scheduler_.reset();
LOG(ERROR) << "TEAR DOWN";
}
private:
td::unique_ptr<ConcurrentScheduler> scheduler_;
std::shared_ptr<SqliteConnectionSafe> sql_connection_;
std::shared_ptr<MessagesDbSyncSafeInterface> messages_db_sync_safe_;
std::shared_ptr<MessagesDbAsyncInterface> messages_db_async_;
Status do_start_up() {
scheduler_ = make_unique<ConcurrentScheduler>();
scheduler_->init(1);
auto guard = scheduler_->get_main_guard();
string sql_db_name = "testdb.sqlite";
sql_connection_ = std::make_shared<SqliteConnectionSafe>(sql_db_name);
auto &db = sql_connection_->get();
TRY_STATUS(init_db(db));
db.exec("BEGIN TRANSACTION").ensure();
// version == 0 ==> db will be destroyed
TRY_STATUS(init_messages_db(db, 0));
db.exec("COMMIT TRANSACTION").ensure();
messages_db_sync_safe_ = create_messages_db_sync(sql_connection_);
messages_db_async_ = create_messages_db_async(messages_db_sync_safe_, 0);
return Status::OK();
}
};
} // namespace td
int main() {
SET_VERBOSITY_LEVEL(VERBOSITY_NAME(WARNING));
bench(td::MessagesDbBench());
}
|
#include <omp.h>
#include <benchmark/benchmark.h>
#include <iostream>
#include <vector>
// L1: 32KB
// L2: 256KB
// L3: 12MB
constexpr size_t n = 1<<27; // 512MB
std::vector<float> a(n);
static uint32_t randomize(uint32_t i) {
i = (i ^ 61) ^ (i >> 16);
i *= 9;
i ^= i << 4;
i *= 0x27d4eb2d;
i ^= i >> 15;
return i;
}
void BM_ordered(benchmark::State &state) {
for (auto _: state) {
#pragma omp parallel for
for ( size_t i = 0; i < n; ++ i ) {
benchmark::DoNotOptimize(a[i]);
}
benchmark::DoNotOptimize(a);
}
}
BENCHMARK(BM_ordered);
void BM_random_64B(benchmark::State &state) {
for (auto _: state) {
#pragma omp parallel for
for ( size_t i = 0; i < n / 16; ++ i ) {
size_t r = randomize(i) % (n / 16);
for ( size_t j = 0; j < 16; ++ j ) {
benchmark::DoNotOptimize(a[r * 16 + j]);
}
}
benchmark::DoNotOptimize(a);
}
}
BENCHMARK(BM_random_64B);
void BM_random_4KB(benchmark::State &state) {
for (auto _: state) {
#pragma omp parallel for
for ( size_t i = 0; i < n / 1024; ++ i ) {
size_t r = randomize(i) % (n / 1024);
for ( size_t j = 0; j < 1024; ++ j ) {
benchmark::DoNotOptimize(a[r * 1024 + j]);
}
}
benchmark::DoNotOptimize(a);
}
}
BENCHMARK(BM_random_4KB);
void BM_random_4KB_aligned(benchmark::State &state) {
float *a = (float *)_mm_malloc(n * sizeof(float), 4096);
memset(a, 0, n * sizeof(float));
for (auto _: state) {
#pragma omp parallel for
for ( size_t i = 0; i < n / 1024; ++ i ) {
size_t r = randomize(i) % (n / 1024);
for ( size_t j = 0; j < 1024; ++ j ) {
benchmark::DoNotOptimize(a[r * 1024 + j]);
}
}
benchmark::DoNotOptimize(a);
}
_mm_free(a);
}
BENCHMARK(BM_random_4KB_aligned);
BENCHMARK_MAIN();
|
/*---------------------------------------------------------------------------*\
Copyright (C) 2015 Applied CCM
-------------------------------------------------------------------------------
License
This file is part of CAELUS.
CAELUS 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.
CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>.
Author
Oliver Borm
Aleksandar Jemcov
\*---------------------------------------------------------------------------*/
#include "hllcFlux.hpp"
void CML::hllcFlux::evaluateFlux
(
scalar& rhoFlux,
vector& rhoUFlux,
scalar& rhoEFlux,
scalar const pLeft,
scalar const pRight,
vector const ULeft,
vector const URight,
scalar const TLeft,
scalar const TRight,
scalar const RLeft,
scalar const RRight,
scalar const CvLeft,
scalar const CvRight,
vector const Sf,
scalar const magSf,
vector const dotX
) const
{
vector const normalVector = Sf/magSf;
scalar const kappaLeft = (RLeft + CvLeft)/CvLeft;
scalar const kappaRight = (RRight + CvRight)/CvRight;
scalar const rhoLeft = pLeft / ( RLeft * TLeft);
scalar const rhoRight = pRight / ( RLeft * TRight);
vector const rhoULeft = rhoLeft*ULeft;
vector const rhoURight = rhoRight*URight;
scalar const rhoELeft = rhoLeft*(CvLeft*TLeft+0.5*magSqr(ULeft));
scalar const rhoERight = rhoRight*(CvRight*TRight+0.5*magSqr(URight));
scalar const HLeft = (rhoELeft + pLeft)/rhoLeft;
scalar const HRight = (rhoERight + pRight)/rhoRight;
scalar const qLeft = (ULeft & normalVector);
scalar const qRight = (URight & normalVector);
scalar const aLeft =
sqrt(max(0.0,kappaLeft * pLeft/rhoLeft));
scalar const aRight =
sqrt(max(0.0,kappaRight * pRight/rhoRight));
scalar const rhoLeftSqrt = sqrt(max(0.0,rhoLeft));
scalar const rhoRightSqrt = sqrt(max(0.0,rhoRight));
scalar const wLeft = rhoLeftSqrt
/stabilise((rhoLeftSqrt + rhoRightSqrt),VSMALL);
scalar const wRight = 1 - wLeft;
vector const UTilde = wLeft*ULeft + wRight*URight;
scalar const contrUTilde = (UTilde & normalVector);
scalar const HTilde = wLeft*HLeft + wRight*HRight;
scalar const kappaTilde = wLeft*kappaLeft + wRight*kappaRight;
scalar const aTilde =
sqrt(max(0.0,(kappaTilde-1.0)*(HTilde-0.5*sqr(contrUTilde))));
scalar const SLeft = min(qLeft-aLeft, contrUTilde-aTilde);
scalar const SRight = max(contrUTilde+aTilde, qRight+aRight);
scalar const SStar = (rhoRight*qRight*(SRight-qRight)
- rhoLeft*qLeft*(SLeft - qLeft) + pLeft - pRight )/
stabilise((rhoRight*(SRight-qRight)-rhoLeft*(SLeft-qLeft)),VSMALL);
scalar const pStarRight =
rhoRight*(qRight - SRight)*(qRight - SStar) + pRight;
scalar const pStarLeft =
rhoLeft*(qLeft - SLeft)*(qLeft - SStar) + pLeft;
if (mag(pStarRight-pStarLeft) > 1e-6)
{
Info << "mag(pStarRight-pStarLeft) > VSMALL " << endl;
}
scalar const pStar = pStarRight;
scalar convectionSpeed = 0.0;
scalar rhoState = 0.0;
vector rhoUState = vector::zero;
scalar rhoEState = 0.0;
scalar pState = 0.0;
if (pos(SLeft))
{
convectionSpeed = qLeft;
rhoState = rhoLeft;
rhoUState = rhoULeft;
rhoEState = rhoELeft;
pState = pLeft;
}
else if (pos(SStar))
{
scalar omegaLeft = scalar(1.0)/stabilise((SLeft - SStar),VSMALL);
convectionSpeed = SStar;
rhoState = omegaLeft*(SLeft - qLeft)*rhoLeft;
rhoUState = omegaLeft*((SLeft - qLeft)*rhoULeft
+ (pStar - pLeft)*normalVector);
rhoEState = omegaLeft*((SLeft - qLeft)*rhoELeft
- pLeft*qLeft + pStar*SStar);
pState = pStar;
}
else if (pos(SRight))
{
scalar omegaRight = scalar(1.0)/stabilise((SRight - SStar),VSMALL);
convectionSpeed = SStar;
rhoState = omegaRight*(SRight - qRight)*rhoRight;
rhoUState = omegaRight*((SRight - qRight)*rhoURight
+ (pStar - pRight)*normalVector);
rhoEState = omegaRight*((SRight - qRight)*rhoERight
- pRight*qRight + pStar*SStar);
pState = pStar;
}
else if (neg(SRight))
{
convectionSpeed = qRight;
rhoState = rhoRight;
rhoUState = rhoURight;
rhoEState = rhoERight;
pState = pRight;
}
else
{
Info << "Error in HLLC Riemann solver" << endl;
}
rhoFlux = (convectionSpeed*rhoState)*magSf;
rhoUFlux = (convectionSpeed*rhoUState+pState*normalVector)*magSf;
rhoEFlux = (convectionSpeed*(rhoEState+pState))*magSf;
}
|
#include "graph/Edge.h"
#include "graph/Vertex.h"
#include "gtest/gtest.h"
TEST(Vertex, initialize) {
cuhksz::Vertex v[10];
v[0] = cuhksz::Vertex(3);
}
TEST(Vertex, getter) {
cuhksz::Vertex v(3);
EXPECT_EQ(v.getVal(), 3);
}
TEST(Vertex, setter) {
cuhksz::Vertex v(3);
v.setVal(5);
EXPECT_EQ(v.getVal(), 5);
}
TEST(Vertex, compare) {
cuhksz::Vertex v1(3), v2(5);
EXPECT_TRUE(v1 < v2);
}
TEST(Vertex, addEdge) {
cuhksz::Vertex v1(3);
cuhksz::Vertex v2(5);
v1.addEdge(v2);
EXPECT_EQ(v1.outEdges.front()->getTo()->getVal(), 5);
EXPECT_EQ(v2.inEdges.front()->getFrom()->getVal(), 3);
}
|
#include "RunGen.h"
using namespace Halide::RunGen;
using Halide::Tools::BenchmarkConfig;
namespace {
struct RegisteredFilter {
struct RegisteredFilter *next;
int (*filter_argv_call)(void **);
const struct halide_filter_metadata_t *filter_metadata;
};
RegisteredFilter *registered_filters = nullptr;
extern "C" void halide_register_argv_and_metadata(
int (*filter_argv_call)(void **),
const struct halide_filter_metadata_t *filter_metadata,
const char *const *extra_key_value_pairs) {
auto *rf = new RegisteredFilter();
rf->next = registered_filters;
rf->filter_argv_call = filter_argv_call;
rf->filter_metadata = filter_metadata;
// RunGen ignores extra_key_value_pairs
registered_filters = rf;
}
std::string replace_all(const std::string &str,
const std::string &find,
const std::string &replace) {
size_t pos = 0;
std::string result = str;
while ((pos = result.find(find, pos)) != std::string::npos) {
result.replace(pos, find.length(), replace);
pos += replace.length();
}
return result;
}
void usage(const char *argv0) {
const std::string usage = R"USAGE(
Usage: $NAME$ argument=value [argument=value... ] [flags]
Arguments:
Specify the Generator's input and output values by name, in any order.
Scalar inputs are specified in the obvious syntax, e.g.
some_int=42 some_float=3.1415
You can also use the text `default` or `estimate` to use the default or
estimate value of the given input, respectively. (You can join these by
commas to give default-then-estimate or estimate-then-default behaviors.)
Buffer inputs and outputs are specified by pathname:
some_input_buffer=/path/to/existing/file.png
some_output_buffer=/path/to/create/output/file.png
We currently support JPG, PGM, PNG, PPM format. If the type or dimensions
of the input or output file type can't support the data (e.g., your filter
uses float32 input and output, and you load/save to PNG), we'll use the most
robust approximation within the format and issue a warning to stdout.
(We anticipate adding other image formats in the future, in particular,
TIFF and TMP.)
For inputs, there are also "pseudo-file" specifiers you can use; currently
supported are
zero:[NUM,NUM,...]
This input should be an image with the given extents, and all elements
set to zero of the appropriate type. (This is useful for benchmarking
filters that don't have performance variances with different data.)
constant:VALUE:[NUM,NUM,...]
Like zero, but allows an arbitrary value of the input's type.
identity:[NUM,NUM,...]
This input should be an image with the given extents, where diagonal
elements are set to one of the appropriate type, and the rest are zero.
Diagonal elements are those whose first two coordinates are equal.
random:SEED:[NUM,NUM,...]
This input should be an image with the given extents, and all elements
set to a random value of the appropriate type. The random values will
be constructed using the mt19937_64 engine, using the given seed;
all floating point values will be in a uniform distribution between
0.0 and 1.0, while integral values will be uniform across the entire
range of the type.
(We anticipate adding other pseudo-file inputs in the future, e.g.
various random distributions, gradients, rainbows, etc.)
In place of [NUM,NUM,...] for boundary, you may specify 'auto'; this
will run a bounds-query to choose a legal input size given the output
size constraints. (In general, this is useful only when also using
the --output_extents flag.)
In place of [NUM,NUM,...] for boundary, you may specify 'estimate';
this will use the estimated bounds specified in the code.
Flags:
--describe:
print names and types of all arguments to stdout and exit.
--output_extents=[NUM,NUM,...]
By default, we attempt to calculate a reasonable size for the output
buffers, based on the size of the input buffers and bounds query; if we
guess wrong, or you want to explicitly specify the desired output size,
you can specify the extent of each dimension with this flag:
--output_extents=[1000,100] # 2 dimensions: w=1000 h = 100
--output_extents=[100,200,3] # 3 dimensions: w=100 h=200 c=3
Note that if there are multiple outputs, all will be constrained
to this shape.
--verbose:
emit extra diagnostic output.
--quiet:
Don't log calls to halide_print() to stdout.
--benchmarks=all:
Run the filter with the given arguments many times to
produce an estimate of average execution time; this currently
runs "samples" sets of "iterations" each, and chooses the fastest
sample set.
--benchmark_min_time=DURATION_SECONDS [default = 0.1]:
Override the default minimum desired benchmarking time; ignored if
--benchmarks is not also specified.
--track_memory:
Override Halide memory allocator to track high-water mark of memory
allocation during run; note that this may slow down execution, so
benchmarks may be inaccurate if you combine --benchmark with this.
--default_input_buffers=VALUE:
Specify the value for all otherwise-unspecified buffer inputs, in the
same syntax in use above. If you omit =VALUE, "zero:auto" will be used.
--default_input_scalars=VALUE:
Specify the value for all otherwise-unspecified scalar inputs, in the
same syntax in use above. If you omit =VALUE, "estimate,default"
will be used.
--parsable_output:
Final output is emitted in an easy-to-parse output (one value per line),
rather than easy-for-humans.
--estimate_all:
Request that all inputs and outputs are based on estimate,
and fill buffers with random values. This is exactly equivalent to
specifying
--default_input_buffers=estimate_then_auto
--default_input_scalars=estimate
--output_extents=estimate
and is a convenience for automated benchmarking.
Known Issues:
* Filters running on GPU (vs CPU) have not been tested.
* Filters using buffer layouts other than planar (e.g. interleaved/chunky)
may be buggy.
)USAGE";
std::string basename = split_string(replace_all(argv0, "\\", "/"), "/").back();
std::cout << replace_all(usage, "$NAME$", basename);
}
// Utility class for installing memory-tracking machinery into the Halide runtime
// when --track_memory is specified.
class HalideMemoryTracker {
static HalideMemoryTracker *active;
std::mutex tracker_mutex;
// Total current CPU memory allocated via halide_malloc.
// Access controlled by tracker_mutex.
uint64_t memory_allocated{0};
// High-water mark of CPU memory allocated since program start
// (or last call to get_cpu_memory_highwater_reset).
// Access controlled by tracker_mutex.
uint64_t memory_highwater{0};
// Map of outstanding allocation sizes.
// Access controlled by tracker_mutex.
std::map<void *, size_t> memory_size_map;
void *tracker_malloc_impl(void *user_context, size_t x) {
std::lock_guard<std::mutex> lock(tracker_mutex);
void *ptr = halide_default_malloc(user_context, x);
memory_allocated += x;
if (memory_highwater < memory_allocated) {
memory_highwater = memory_allocated;
}
if (memory_size_map.find(ptr) != memory_size_map.end()) {
halide_error(user_context, "Tracking error in tracker_malloc");
}
memory_size_map[ptr] = x;
return ptr;
}
void tracker_free_impl(void *user_context, void *ptr) {
std::lock_guard<std::mutex> lock(tracker_mutex);
auto it = memory_size_map.find(ptr);
if (it == memory_size_map.end()) {
halide_error(user_context, "Tracking error in tracker_free");
}
size_t x = it->second;
memory_allocated -= x;
memory_size_map.erase(it);
halide_default_free(user_context, ptr);
}
static void *tracker_malloc(void *user_context, size_t x) {
return active->tracker_malloc_impl(user_context, x);
}
static void tracker_free(void *user_context, void *ptr) {
return active->tracker_free_impl(user_context, ptr);
}
public:
void install() {
assert(!active);
active = this;
halide_set_custom_malloc(tracker_malloc);
halide_set_custom_free(tracker_free);
}
uint64_t allocated() {
std::lock_guard<std::mutex> lock(tracker_mutex);
return memory_allocated;
}
uint64_t highwater() {
std::lock_guard<std::mutex> lock(tracker_mutex);
return memory_highwater;
}
void highwater_reset() {
std::lock_guard<std::mutex> lock(tracker_mutex);
memory_highwater = memory_allocated;
}
};
/* static */ HalideMemoryTracker *HalideMemoryTracker::active{nullptr};
bool log_info = false;
bool log_warn = true;
void do_log_cout(const std::string &s) {
std::cout << s;
}
void do_log_cerr(const std::string &s) {
std::cerr << s;
}
void do_log_info(const std::string &s) {
if (log_info) {
do_log_cerr(s);
}
}
void do_log_warn(const std::string &s) {
if (log_warn) {
do_log_cerr("Warning: " + s);
}
}
void do_log_fail(const std::string &s) {
do_log_cerr(s);
abort();
}
} // namespace
namespace Halide {
namespace RunGen {
Logger log() {
return {do_log_cout, do_log_info, do_log_warn, do_log_fail};
}
} // namespace RunGen
} // namespace Halide
int main(int argc, char **argv) {
if (argc <= 1) {
usage(argv[0]);
return 0;
}
if (registered_filters == nullptr) {
std::cerr << "No filters registered. Compile RunGenMain.cpp along with at least one 'registration' output from a generator.\n";
return -1;
}
// Look for --name
std::string filter_name;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
const char *p = argv[i] + 1; // skip -
if (p[0] == '-') {
p++; // allow -- as well, because why not
}
std::vector<std::string> v = split_string(p, "=");
std::string flag_name = v[0];
std::string flag_value = v.size() > 1 ? v[1] : "";
if (v.size() > 2) {
fail() << "Invalid argument: " << argv[i];
}
if (flag_name != "name") {
continue;
}
if (!filter_name.empty()) {
fail() << "--name cannot be specified twice.";
}
filter_name = flag_value;
if (filter_name.empty()) {
fail() << "--name cannot be empty.";
}
}
}
auto *rf = registered_filters;
if (filter_name.empty()) {
// Just choose the first one.
if (rf->next != nullptr) {
std::ostringstream o;
o << "Must specify --name if multiple filters are registered; registered filters are:\n";
for (auto *rf = registered_filters; rf != nullptr; rf = rf->next) {
o << " " << rf->filter_metadata->name << "\n";
}
o << "\n";
fail() << o.str();
}
} else {
for (; rf != nullptr; rf = rf->next) {
if (filter_name == rf->filter_metadata->name) {
break;
}
}
if (rf == nullptr) {
std::ostringstream o;
o << "Filter " << filter_name << " not found; registered filters are:\n";
for (auto *rf = registered_filters; rf != nullptr; rf = rf->next) {
o << " " << rf->filter_metadata->name << "\n";
}
o << "\n";
fail() << o.str();
}
}
RunGen r(rf->filter_argv_call, rf->filter_metadata);
std::string user_specified_output_shape;
std::set<std::string> seen_args;
bool benchmark = false;
bool track_memory = false;
bool describe = false;
double benchmark_min_time = BenchmarkConfig().min_time;
std::string default_input_buffers;
std::string default_input_scalars;
std::string benchmarks_flag_value;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
const char *p = argv[i] + 1; // skip -
if (p[0] == '-') {
p++; // allow -- as well, because why not
}
std::vector<std::string> v = split_string(p, "=");
std::string flag_name = v[0];
std::string flag_value = v.size() > 1 ? v[1] : "";
if (v.size() > 2) {
fail() << "Invalid argument: " << argv[i];
}
if (flag_name == "name") {
continue;
} else if (flag_name == "verbose") {
if (flag_value.empty()) {
flag_value = "true";
}
if (!parse_scalar(flag_value, &log_info)) {
fail() << "Invalid value for flag: " << flag_name;
}
} else if (flag_name == "quiet") {
if (flag_value.empty()) {
flag_value = "true";
}
bool quiet;
if (!parse_scalar(flag_value, &quiet)) {
fail() << "Invalid value for flag: " << flag_name;
}
r.set_quiet(quiet);
} else if (flag_name == "parsable_output") {
if (flag_value.empty()) {
flag_value = "true";
}
bool parsable_output;
if (!parse_scalar(flag_value, &parsable_output)) {
fail() << "Invalid value for flag: " << flag_name;
}
r.set_parsable_output(parsable_output);
} else if (flag_name == "describe") {
if (flag_value.empty()) {
flag_value = "true";
}
if (!parse_scalar(flag_value, &describe)) {
fail() << "Invalid value for flag: " << flag_name;
}
} else if (flag_name == "track_memory") {
if (flag_value.empty()) {
flag_value = "true";
}
if (!parse_scalar(flag_value, &track_memory)) {
fail() << "Invalid value for flag: " << flag_name;
}
} else if (flag_name == "benchmarks") {
benchmarks_flag_value = flag_value;
benchmark = true;
} else if (flag_name == "benchmark_min_time") {
if (!parse_scalar(flag_value, &benchmark_min_time)) {
fail() << "Invalid value for flag: " << flag_name;
}
} else if (flag_name == "default_input_buffers") {
default_input_buffers = flag_value;
if (default_input_buffers.empty()) {
default_input_buffers = "zero:auto";
}
} else if (flag_name == "default_input_scalars") {
default_input_scalars = flag_value;
if (default_input_scalars.empty()) {
default_input_scalars = "estimate,default";
}
} else if (flag_name == "output_extents") {
user_specified_output_shape = flag_value;
} else if (flag_name == "estimate_all") {
// Equivalent to:
// --default_input_buffers=random:0:estimate_then_auto
// --default_input_scalars=estimate
// --output_extents=estimate
default_input_buffers = "random:0:estimate_then_auto";
default_input_scalars = "estimate";
user_specified_output_shape = "estimate";
} else {
usage(argv[0]);
fail() << "Unknown flag: " << flag_name;
}
} else {
// Assume it's a named Input or Output for the Generator,
// in the form name=value.
std::vector<std::string> v = split_string(argv[i], "=");
if (v.size() != 2 || v[0].empty() || v[1].empty()) {
fail() << "Invalid argument: " << argv[i];
}
r.parse_one(v[0], v[1], &seen_args);
}
}
if (describe) {
r.describe();
return 0;
}
// It's OK to omit output arguments when we are benchmarking or tracking memory.
bool ok_to_omit_outputs = (benchmark || track_memory);
if (benchmark && track_memory) {
warn() << "Using --track_memory with --benchmarks will produce inaccurate benchmark results.";
}
// Check to be sure that all required arguments are specified.
r.validate(seen_args, default_input_buffers, default_input_scalars, ok_to_omit_outputs);
// Parse all the input arguments, loading images as necessary.
// (Don't handle outputs yet.)
r.load_inputs(user_specified_output_shape);
// Run a bounds query: we need to figure out how to allocate the output buffers,
// and the input buffers might need reshaping to satisfy constraints (e.g. a chunky/interleaved layout).
std::vector<Shape> constrained_shapes = r.run_bounds_query();
r.adapt_input_buffers(constrained_shapes);
r.allocate_output_buffers(constrained_shapes);
// If we're tracking memory, install the memory tracker *after* doing a bounds query.
HalideMemoryTracker tracker;
if (track_memory) {
tracker.install();
}
// This is a single-purpose binary to benchmark this filter, so we
// shouldn't be eagerly returning device memory.
halide_reuse_device_allocations(nullptr, true);
if (benchmark) {
if (benchmarks_flag_value.empty()) {
benchmarks_flag_value = "all";
}
if (benchmarks_flag_value != "all") {
fail() << "The only valid value for --benchmarks is 'all'";
}
r.run_for_benchmark(benchmark_min_time);
} else {
r.run_for_output();
}
if (track_memory) {
// Ensure that we copy any GPU-output buffers back to host before
// we report on memory usage.
r.copy_outputs_to_host();
std::cout << "Maximum Halide memory: " << tracker.highwater()
<< " bytes for output of " << r.megapixels_out() << " mpix.\n";
}
// Save the output(s), if necessary.
r.save_outputs();
return 0;
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Dan Larkin-York
////////////////////////////////////////////////////////////////////////////////
#include "RestoreFeature.h"
#include <velocypack/Builder.h>
#include <velocypack/Collection.h>
#include <velocypack/Iterator.h>
#include <velocypack/StringRef.h>
#include <velocypack/velocypack-aliases.h>
#include <boost/algorithm/clamp.hpp>
#include <chrono>
#include <thread>
#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/FileUtils.h"
#include "Basics/Result.h"
#include "Basics/StaticStrings.h"
#include "Basics/StringUtils.h"
#include "Basics/VelocyPackHelper.h"
#include "Basics/application-exit.h"
#include "Basics/files.h"
#include "Basics/system-functions.h"
#include "FeaturePhases/BasicFeaturePhaseClient.h"
#include "Logger/LogMacros.h"
#include "Logger/Logger.h"
#include "Logger/LoggerStream.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Shell/ClientFeature.h"
#include "SimpleHttpClient/GeneralClientConnection.h"
#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"
#include "Ssl/SslInterface.h"
#ifdef USE_ENTERPRISE
#include "Enterprise/Encryption/EncryptionFeature.h"
#endif
namespace {
/// @brief name of the feature to report to application server
constexpr auto FeatureName = "Restore";
/// @brief return the target replication factor for the specified collection
uint64_t getReplicationFactor(arangodb::RestoreFeature::Options const& options,
arangodb::velocypack::Slice const& slice, bool& isSatellite) {
uint64_t result = options.defaultReplicationFactor;
isSatellite = false;
arangodb::velocypack::Slice s = slice.get(arangodb::StaticStrings::ReplicationFactor);
if (s.isInteger()) {
result = s.getNumericValue<uint64_t>();
} else if (s.isString()) {
if (s.copyString() == arangodb::StaticStrings::Satellite) {
isSatellite = true;
}
}
s = slice.get("name");
if (!s.isString()) {
// should not happen, but anyway, let's be safe here
return result;
}
if (!options.replicationFactor.empty()) {
std::string const name = s.copyString();
for (auto const& it : options.replicationFactor) {
auto parts = arangodb::basics::StringUtils::split(it, '=');
if (parts.size() == 1) {
// this is the default value, e.g. `--replicationFactor 2`
if (parts[0] == arangodb::StaticStrings::Satellite) {
isSatellite = true;
} else {
result = arangodb::basics::StringUtils::uint64(parts[0]);
}
}
// look if we have a more specific value, e.g. `--replicationFactor myCollection=3`
if (parts.size() != 2 || parts[0] != name) {
// somehow invalid or different collection
continue;
}
if (parts[1] == arangodb::StaticStrings::Satellite) {
isSatellite = true;
} else {
result = arangodb::basics::StringUtils::uint64(parts[1]);
}
break;
}
}
return result;
}
/// @brief return the target number of shards for the specified collection
uint64_t getNumberOfShards(arangodb::RestoreFeature::Options const& options,
arangodb::velocypack::Slice const& slice) {
uint64_t result = options.defaultNumberOfShards;
arangodb::velocypack::Slice s = slice.get("numberOfShards");
if (s.isInteger()) {
result = s.getNumericValue<uint64_t>();
}
s = slice.get("name");
if (!s.isString()) {
// should not happen, but anyway, let's be safe here
return result;
}
if (!options.numberOfShards.empty()) {
std::string const name = s.copyString();
for (auto const& it : options.numberOfShards) {
auto parts = arangodb::basics::StringUtils::split(it, '=');
if (parts.size() == 1) {
// this is the default value, e.g. `--numberOfShards 2`
result = arangodb::basics::StringUtils::uint64(parts[0]);
}
// look if we have a more specific value, e.g. `--numberOfShards myCollection=3`
if (parts.size() != 2 || parts[0] != name) {
// somehow invalid or different collection
continue;
}
result = arangodb::basics::StringUtils::uint64(parts[1]);
break;
}
}
return result;
}
/// @brief check whether HTTP response is valid, complete, and not an error
arangodb::Result checkHttpResponse(arangodb::httpclient::SimpleHttpClient& client,
std::unique_ptr<arangodb::httpclient::SimpleHttpResult>& response,
char const* requestAction,
std::string const& originalRequest) {
using arangodb::basics::StringUtils::itoa;
if (response == nullptr || !response->isComplete()) {
return {TRI_ERROR_INTERNAL,
"got invalid response from server: '" + client.getErrorMessage() +
"' while executing " + requestAction + (originalRequest.empty() ? "" : " with this payload: '" +
originalRequest + "'")};
}
if (response->wasHttpError()) {
int errorNum = TRI_ERROR_INTERNAL;
std::string errorMsg = response->getHttpReturnMessage();
std::shared_ptr<arangodb::velocypack::Builder> bodyBuilder(response->getBodyVelocyPack());
arangodb::velocypack::Slice error = bodyBuilder->slice();
if (!error.isNone() && error.hasKey(arangodb::StaticStrings::ErrorMessage)) {
errorNum = error.get(arangodb::StaticStrings::ErrorNum).getNumericValue<int>();
errorMsg = error.get(arangodb::StaticStrings::ErrorMessage).copyString();
}
return {errorNum, "got invalid response from server: HTTP " +
itoa(response->getHttpReturnCode()) + ": '" +
errorMsg + "' while executing '" + requestAction +
(originalRequest.empty() ? "" : "' with this payload: '" + originalRequest + "'")};
}
return {TRI_ERROR_NO_ERROR};
}
/// @brief Sort collections for proper recreation order
bool sortCollectionsForCreation(VPackBuilder const& l, VPackBuilder const& r) {
VPackSlice const left = l.slice().get("parameters");
VPackSlice const right = r.slice().get("parameters");
std::string leftName =
arangodb::basics::VelocyPackHelper::getStringValue(left, "name", "");
std::string rightName =
arangodb::basics::VelocyPackHelper::getStringValue(right, "name", "");
// First we sort by shard distribution.
// We first have to create the collections which have no dependencies.
// NB: Dependency graph has depth at most 1, no need to manage complex DAG
VPackSlice leftDist = left.get("distributeShardsLike");
VPackSlice rightDist = right.get("distributeShardsLike");
if (leftDist.isNone() && rightDist.isString() &&
rightDist.copyString() == leftName) {
return true;
}
if (rightDist.isNone() && leftDist.isString() &&
leftDist.copyString() == rightName) {
return false;
}
// Next we sort by collection type so that vertex collections are recreated
// before edge, etc.
int leftType =
arangodb::basics::VelocyPackHelper::getNumericValue<int>(left, "type", 0);
int rightType =
arangodb::basics::VelocyPackHelper::getNumericValue<int>(right, "type", 0);
if (leftType != rightType) {
return leftType < rightType;
}
// Finally, sort by name so we have stable, reproducible results
// Sort system collections first
if (!leftName.empty() && leftName[0] == '_' &&
!rightName.empty() && rightName[0] != '_') {
return true;
}
if (!leftName.empty() && leftName[0] != '_' &&
!rightName.empty() && rightName[0] == '_') {
return false;
}
return strcasecmp(leftName.c_str(), rightName.c_str()) < 0;
}
void makeAttributesUnique(arangodb::velocypack::Builder& builder,
arangodb::velocypack::Slice slice) {
if (slice.isObject()) {
std::unordered_set<arangodb::velocypack::StringRef> keys;
builder.openObject();
auto it = arangodb::velocypack::ObjectIterator(slice, true);
while (it.valid()) {
if (!keys.emplace(it.key().stringRef()).second) {
// duplicate key
it.next();
continue;
}
// process attributes recursively
builder.add(it.key());
makeAttributesUnique(builder, it.value());
it.next();
}
builder.close();
} else if (slice.isArray()) {
builder.openArray();
auto it = arangodb::velocypack::ArrayIterator(slice);
while (it.valid()) {
// recurse into array
makeAttributesUnique(builder, it.value());
it.next();
}
builder.close();
} else {
// non-compound value!
builder.add(slice);
}
}
/// @brief Create the database to restore to, connecting manually
arangodb::Result tryCreateDatabase(arangodb::application_features::ApplicationServer& server,
std::string const& name) {
using arangodb::httpclient::SimpleHttpClient;
using arangodb::httpclient::SimpleHttpResult;
using arangodb::rest::RequestType;
using arangodb::rest::ResponseCode;
using arangodb::velocypack::ArrayBuilder;
using arangodb::velocypack::ObjectBuilder;
// get client feature for configuration info
arangodb::ClientFeature& client =
server.getFeature<arangodb::HttpEndpointProvider, arangodb::ClientFeature>();
// get httpclient by hand rather than using manager, to bypass any built-in
// checks which will fail if the database doesn't exist
std::unique_ptr<SimpleHttpClient> httpClient;
try {
httpClient = client.createHttpClient();
httpClient->params().setLocationRewriter(static_cast<void*>(&client),
arangodb::ClientManager::rewriteLocation);
httpClient->params().setUserNamePassword("/", client.username(), client.password());
} catch (...) {
LOG_TOPIC("832ef", FATAL, arangodb::Logger::RESTORE)
<< "cannot create server connection, giving up!";
return {TRI_ERROR_SIMPLE_CLIENT_COULD_NOT_CONNECT};
}
VPackBuilder builder;
{
ObjectBuilder object(&builder);
object->add("name", VPackValue(name));
{
ArrayBuilder users(&builder, "users");
{
ObjectBuilder user(&builder);
user->add("username", VPackValue(client.username()));
user->add("passwd", VPackValue(client.password()));
}
}
}
std::string const body = builder.slice().toJson();
std::unique_ptr<SimpleHttpResult> response(
httpClient->request(RequestType::POST, "/_api/database", body.c_str(), body.size()));
if (response == nullptr || !response->isComplete()) {
return {TRI_ERROR_INTERNAL};
}
auto returnCode = response->getHttpReturnCode();
if (returnCode == static_cast<int>(ResponseCode::OK) ||
returnCode == static_cast<int>(ResponseCode::CREATED)) {
// all ok
return {TRI_ERROR_NO_ERROR};
}
if (returnCode == static_cast<int>(ResponseCode::UNAUTHORIZED) ||
returnCode == static_cast<int>(ResponseCode::FORBIDDEN)) {
// invalid authorization
auto res = ::checkHttpResponse(*httpClient, response, "creating database", body);
return {TRI_ERROR_FORBIDDEN, res.errorMessage()};
}
// any other error
auto res = ::checkHttpResponse(*httpClient, response, "creating database", body);
return {TRI_ERROR_INTERNAL, res.errorMessage()};
}
/// @check If directory is encrypted, check that key option is specified
void checkEncryption(arangodb::ManagedDirectory& directory) {
using arangodb::Logger;
if (directory.isEncrypted()) {
#ifdef USE_ENTERPRISE
if (!directory.encryptionFeature()->keyOptionSpecified()) {
LOG_TOPIC("cc58e", WARN, Logger::RESTORE)
<< "the dump data seems to be encrypted with " << directory.encryptionType()
<< ", but no key information was specified to decrypt the dump";
LOG_TOPIC("1a5a4", WARN, Logger::RESTORE)
<< "it is recommended to specify either "
"`--encryption.keyfile` or `--encryption.key-generator` "
"when invoking arangorestore with an encrypted dump";
} else {
LOG_TOPIC("4f9cf", INFO, Logger::RESTORE)
<< "# using encryption type " << directory.encryptionType()
<< " for reading dump";
}
#endif
}
}
/// @brief Check the database name specified by the dump file
arangodb::Result checkDumpDatabase(arangodb::application_features::ApplicationServer& server,
arangodb::ManagedDirectory& directory,
bool forceSameDatabase) {
using arangodb::ClientFeature;
using arangodb::HttpEndpointProvider;
using arangodb::Logger;
using arangodb::application_features::ApplicationServer;
std::string databaseName;
try {
VPackBuilder fileContentBuilder = directory.vpackFromJsonFile("dump.json");
VPackSlice const fileContent = fileContentBuilder.slice();
databaseName = fileContent.get("database").copyString();
} catch (...) {
// the above may go wrong for several reasons
}
if (!databaseName.empty()) {
LOG_TOPIC("abeb4", INFO, Logger::RESTORE)
<< "Database name in source dump is '" << databaseName << "'";
}
ClientFeature& client = server.getFeature<HttpEndpointProvider, ClientFeature>();
if (forceSameDatabase && databaseName != client.databaseName()) {
return {TRI_ERROR_BAD_PARAMETER,
std::string("database name in dump.json ('") + databaseName +
"') does not match specified database name ('" +
client.databaseName() + "')"};
}
return {};
}
/// @brief Send the command to recreate a collection
arangodb::Result sendRestoreCollection(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::Options const& options,
VPackSlice const& slice, std::string const& name) {
using arangodb::Logger;
using arangodb::httpclient::SimpleHttpResult;
std::string url =
"/_api/replication/restore-collection"
"?overwrite=" +
std::string(options.overwrite ? "true" : "false") +
"&force=" + std::string(options.force ? "true" : "false") +
"&ignoreDistributeShardsLikeErrors=" +
std::string(options.ignoreDistributeShardsLikeErrors ? "true" : "false");
VPackSlice const parameters = slice.get("parameters");
// build cluster options using command-line parameter values
VPackBuilder newOptions;
newOptions.openObject();
bool isSatellite = false;
uint64_t replicationFactor = getReplicationFactor(options, parameters, isSatellite);
if (isSatellite) {
newOptions.add(arangodb::StaticStrings::ReplicationFactor, VPackValue(arangodb::StaticStrings::Satellite));
} else {
newOptions.add(arangodb::StaticStrings::ReplicationFactor, VPackValue(replicationFactor));
}
newOptions.add(arangodb::StaticStrings::NumberOfShards, VPackValue(getNumberOfShards(options, parameters)));
newOptions.close();
VPackBuilder b;
b.openObject();
b.add("indexes", slice.get("indexes"));
b.add(VPackValue("parameters"));
VPackCollection::merge(b, parameters, newOptions.slice(), true, false);
b.close();
std::string const body = b.slice().toJson();
std::unique_ptr<SimpleHttpResult> response(
httpClient.request(arangodb::rest::RequestType::PUT, url, body.c_str(), body.size()));
return ::checkHttpResponse(httpClient, response, "restoring collection", body);
}
/// @brief Send command to restore a collection's indexes
arangodb::Result sendRestoreIndexes(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::Options const& options,
VPackSlice const& slice) {
using arangodb::httpclient::SimpleHttpResult;
std::string const url = "/_api/replication/restore-indexes?force=" +
std::string(options.force ? "true" : "false");
std::string const body = slice.toJson();
std::unique_ptr<SimpleHttpResult> response(
httpClient.request(arangodb::rest::RequestType::PUT, url, body.c_str(), body.size()));
return ::checkHttpResponse(httpClient, response, "restoring indexes", body);
}
/// @brief Send a command to restore actual data
arangodb::Result sendRestoreData(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::Options const& options,
std::string const& cname, char const* buffer,
size_t bufferSize) {
using arangodb::basics::StringUtils::urlEncode;
using arangodb::httpclient::SimpleHttpResult;
// the following two structs are needed for cleaning up duplicate attributes
arangodb::velocypack::Builder result;
arangodb::basics::StringBuffer cleaned;
if (options.cleanupDuplicateAttributes) {
int res = cleaned.reserve(bufferSize);
if (res != TRI_ERROR_NO_ERROR) {
// out of memory
THROW_ARANGO_EXCEPTION(res);
}
arangodb::velocypack::Options options = arangodb::velocypack::Options::Defaults;
// do *not* check duplicate attributes here (because that would throw)
options.checkAttributeUniqueness = false;
arangodb::velocypack::Builder builder(&options);
// instead, we need to manually check for duplicate attributes...
char const* p = buffer;
char const* e = p + bufferSize;
while (p < e) {
while (p < e && (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t')) {
++p;
}
// detect line ending
size_t length;
char const* nl = static_cast<char const*>(memchr(p, '\n', e - p));
if (nl == nullptr) {
length = e - p;
} else {
length = nl - p;
}
builder.clear();
try {
VPackParser parser(builder, builder.options);
parser.parse(p, length);
} catch (arangodb::velocypack::Exception const& ex) {
return {TRI_ERROR_HTTP_CORRUPTED_JSON, ex.what()};
} catch (std::bad_alloc const&) {
return {TRI_ERROR_OUT_OF_MEMORY};
} catch (std::exception const& ex) {
return {TRI_ERROR_INTERNAL, ex.what()};
}
// recursively clean up duplicate attributes in the document
result.clear();
makeAttributesUnique(result, builder.slice());
std::string const json = result.toJson();
cleaned.appendText(json.data(), json.size());
if (nl == nullptr) {
// done
break;
}
cleaned.appendChar('\n');
// advance behind newline
p = nl + 1;
}
// now point to the cleaned up data
buffer = cleaned.c_str();
bufferSize = cleaned.length();
}
std::string const url = "/_api/replication/restore-data?collection=" + urlEncode(cname) +
"&force=" + (options.force ? "true" : "false");
std::unique_ptr<SimpleHttpResult> response(
httpClient.request(arangodb::rest::RequestType::PUT, url, buffer, bufferSize));
return ::checkHttpResponse(httpClient, response, "restoring data", "");
}
/// @brief Recreate a collection given its description
arangodb::Result recreateCollection(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::JobData& jobData) {
using arangodb::Logger;
arangodb::Result result;
VPackSlice const parameters = jobData.collection.get("parameters");
std::string const cname =
arangodb::basics::VelocyPackHelper::getStringValue(parameters, "name", "");
int type = arangodb::basics::VelocyPackHelper::getNumericValue<int>(parameters,
"type", 2);
std::string const collectionType(type == 2 ? "document" : "edge");
// re-create collection
if (jobData.options.progress) {
if (jobData.options.overwrite) {
LOG_TOPIC("9b414", INFO, Logger::RESTORE) << "# Re-creating " << collectionType
<< " collection '" << cname << "'...";
} else {
LOG_TOPIC("a9123", INFO, Logger::RESTORE) << "# Creating " << collectionType
<< " collection '" << cname << "'...";
}
}
result = ::sendRestoreCollection(httpClient, jobData.options, jobData.collection, cname);
if (result.fail()) {
if (jobData.options.force) {
LOG_TOPIC("c6658", WARN, Logger::RESTORE)
<< "Error while creating " << collectionType << " collection '"
<< cname << "': " << result.errorMessage();
result.reset();
} else {
LOG_TOPIC("e8e7a", ERR, Logger::RESTORE)
<< "Error while creating " << collectionType << " collection '"
<< cname << "': " << result.errorMessage();
}
}
return result;
}
/// @brief Restore a collection's indexes given its description
arangodb::Result restoreIndexes(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::JobData& jobData) {
using arangodb::Logger;
arangodb::Result result;
VPackSlice const parameters = jobData.collection.get("parameters");
VPackSlice const indexes = jobData.collection.get("indexes");
// re-create indexes
if (indexes.length() > 0) {
// we actually have indexes
if (jobData.options.progress) {
std::string const cname =
arangodb::basics::VelocyPackHelper::getStringValue(parameters, "name",
"");
LOG_TOPIC("d88c6", INFO, Logger::RESTORE)
<< "# Creating indexes for collection '" << cname << "'...";
}
result = ::sendRestoreIndexes(httpClient, jobData.options, jobData.collection);
if (result.fail()) {
std::string const cname =
arangodb::basics::VelocyPackHelper::getStringValue(parameters, "name",
"");
if (jobData.options.force) {
LOG_TOPIC("db937", WARN, Logger::RESTORE)
<< "Error while creating indexes for collection '" << cname
<< "': " << result.errorMessage();
result.reset();
} else {
LOG_TOPIC("d5d06", ERR, Logger::RESTORE)
<< "Error while creating indexes for collection '" << cname
<< "': " << result.errorMessage();
}
}
}
return result;
}
/// @brief Restore the data for a given collection
arangodb::Result restoreData(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::JobData& jobData) {
using arangodb::Logger;
using arangodb::basics::StringBuffer;
arangodb::Result result;
StringBuffer buffer(true);
VPackSlice const parameters = jobData.collection.get("parameters");
std::string const cname =
arangodb::basics::VelocyPackHelper::getStringValue(parameters, "name", "");
int type = arangodb::basics::VelocyPackHelper::getNumericValue<int>(parameters,
"type", 2);
std::string const collectionType(type == 2 ? "document" : "edge");
// import data. check if we have a datafile
// ... there are 4 possible names
auto datafile = jobData.directory.readableFile(
cname + "_" + arangodb::rest::SslInterface::sslMD5(cname) + ".data.json");
if (!datafile || datafile->status().fail()) {
datafile = jobData.directory.readableFile(
cname + "_" + arangodb::rest::SslInterface::sslMD5(cname) + ".data.json.gz");
}
if (!datafile || datafile->status().fail()) {
datafile = jobData.directory.readableFile(cname + ".data.json.gz");
}
if (!datafile || datafile->status().fail()) {
datafile = jobData.directory.readableFile(cname + ".data.json");
}
if (!datafile || datafile->status().fail()) {
result = {TRI_ERROR_CANNOT_READ_FILE, "could not open data file for collection '" + cname + "'"};
return result;
}
int64_t const fileSize = TRI_SizeFile(datafile->path().c_str());
if (jobData.options.progress) {
LOG_TOPIC("94913", INFO, Logger::RESTORE)
<< "# Loading data into " << collectionType << " collection '" << cname
<< "', data size: " << fileSize << " byte(s)";
}
int64_t numReadForThisCollection = 0;
int64_t numReadSinceLastReport = 0;
bool const isGzip = (0 == datafile->path().substr(datafile->path().size() - 3).compare(".gz"));
buffer.clear();
while (true) {
if (buffer.reserve(16384) != TRI_ERROR_NO_ERROR) {
result = {TRI_ERROR_OUT_OF_MEMORY, "out of memory"};
return result;
}
ssize_t numRead = datafile->read(buffer.end(), 16384);
if (datafile->status().fail()) { // error while reading
result = datafile->status();
return result;
}
// we read something
buffer.increaseLength(numRead);
jobData.stats.totalRead += static_cast<uint64_t>(numRead);
numReadForThisCollection += numRead;
numReadSinceLastReport += numRead;
if (buffer.length() < jobData.options.chunkSize && numRead > 0) {
continue; // still continue reading
}
// do we have a buffer?
if (buffer.length() > 0) {
// look for the last \n in the buffer
char* found = (char*)memrchr((const void*)buffer.begin(), '\n', buffer.length());
size_t length;
if (found == nullptr) { // no \n in buffer...
if (numRead == 0) {
// we're at the end of the file, so send the complete buffer anyway
length = buffer.length();
} else {
continue; // don't have a complete line yet, read more
}
} else {
length = found - buffer.begin(); // found a \n somewhere; break at line
}
jobData.stats.totalBatches++;
result = ::sendRestoreData(httpClient, jobData.options, cname, buffer.begin(), length);
jobData.stats.totalSent += length;
if (result.fail()) {
if (jobData.options.force) {
LOG_TOPIC("a595a", WARN, Logger::RESTORE)
<< "Error while restoring data into collection '" << cname
<< "': " << result.errorMessage();
result.reset();
continue;
} else {
LOG_TOPIC("a89bf", ERR, Logger::RESTORE)
<< "Error while restoring data into collection '" << cname
<< "': " << result.errorMessage();
}
return result;
}
buffer.erase_front(length);
if (jobData.options.progress && fileSize > 0 &&
numReadSinceLastReport > 1024 * 1024 * 8) {
// report every 8MB of transferred data
// currently do not have unzipped size for .gz files
std::stringstream percentage, ofFilesize;
if (isGzip) {
ofFilesize << "";
percentage << "";
} else {
ofFilesize << " of " << fileSize;
percentage << " ("
<< int(100. * double(numReadForThisCollection) / double(fileSize)) << " %)";
} // else
LOG_TOPIC("69a73", INFO, Logger::RESTORE)
<< "# Still loading data into " << collectionType << " collection '"
<< cname << "', " << numReadForThisCollection << ofFilesize.str()
<< " byte(s) restored" << percentage.str();
numReadSinceLastReport = 0;
}
}
if (numRead == 0) { // EOF
break;
}
}
return result;
}
/// @brief Restore the data for a given view
arangodb::Result restoreView(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::Options const& options,
VPackSlice const& viewDefinition) {
using arangodb::httpclient::SimpleHttpResult;
std::string url = "/_api/replication/restore-view?overwrite=" +
std::string(options.overwrite ? "true" : "false") +
"&force=" + std::string(options.force ? "true" : "false");
std::string const body = viewDefinition.toJson();
std::unique_ptr<SimpleHttpResult> response(
httpClient.request(arangodb::rest::RequestType::PUT, url, body.c_str(), body.size()));
return ::checkHttpResponse(httpClient, response, "restoring view", body);
}
arangodb::Result triggerFoxxHeal(arangodb::httpclient::SimpleHttpClient& httpClient) {
using arangodb::Logger;
using arangodb::httpclient::SimpleHttpResult;
const std::string FoxxHealUrl = "/_api/foxx/_local/heal";
std::string body = "";
std::unique_ptr<SimpleHttpResult> response(
httpClient.request(arangodb::rest::RequestType::POST, FoxxHealUrl,
body.c_str(), body.length()));
return ::checkHttpResponse(httpClient, response, "trigger self heal", body);
}
arangodb::Result processInputDirectory(
arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::ClientTaskQueue<arangodb::RestoreFeature::JobData>& jobQueue,
arangodb::RestoreFeature& feature, arangodb::RestoreFeature::Options const& options,
arangodb::ManagedDirectory& directory, arangodb::RestoreFeature::Stats& stats) {
using arangodb::Logger;
using arangodb::Result;
using arangodb::StaticStrings;
using arangodb::basics::VelocyPackHelper;
using arangodb::basics::FileUtils::listFiles;
// create a lookup table for collections
std::set<std::string> restrictColls, restrictViews;
restrictColls.insert(options.collections.begin(), options.collections.end());
restrictViews.insert(options.views.begin(), options.views.end());
try {
std::vector<std::string> const files = listFiles(directory.path());
std::string const collectionSuffix = std::string(".structure.json");
std::string const viewsSuffix = std::string(".view.json");
std::vector<VPackBuilder> collections, views;
// Step 1 determine all collections to process
{
// loop over all files in InputDirectory, and look for all structure.json
// files
for (std::string const& file : files) {
size_t const nameLength = file.size();
if (nameLength > viewsSuffix.size() &&
file.substr(file.size() - viewsSuffix.size()) == viewsSuffix) {
if (!restrictColls.empty() && restrictViews.empty()) {
continue; // skip view if not specifically included
}
VPackBuilder contentBuilder = directory.vpackFromJsonFile(file);
VPackSlice const fileContent = contentBuilder.slice();
if (!fileContent.isObject()) {
return {TRI_ERROR_INTERNAL, "could not read view file '" +
directory.pathToFile(file) + "'"};
}
if (!restrictViews.empty()) {
std::string const name =
VelocyPackHelper::getStringValue(fileContent, StaticStrings::DataSourceName,
"");
if (restrictViews.find(name) == restrictViews.end()) {
continue;
}
}
views.emplace_back(std::move(contentBuilder));
continue;
}
if (nameLength <= collectionSuffix.size() ||
file.substr(file.size() - collectionSuffix.size()) != collectionSuffix) {
// some other file
continue;
}
// found a structure.json file
std::string name = file.substr(0, file.size() - collectionSuffix.size());
if (!options.includeSystemCollections && name[0] == '_') {
continue;
}
VPackBuilder fileContentBuilder = directory.vpackFromJsonFile(file);
VPackSlice const fileContent = fileContentBuilder.slice();
if (!fileContent.isObject()) {
return {TRI_ERROR_INTERNAL,
"could not read collection structure file '" +
directory.pathToFile(file) + "'"};
}
VPackSlice const parameters = fileContent.get("parameters");
VPackSlice const indexes = fileContent.get("indexes");
if (!parameters.isObject() || !indexes.isArray()) {
return {TRI_ERROR_INTERNAL,
"could not read collection structure file '" +
directory.pathToFile(file) + "'"};
}
std::string const cname =
VelocyPackHelper::getStringValue(parameters,
StaticStrings::DataSourceName, "");
bool overwriteName = false;
if (cname != name &&
name != (cname + "_" + arangodb::rest::SslInterface::sslMD5(cname))) {
// file has a different name than found in structure file
if (options.importStructure) {
// we cannot go on if there is a mismatch
return {TRI_ERROR_INTERNAL,
"collection name mismatch in collection structure file '" +
directory.pathToFile(file) + "' (offending value: '" +
cname + "')"};
} else {
// we can patch the name in our array and go on
LOG_TOPIC("8e7b7", INFO, Logger::RESTORE)
<< "ignoring collection name mismatch in collection "
"structure file '" +
directory.pathToFile(file) + "' (offending value: '" +
cname + "')";
overwriteName = true;
}
}
if (!restrictColls.empty() && restrictColls.find(cname) == restrictColls.end()) {
continue; // collection name not in list
}
if (overwriteName) {
// TODO: we have a JSON object with sub-object "parameters" with
// attribute "name". we only want to replace this. how?
} else {
collections.emplace_back(std::move(fileContentBuilder));
}
}
}
// order collections so that prototypes for distributeShardsLike come first
std::sort(collections.begin(), collections.end(), ::sortCollectionsForCreation);
std::unique_ptr<arangodb::RestoreFeature::JobData> usersData;
std::unique_ptr<arangodb::RestoreFeature::JobData> analyzersData;
std::vector<std::unique_ptr<arangodb::RestoreFeature::JobData>> jobs;
jobs.reserve(collections.size());
bool didModifyFoxxCollection = false;
// Step 3: create collections
for (VPackBuilder const& b : collections) {
VPackSlice const collection = b.slice();
LOG_TOPIC("c601a", DEBUG, Logger::RESTORE)
<< "# Processing collection: " << collection.toJson();
VPackSlice params = collection.get("parameters");
VPackSlice name = VPackSlice::emptyStringSlice();
if (params.isObject()) {
name = params.get("name");
// Only these two are relevant for FOXX.
if (name.isString() && (name.isEqualString("_apps") ||
name.isEqualString("_appbundles"))) {
didModifyFoxxCollection = true;
}
}
auto jobData =
std::make_unique<arangodb::RestoreFeature::JobData>(directory, feature, options,
stats, collection);
// take care of collection creation now, serially
if (options.importStructure) {
Result result = ::recreateCollection(httpClient, *jobData);
if (result.fail()) {
return result;
}
}
if (name.isString() && name.stringRef() == "_users") {
// special treatment for _users collection - this must be the very last,
// and run isolated from all previous data loading operations - the
// reason is that loading into the users collection may change the
// credentials for the current arangorestore connection!
usersData = std::move(jobData);
} else if (name.isString() && name.stringRef() == StaticStrings::AnalyzersCollection) {
// special treatment for _analyzers collection - this must be the very first
stats.totalCollections++;
analyzersData = std::move(jobData);
} else {
stats.totalCollections++;
jobs.push_back(std::move(jobData));
}
}
// Step 4: restore data from _analyzers collection
if (analyzersData) {
// restore analyzers
if (!jobQueue.queueJob(std::move(analyzersData))) {
return Result(TRI_ERROR_OUT_OF_MEMORY, "unable to queue restore job");
}
jobQueue.waitForIdle();
}
// Step 5: create arangosearch views
if (options.importStructure && !views.empty()) {
LOG_TOPIC("f723c", INFO, Logger::RESTORE) << "# Creating views...";
for (auto const& viewDefinition : views) {
LOG_TOPIC("c608d", DEBUG, Logger::RESTORE)
<< "# Creating view: " << viewDefinition.toJson();
auto res = ::restoreView(httpClient, options, viewDefinition.slice());
if (!res.ok()) {
return res;
}
}
}
// Step 6: fire up data transfer
for (auto& job : jobs) {
if (!jobQueue.queueJob(std::move(job))) {
return Result(TRI_ERROR_OUT_OF_MEMORY, "unable to queue restore job");
}
}
// wait for all jobs to finish, then check for errors
if (options.progress) {
LOG_TOPIC("6d69f", INFO, Logger::RESTORE)
<< "# Dispatched " << stats.totalCollections << " job(s), using "
<< options.threadCount << " worker(s)";
double start = TRI_microtime();
while (true) {
if (jobQueue.isQueueEmpty() && jobQueue.allWorkersIdle()) {
// done
break;
}
double now = TRI_microtime();
if (now - start >= 5.0) {
// returns #queued jobs, #workers total, #workers busy
auto queueStats = jobQueue.statistics();
// periodically report current status, but do not spam user
LOG_TOPIC("75e65", INFO, Logger::RESTORE)
<< "# Current restore progress: restored " << stats.restoredCollections
<< " of " << stats.totalCollections << " collection(s), read "
<< stats.totalRead << " byte(s) from datafiles, "
<< "sent " << stats.totalBatches << " data batch(es) of "
<< stats.totalSent << " byte(s) total size"
<< ", queued jobs: " << std::get<0>(queueStats)
<< ", workers: " << std::get<1>(queueStats);
start = now;
}
// don't sleep for too long, as we want to quickly terminate
// when the gets empty
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
jobQueue.waitForIdle();
jobs.clear();
Result firstError = feature.getFirstError();
if (firstError.fail()) {
return firstError;
}
if (didModifyFoxxCollection) {
// if we get here we need to trigger foxx heal
Result res = ::triggerFoxxHeal(httpClient);
if (res.fail()) {
LOG_TOPIC("47cd7", WARN, Logger::RESTORE)
<< "Reloading of Foxx services failed: " << res.errorMessage()
<< "- in the cluster Foxx services will be available eventually, On single servers send "
<< "a POST to '/_api/foxx/_local/heal' on the current database, "
<< "with an empty body. Please note that any of this is not necessary if the Foxx APIs "
<< "have been turned off on the server using the option `--foxx.api false`.";
}
}
// Last step: reload data into _users. Note: this can change the credentials
// of the arangorestore user itself
if (usersData) {
TRI_ASSERT(jobs.empty());
if (!jobQueue.queueJob(std::move(usersData))) {
return Result(TRI_ERROR_OUT_OF_MEMORY, "unable to queue restore job");
}
jobQueue.waitForIdle();
jobs.clear();
Result firstError = feature.getFirstError();
if (firstError.fail()) {
return firstError;
}
}
} catch (std::exception const& ex) {
return {TRI_ERROR_INTERNAL,
std::string(
"arangorestore terminated because of an unhandled exception: ")
.append(ex.what())};
} catch (...) {
return {TRI_ERROR_OUT_OF_MEMORY, "arangorestore out of memory"};
}
return {TRI_ERROR_NO_ERROR};
}
/// @brief process a single job from the queue
arangodb::Result processJob(arangodb::httpclient::SimpleHttpClient& httpClient,
arangodb::RestoreFeature::JobData& jobData) {
arangodb::Result result;
if (jobData.options.indexesFirst && jobData.options.importStructure) {
// restore indexes first if we are using rocksdb
result = ::restoreIndexes(httpClient, jobData);
if (result.fail()) {
return result;
}
}
if (jobData.options.importData) {
result = ::restoreData(httpClient, jobData);
if (result.fail()) {
return result;
}
}
if (!jobData.options.indexesFirst && jobData.options.importStructure) {
// restore indexes second if we are using mmfiles
result = ::restoreIndexes(httpClient, jobData);
if (result.fail()) {
return result;
}
}
++jobData.stats.restoredCollections;
if (jobData.options.progress) {
VPackSlice const parameters = jobData.collection.get("parameters");
std::string const cname =
arangodb::basics::VelocyPackHelper::getStringValue(parameters, "name",
"");
int type = arangodb::basics::VelocyPackHelper::getNumericValue<int>(parameters,
"type", 2);
std::string const collectionType(type == 2 ? "document" : "edge");
LOG_TOPIC("6ae09", INFO, arangodb::Logger::RESTORE) << "# Successfully restored " << collectionType
<< " collection '" << cname << "'";
}
return result;
}
/// @brief handle the result of a single job
void handleJobResult(std::unique_ptr<arangodb::RestoreFeature::JobData>&& jobData,
arangodb::Result const& result) {
if (result.fail()) {
jobData->feature.reportError(result);
}
}
} // namespace
namespace arangodb {
RestoreFeature::JobData::JobData(ManagedDirectory& d, RestoreFeature& f,
RestoreFeature::Options const& o,
RestoreFeature::Stats& s, VPackSlice const& c)
: directory{d}, feature{f}, options{o}, stats{s}, collection{c} {}
RestoreFeature::RestoreFeature(application_features::ApplicationServer& server, int& exitCode)
: ApplicationFeature(server, RestoreFeature::featureName()),
_clientManager{server, Logger::RESTORE},
_clientTaskQueue{server, ::processJob, ::handleJobResult},
_exitCode{exitCode} {
requiresElevatedPrivileges(false);
setOptional(false);
startsAfter<application_features::BasicFeaturePhaseClient>();
using arangodb::basics::FileUtils::buildFilename;
using arangodb::basics::FileUtils::currentDirectory;
_options.inputPath = buildFilename(currentDirectory().result(), "dump");
}
void RestoreFeature::collectOptions(std::shared_ptr<options::ProgramOptions> options) {
using arangodb::options::BooleanParameter;
using arangodb::options::StringParameter;
using arangodb::options::UInt32Parameter;
using arangodb::options::UInt64Parameter;
using arangodb::options::VectorParameter;
options->addOption(
"--collection",
"restrict to collection name (can be specified multiple times)",
new VectorParameter<StringParameter>(&_options.collections));
options->addOption("--view",
"restrict to view name (can be specified multiple times)",
new VectorParameter<StringParameter>(&_options.views));
options->addObsoleteOption("--recycle-ids",
"collection ids are now handled automatically", false);
options->addOption("--batch-size",
"maximum size for individual data batches (in bytes)",
new UInt64Parameter(&_options.chunkSize));
options
->addOption("--threads",
"maximum number of collections to process in parallel",
new UInt32Parameter(&_options.threadCount))
.setIntroducedIn(30400);
options->addOption("--include-system-collections",
"include system collections",
new BooleanParameter(&_options.includeSystemCollections));
options->addOption("--create-database",
"create the target database if it does not exist",
new BooleanParameter(&_options.createDatabase));
options->addOption(
"--force-same-database",
"force usage of the same database name as in the source dump.json file",
new BooleanParameter(&_options.forceSameDatabase));
options->addOption(
"--all-databases", "restore data to all databases",
new BooleanParameter(&_options.allDatabases))
.setIntroducedIn(30500);
options->addOption("--input-directory", "input directory",
new StringParameter(&_options.inputPath));
options
->addOption(
"--cleanup-duplicate-attributes",
"clean up duplicate attributes (use first specified value) in input "
"documents instead of making the restore operation fail",
new BooleanParameter(&_options.cleanupDuplicateAttributes),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden))
.setIntroducedIn(30322)
.setIntroducedIn(30402);
options->addOption("--import-data", "import data into collection",
new BooleanParameter(&_options.importData));
options->addOption("--create-collection", "create collection structure",
new BooleanParameter(&_options.importStructure));
options->addOption("--progress", "show progress",
new BooleanParameter(&_options.progress));
options->addOption("--overwrite", "overwrite collections if they exist",
new BooleanParameter(&_options.overwrite));
options
->addOption(
"--number-of-shards",
"override value for numberOfShards (can be specified multiple times, "
"e.g. --numberOfShards 2 --numberOfShards myCollection=3)",
new VectorParameter<StringParameter>(&_options.numberOfShards))
.setIntroducedIn(30322)
.setIntroducedIn(30402);
options
->addOption("--replication-factor",
"override value for replicationFactor (can be specified "
"multiple times, e.g. --replicationFactor 2 "
"--replicationFactor myCollection=3)",
new VectorParameter<StringParameter>(&_options.replicationFactor))
.setIntroducedIn(30322)
.setIntroducedIn(30402);
options->addOption(
"--ignore-distribute-shards-like-errors",
"continue restore even if sharding prototype collection is missing",
new BooleanParameter(&_options.ignoreDistributeShardsLikeErrors));
options->addOption(
"--force", "continue restore even in the face of some server-side errors",
new BooleanParameter(&_options.force));
// deprecated options
options
->addOption("--default-number-of-shards",
"default value for numberOfShards if not specified in dump",
new UInt64Parameter(&_options.defaultNumberOfShards),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden))
.setDeprecatedIn(30322)
.setDeprecatedIn(30402);
options
->addOption(
"--default-replication-factor",
"default value for replicationFactor if not specified in dump",
new UInt64Parameter(&_options.defaultReplicationFactor),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden))
.setDeprecatedIn(30322)
.setDeprecatedIn(30402);
}
void RestoreFeature::validateOptions(std::shared_ptr<options::ProgramOptions> options) {
using arangodb::basics::StringUtils::join;
auto const& positionals = options->processingResult()._positionals;
size_t n = positionals.size();
if (1 == n) {
_options.inputPath = positionals[0];
} else if (1 < n) {
LOG_TOPIC("d249a", FATAL, arangodb::Logger::RESTORE)
<< "expecting at most one directory, got " + join(positionals, ", ");
FATAL_ERROR_EXIT();
}
if (_options.allDatabases) {
if (options->processingResult().touched("server.database")) {
LOG_TOPIC("94d22", FATAL, arangodb::Logger::RESTORE)
<< "cannot use --server.database and --all-databases at the same time";
FATAL_ERROR_EXIT();
}
if (_options.forceSameDatabase) {
LOG_TOPIC("fd66a", FATAL, arangodb::Logger::RESTORE)
<< "cannot use --force-same-database and --all-databases at the same time";
FATAL_ERROR_EXIT();
}
}
// use a minimum value for batches
if (_options.chunkSize < 1024 * 128) {
_options.chunkSize = 1024 * 128;
}
auto clamped = boost::algorithm::clamp(_options.threadCount, uint32_t(1),
uint32_t(4 * TRI_numberProcessors()));
if (_options.threadCount != clamped) {
LOG_TOPIC("53570", WARN, Logger::RESTORE) << "capping --threads value to " << clamped;
_options.threadCount = clamped;
}
// validate shards and replication factor
if (_options.defaultNumberOfShards == 0) {
LOG_TOPIC("248ee", FATAL, arangodb::Logger::RESTORE)
<< "invalid value for `--default-number-of-shards`, expecting at least "
"1";
FATAL_ERROR_EXIT();
}
if (_options.defaultReplicationFactor == 0) {
LOG_TOPIC("daf22", FATAL, arangodb::Logger::RESTORE)
<< "invalid value for `--default-replication-factor, expecting at "
"least 1";
FATAL_ERROR_EXIT();
}
for (auto& it : _options.numberOfShards) {
auto parts = basics::StringUtils::split(it, '=');
if (parts.size() == 1 && basics::StringUtils::int64(parts[0]) > 0) {
// valid
continue;
} else if (parts.size() == 2 && basics::StringUtils::int64(parts[1]) > 0) {
// valid
continue;
}
// invalid!
LOG_TOPIC("1951e", FATAL, arangodb::Logger::RESTORE)
<< "got invalid value '" << it << "' for `--number-of-shards";
FATAL_ERROR_EXIT();
}
for (auto& it : _options.replicationFactor) {
auto parts = basics::StringUtils::split(it, '=');
if (parts.size() == 1) {
if (parts[0] == "satellite" || basics::StringUtils::int64(parts[0]) > 0) {
// valid
continue;
}
} else if (parts.size() == 2) {
if (parts[1] == "satellite" || basics::StringUtils::int64(parts[1]) > 0) {
// valid
continue;
}
}
// invalid!
LOG_TOPIC("d038e", FATAL, arangodb::Logger::RESTORE)
<< "got invalid value '" << it << "' for `--replication-factor";
FATAL_ERROR_EXIT();
}
}
void RestoreFeature::prepare() {
if (!_options.inputPath.empty() && _options.inputPath.back() == TRI_DIR_SEPARATOR_CHAR) {
// trim trailing slash from path because it may cause problems on ...
// Windows
TRI_ASSERT(_options.inputPath.size() > 0);
_options.inputPath.pop_back();
}
if (!_options.importStructure && !_options.importData) {
LOG_TOPIC("1281f", FATAL, arangodb::Logger::RESTORE)
<< "Error: must specify either --create-collection or --import-data";
FATAL_ERROR_EXIT();
}
}
void RestoreFeature::start() {
using arangodb::httpclient::SimpleHttpClient;
double const start = TRI_microtime();
// set up the output directory, not much else
_directory =
std::make_unique<ManagedDirectory>(server(), _options.inputPath, false, false);
if (_directory->status().fail()) {
switch (_directory->status().errorNumber()) {
case TRI_ERROR_FILE_NOT_FOUND:
LOG_TOPIC("3246c", FATAL, arangodb::Logger::RESTORE)
<< "input directory '" << _options.inputPath << "' does not exist";
break;
default:
LOG_TOPIC("535b3", FATAL, arangodb::Logger::RESTORE)
<< _directory->status().errorMessage();
break;
}
FATAL_ERROR_EXIT();
}
ClientFeature& client = server().getFeature<HttpEndpointProvider, ClientFeature>();
_exitCode = EXIT_SUCCESS;
// enumerate all databases present in the dump directory (in case of
// --all-databases=true, or use just the flat files in case of --all-databases=false)
std::vector<std::string> databases;
if (_options.allDatabases) {
for (auto const& it : basics::FileUtils::listFiles(_options.inputPath)) {
std::string path = basics::FileUtils::buildFilename(_options.inputPath, it);
if (basics::FileUtils::isDirectory(path)) {
databases.push_back(it);
}
}
// sort by name, with _system last
// this is necessary because in the system database there is the _users collection,
// and we have to process users last of all. otherwise we risk updating the
// credentials for the user which users the current arangorestore connection, and
// this will make subsequent arangorestore calls to the server fail with "unauthorized"
std::sort(databases.begin(), databases.end(), [](std::string const& lhs, std::string const& rhs) {
if (lhs == "_system" && rhs != "_system") {
return false;
} else if (rhs == "_system" && lhs != "_system") {
return true;
}
return lhs < rhs;
});
if (databases.empty()) {
LOG_TOPIC("b41d9", FATAL, Logger::RESTORE) << "Unable to find per-database subdirectories in input directory '" << _options.inputPath << "'. No data will be restored!";
FATAL_ERROR_EXIT();
}
} else {
databases.push_back(client.databaseName());
}
std::unique_ptr<SimpleHttpClient> httpClient;
// final result
Result result;
result = _clientManager.getConnectedClient(httpClient, _options.force,
true, !_options.createDatabase, false);
if (result.is(TRI_ERROR_SIMPLE_CLIENT_COULD_NOT_CONNECT)) {
LOG_TOPIC("c23bf", FATAL, Logger::RESTORE)
<< "cannot create server connection, giving up!";
FATAL_ERROR_EXIT();
}
if (result.is(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND)) {
std::string dbName = client.databaseName();
if (_options.createDatabase) {
// database not found, but database creation requested
LOG_TOPIC("9b5a6", INFO, Logger::RESTORE) << "Creating database '" << dbName << "'";
client.setDatabaseName("_system");
Result res = ::tryCreateDatabase(server(), dbName);
if (res.fail()) {
LOG_TOPIC("b19db", FATAL, Logger::RESTORE) << "Could not create database '" << dbName << "': " << httpClient->getErrorMessage();
FATAL_ERROR_EXIT();
}
// restore old database name
client.setDatabaseName(dbName);
// re-check connection and version
result = _clientManager.getConnectedClient(httpClient, _options.force, true, true, false);
} else {
LOG_TOPIC("ad95b", WARN, Logger::RESTORE) << "Database '" << dbName << "' does not exist on target endpoint. In order to create this database along with the restore, please use the --create-database option";
}
}
if (result.fail() && !_options.force) {
LOG_TOPIC("62a31", FATAL, Logger::RESTORE)
<< "cannot create server connection: " << result.errorMessage();
FATAL_ERROR_EXIT();
}
// check if we are in cluster or single-server mode
std::string role;
std::tie(result, role) = _clientManager.getArangoIsCluster(*httpClient);
_options.clusterMode = (role == "COORDINATOR");
if (result.fail()) {
LOG_TOPIC("b18ac", FATAL, arangodb::Logger::RESTORE)
<< "Error: could not detect ArangoDB instance type: " << result.errorMessage();
_exitCode = EXIT_FAILURE;
return;
}
if (role == "DBSERVER" || role == "PRIMARY") {
LOG_TOPIC("1fc99", WARN, arangodb::Logger::RESTORE) << "You connected to a DBServer node, but operations in a cluster should be carried out via a Coordinator. This is an unsupported operation!";
}
std::tie(result, _options.indexesFirst) =
_clientManager.getArangoIsUsingEngine(*httpClient, "rocksdb");
if (result.fail()) {
LOG_TOPIC("b90ec", FATAL, arangodb::Logger::RESTORE)
<< "Error while trying to determine server storage engine: "
<< result.errorMessage();
_exitCode = EXIT_FAILURE;
return;
}
if (_options.progress) {
LOG_TOPIC("05c30", INFO, Logger::RESTORE)
<< "Connected to ArangoDB '" << httpClient->getEndpointSpecification() << "'";
}
// set up threads and workers
_clientTaskQueue.spawnWorkers(_clientManager, _options.threadCount);
LOG_TOPIC("6bb3c", DEBUG, Logger::RESTORE) << "Using " << _options.threadCount << " worker thread(s)";
if (_options.allDatabases) {
LOG_TOPIC("7c10a", INFO, Logger::RESTORE) << "About to restore databases '" << basics::StringUtils::join(databases, "', '") << "' from dump directory '" << _options.inputPath << "'...";
}
for (auto const& db : databases) {
result.reset();
if (_options.allDatabases) {
// inject current database
client.setDatabaseName(db);
LOG_TOPIC("36075", INFO, Logger::RESTORE) << "Restoring database '" << db << "'";
_directory = std::make_unique<ManagedDirectory>(
server(), basics::FileUtils::buildFilename(_options.inputPath, db), false, false);
result = _clientManager.getConnectedClient(httpClient, _options.force,
false, !_options.createDatabase, false);
if (result.is(TRI_ERROR_SIMPLE_CLIENT_COULD_NOT_CONNECT)) {
LOG_TOPIC("3e715", FATAL, Logger::RESTORE)
<< "cannot create server connection, giving up!";
FATAL_ERROR_EXIT();
}
if (result.is(TRI_ERROR_ARANGO_DATABASE_NOT_FOUND)) {
if (_options.createDatabase) {
// database not found, but database creation requested
LOG_TOPIC("080f3", INFO, Logger::RESTORE) << "Creating database '" << db << "'";
client.setDatabaseName("_system");
result = ::tryCreateDatabase(server(), db);
if (result.fail()) {
LOG_TOPIC("7a35f", ERR, Logger::RESTORE) << "Could not create database '" << db << "': " << httpClient->getErrorMessage();
break;
}
// restore old database name
client.setDatabaseName(db);
// re-check connection and version
result = _clientManager.getConnectedClient(httpClient, _options.force, false, true, false);
} else {
LOG_TOPIC("be594", WARN, Logger::RESTORE) << "Database '" << db << "' does not exist on target endpoint. In order to create this database along with the restore, please use the --create-database option";
}
}
if (result.fail()) {
result.reset(result.errorNumber(), std::string("cannot create server connection: ") + result.errorMessage());
if (!_options.force) {
break;
}
LOG_TOPIC("be86d", ERR, arangodb::Logger::RESTORE) << result.errorMessage();
// continue with next db
continue;
}
}
// read encryption info
::checkEncryption(*_directory);
// read dump info
result = ::checkDumpDatabase(server(), *_directory, _options.forceSameDatabase);
if (result.fail()) {
LOG_TOPIC("0cbdf", FATAL, arangodb::Logger::RESTORE) << result.errorMessage();
FATAL_ERROR_EXIT();
}
// run the actual restore
try {
result = ::processInputDirectory(*httpClient, _clientTaskQueue, *this,
_options, *_directory, _stats);
} catch (basics::Exception const& ex) {
LOG_TOPIC("52b22", ERR, arangodb::Logger::RESTORE) << "caught exception: " << ex.what();
result = {ex.code(), ex.what()};
} catch (std::exception const& ex) {
LOG_TOPIC("8f13f", ERR, arangodb::Logger::RESTORE) << "caught exception: " << ex.what();
result = {TRI_ERROR_INTERNAL, ex.what()};
} catch (...) {
LOG_TOPIC("a74e8", ERR, arangodb::Logger::RESTORE) << "caught unknown exception";
result = {TRI_ERROR_INTERNAL};
}
if (result.fail()) {
break;
}
}
if (result.fail()) {
LOG_TOPIC("cb69f", ERR, arangodb::Logger::RESTORE) << result.errorMessage();
_exitCode = EXIT_FAILURE;
}
if (_options.progress) {
double totalTime = TRI_microtime() - start;
if (_options.importData) {
LOG_TOPIC("a66e1", INFO, Logger::RESTORE)
<< "Processed " << _stats.restoredCollections << " collection(s) in "
<< Logger::FIXED(totalTime, 6) << " s, "
<< "read " << _stats.totalRead << " byte(s) from datafiles, "
<< "sent " << _stats.totalBatches << " data batch(es) of "
<< _stats.totalSent << " byte(s) total size";
} else if (_options.importStructure) {
LOG_TOPIC("147ca", INFO, Logger::RESTORE)
<< "Processed " << _stats.restoredCollections << " collection(s) in "
<< Logger::FIXED(totalTime, 6) << " s";
}
}
}
std::string RestoreFeature::featureName() { return ::FeatureName; }
void RestoreFeature::reportError(Result const& error) {
try {
MUTEX_LOCKER(lock, _workerErrorLock);
_workerErrors.emplace(error);
_clientTaskQueue.clearQueue();
} catch (...) {
}
}
Result RestoreFeature::getFirstError() const {
{
MUTEX_LOCKER(lock, _workerErrorLock);
if (!_workerErrors.empty()) {
return _workerErrors.front();
}
}
return {TRI_ERROR_NO_ERROR};
}
} // namespace arangodb
|
// atcoder/abc180/E/main.cpp
// author: @___Johniel
// github: https://github.com/johniel/
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; for (auto& i: v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { for (auto& i: v) is >> i; return is; }
template<typename T> ostream& operator << (ostream& os, set<T> s) { os << "#{"; for (auto& i: s) os << i << ","; os << "}"; return os; }
template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; for (auto& i: m) os << i << ","; os << "}"; return os; }
template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }
using lli = long long int;
using ull = unsigned long long;
using point = complex<double>;
using str = string;
template<typename T> using vec = vector<T>;
constexpr array<int, 8> di({0, 1, -1, 0, 1, -1, 1, -1});
constexpr array<int, 8> dj({1, 0, 0, -1, 1, -1, -1, 1});
constexpr lli mod = 1e9 + 7;
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.setf(ios_base::fixed);
cout.precision(15);
int n;
while (cin >> n) {
lli x[n];
lli y[n];
lli z[n];
for (int i = 0; i < n; ++i) {
cin >> x[i] >> y[i] >> z[i];
}
const int N = 18;
const int BIT = 1 << N;
static lli dp[BIT][N];
const lli inf = 1LL << 60;
fill(&dp[0][0], &dp[BIT - 1][N - 1] + 1, inf);
dp[1 << 0][0] = 0;
for (int bit = 0; bit < BIT; ++bit) {
for (int i = 0; i < n; ++i) {
unless (bit & (1 << i)) continue;
for (int j = 0; j < n; ++j) {
lli cost = abs(x[i] - x[j]) + abs(y[i] - y[j]) + max(0LL, z[j] - z[i]);
setmin(dp[bit | (1 << j)][j], dp[bit][i] + cost);
}
}
}
lli mn = inf;
for (int i = 0; i < n; ++i) {
lli cost = abs(x[i] - x[0]) + abs(y[i] - y[0]) + max(0LL, z[0] - z[i]);
if (i == 0) cost = 0;
setmin(mn, dp[(1 << n) - 1][i] + cost);
}
cout << mn << endl;
}
return 0;
}
|
/* Sirikata
* FCache.cpp
*
* Copyright (c) 2010, Behram Mistree
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include "Utility.hpp"
#include "FCache.hpp"
#include "Cache.hpp"
#include "Geometry.hpp"
#include <functional>
#include <algorithm>
#include <time.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <cassert>
#include <string>
#include <cmath>
#include "CacheRecords.hpp"
//#define FCACHE_LOG_REMOVALS
namespace Sirikata
{
FCache::~FCache()
{
std::cout<<"\nWould probably be better if removed the cache records from the end of properRecords vec during maintain rather than beginning\n";
std::cout<<"\nConsider whether I need a better way of calculating variances for removed times and popularities\n";
std::cout<<"\nChanged code so that it will always insert a new record. new records also take on zero popularity, etc.\n";
std::cout<<"\n\nNeeed to change to other scaling units\n\n";
worstRecords.clear();
}
void FCache::updatePopAndIncrement(FCacheRecord* bcRec)
{
CacheTimeMS currTime = (ctx->simTime() - Time::null()).toMilliseconds();
bcRec->mLastAccessTime = currTime;
while (bcRec->lastEvictNum != currTime)
{
bcRec->popAvg = ewmaRecPopPar*bcRec->reqsSinceEvict + (1-ewmaRecPopPar)*bcRec->popAvg;
++(bcRec->lastEvictNum);
bcRec->reqsSinceEvict = 0;
//debug
if (bcRec->lastEvictNum > currTime)
{
bcRec->printRecord();
assert(false);
}
}
++(bcRec->reqsSinceEvict);
}
void FCache::updatePopNoIncrement(FCacheRecord* bcRec)
{
CacheTimeMS currTime= (ctx->simTime() - Time::null()).toMilliseconds();
while (bcRec->lastEvictNum != currTime)
{
bcRec->popAvg = ewmaRecPopPar*bcRec->reqsSinceEvict + (1-ewmaRecPopPar)*bcRec->popAvg;
++(bcRec->lastEvictNum);
bcRec->reqsSinceEvict = 0;
//debug
if (bcRec->lastEvictNum > currTime)
{
std::cout<<"\n\n\nThis is the record";
bcRec->printRecord();
std::cout<<"\nGlob evict num: "<<currTime<<" last evict num: "<<bcRec->lastEvictNum<<"\n\n";
std::cout.flush();
assert(false);
}
}
}
void FCache::updatePopNoIncrement(std::vector<FCacheRecord*>& bcRecVec)
{
for (int s=0; s < (int)bcRecVec.size(); ++s)
updatePopNoIncrement(bcRecVec[s]);
}
void FCache::updateRecord(FCacheRecord* rec, ServerID bid,double weight,double distance, double radius, double vMag)
{
rec->bID = bid;
rec->weight = weight;
rec->distance = distance;
rec->radius = radius;
rec->vMag = vMag;
}
void FCache::insert(const UUID& toInsert, ServerID bid, CacheTimeMS tms, double vMag,double weight, double distance, double radius,double lookupWeight,double unitsScaling)
{
//first check to make sure that don't already have a record for this
FCacheRecord* foundRec = cacheProper.getRecord(toInsert);
if (foundRec != NULL) //object existed in cache proper. we need to update its values
{
updateRecord(foundRec,bid,weight,distance,radius, vMag);
}
else
{
//object did not exist in cache proper: insert it
if (cacheProper.hasRoom())
{
//cacheProper isn't full yet. Put it there first
if (!cacheProper.insert(toInsert,bid,(ctx->simTime() - Time::null()).toMilliseconds(),weight,distance,radius,lookupWeight,unitsScaling, vMag))
assert(false);
}
else
{
killRecord();
if (!cacheProper.insert(toInsert,bid,(ctx->simTime()- Time::null()).toMilliseconds(),weight,distance,radius,lookupWeight,unitsScaling, vMag))
assert(false);
}
}
}
void FCache::printWorstRecords()
{
std::cout<<"\n\nWORST RECORDS\n";
for(int s=0;s<(int)worstRecords.size();++s)
{
std::cout<<"\n"<<worstRecords[s]->objid.toString()<<"\t score: "<< (*mScoreFunc)(worstRecords[s]);
}
std::cout<<"\n\n";
}
void FCache::killRecord()
{
generateRandomCacheProper(FCACHE_RAND_SELECT_NUMBER,worstRecords);//generates from cacheProper
//update globals
updatePopNoIncrement(worstRecords);
findMins(worstRecords,mScoreFunc);
//remove bad record from cacheProper
FCacheRecord* toRemove = worstRecords.back();
if (! cacheProper.remove(toRemove))
assert(false);
std::vector<FCacheRecord*>::iterator worstIt = worstRecords.begin();
while(worstIt != worstRecords.end())
{
if( (*worstIt)->objid == toRemove->objid)
worstIt = worstRecords.erase(worstIt);
else
++worstIt;
}
}
const OSegEntry& FCache::lookup(const UUID& lookingFor)
{
FCacheRecord* rec = cacheProper.getRecord(lookingFor);
if (rec != NULL)
{
//record is in cacheProper
updatePopAndIncrement(rec);
mCraqEntry.setServer(rec->bID);
mCraqEntry.setRadius(rec->radius);
return mCraqEntry;
}
static OSegEntry justnothin(OSegEntry::null());
return justnothin;
}
//this function just generates numToSelect random values into randIndices.
void FCache::generateRandomCacheProper(int numToSelect,std::vector<FCacheRecord*>&randRecs)
{
if (cacheProper.empty())
assert(false);
for (int s=0; s < numToSelect; ++s)
{
FCacheRecord* rec = cacheProper.getRandom();
if (rec == NULL)
{
int sizer = cacheProper.getSize();
std::cout<<"\n\n"<<sizer<<"\n\n";
assert(false);
}
randRecs.push_back(rec);
}
}
void FCache::printCacheRecordVec(const std::vector<FCacheRecord*>& vec)
{
std::cout<<"\nPrinting entire cache record vector\n";
for (int s=0; s < (int) vec.size(); ++s)
{
vec[s]->printRecord();
std::cout<<"\n";
}
}
FCache::FCache(double avgPopPar,std::string cacheName,FCacheScoreFunc scoreFunc, FCacheScoreFuncPrint scoreFuncPrint, SpaceContext* spctx)
: ewmaRecPopPar(avgPopPar),
mName(cacheName),
mScoreFunc(scoreFunc),
mScoreFuncPrint(scoreFuncPrint),
ctx(spctx),
mCraqEntry(OSegEntry::null()),
MAX_SIZE_CACHE_PROPER (CACHE_MAX_SIZE),
cacheProper(spctx, MAX_SIZE_CACHE_PROPER)
{
}
FCache::FCache(double avgPopPar,std::string cacheName,FCacheScoreFunc scoreFunc, FCacheScoreFuncPrint scoreFuncPrint, SpaceContext* spctx,int CACHE_SIZE)
: ewmaRecPopPar(avgPopPar),
mName(cacheName),
mScoreFunc(scoreFunc),
mScoreFuncPrint(scoreFuncPrint),
ctx(spctx),
mCraqEntry(OSegEntry::null()),
MAX_SIZE_CACHE_PROPER (CACHE_SIZE),
cacheProper(spctx, CACHE_SIZE)
{
}
std::string FCache::getCacheName()
{
return mName;
}
//remove the object id associated with oid
void FCache::remove(const UUID& oid)
{
FCacheRecord* rec;
//check if record exists in cacheProper
rec = cacheProper.getRecord(oid);
if (rec != NULL)
{
//check if the record is in worst records
std::vector<FCacheRecord*>::iterator it = worstRecords.begin();
while(it != worstRecords.end())
{
if ( (*it)->objid == oid)
it = worstRecords.erase(it);
else
++it;
}
//record exists in cacheProper
removeCacheProper(rec);
}
}
void FCache::removeCacheProper(FCacheRecord* rec)
{
//Time to remove it.
if (! cacheProper.remove(rec))
assert(false); //means that we're trying to remove something that's not there.
}
void FCache::printVecRecs(const std::vector<FCacheRecord*> &recs)
{
for (int s=0; s < (int) recs.size(); ++s)
std::cout<<"Pointer: "<<PTR_AS_INT(recs[s])<<" objid:"<<recs[s]->objid.toString()<<"\n";
}
//changes the vector so that it is stuffed with the worst three (the worst is at the end).
void findMins(std::vector<FCacheRecord*>&vec,FCacheScoreFunc scoreFunc)
{
double s1 = -1;
FCacheRecord* obj1 = NULL;
bool foundS1 = false;
double s2 = -1;
FCacheRecord* obj2 = NULL;
bool foundS2 = false;
double score = 0;
for (int s=0; s < (int)vec.size(); ++s)
{
score = (*scoreFunc)(vec[s]);
if (! foundS1)
{
s1 = score;
obj1 = vec[s];
foundS1 = true;
}
else if (s1 >= score)
{
s2 = s1;
obj2 = obj1;
if (foundS1)
foundS2 = true;
s1 = score;
obj1 = vec[s];
foundS1 = true;
}
else if (! foundS2)
{
s2 = score;
obj2 = vec[s];
foundS2 = true;
}
else if (s2 >= score)
{
s2 = score;
obj2 = vec[s];
foundS2 = true;
}
}
vec.clear();
vec.push_back(obj2);
vec.push_back(obj1);
}
//this is where slab allocating is a good idea;
FCache::FCachePropDataStruct::FCachePropDataStruct(SpaceContext* spctx, int max_size)
: mMaxSize(max_size),
allRecordMem(new FCacheRecord[max_size])
{
ctx = spctx;
//initialize the structures.
for (int s=0; s < max_size; ++s)
{
cPropVec.push_back(UUID());
invalidMap[s] = true; //an index for cPropVec as well as for allRecordData
}
sanityCheck();
}
FCacheRecord* FCache::FCachePropDataStruct::getRandom()
{
sanityCheck();
int index;
int numAttempts= 0;
FCacheRecord* returner = NULL;
if(empty())
{
sanityCheck();
return NULL;
}
while (numAttempts < MAX_NUM_ITERATIONS_GET_RANDOM)
{
++numAttempts;
index = rand() % mMaxSize;
if (invalidMap.find(index) == invalidMap.end()) //means that the object is valid and can be returned
{
UUID oid = cPropVec[index];
returner = cacheProper[oid];
if (returner == NULL)
assert(false);
sanityCheck();
return returner;
}
}
//if can't find something after that many attempts, just return front of the map
returner = cacheProper.begin()->second;
if (returner == NULL)
assert(false);
sanityCheck();
return returner;
}
void FCache::FCachePropDataStruct::printCacheProper()
{
FCacheDataMap::iterator cpIt;
int s=0;
for (cpIt = cacheProper.begin(); cpIt != cacheProper.end(); ++cpIt)
{
std::cout<<"\n"<< cpIt->second->objid.toString()<< " "<<s;
std::cout.flush();
++s;
}
}
void FCache::FCachePropDataStruct::sanityCheck()
{
int propVecSize = (int) cPropVec.size();
int cacheSize = (int) cacheProper.size();
int invalidSize = (int) invalidMap.size();
if (propVecSize != mMaxSize)
assert(false);
if (invalidSize + cacheSize != mMaxSize)
assert(false);
}
bool FCache::FCachePropDataStruct::insert(const UUID& oid, ServerID bid,int globEvNum,double weight, double distance, double radius, double lookupWeight,double mscalingUnits, double vMag)
{
sanityCheck();
if ((int)cacheProper.size() >= mMaxSize)
return false; //full, user must request some removes before we can process things.
//not full, can proceed with insert
if (invalidMap.empty())
{
std::cout<<"\nThis is the size of cacheProper: "<<cacheProper.size()<<"\n";
std::cout<<"\nThis is mMaxSize: "<<mMaxSize<<"\n\n";
assert(false); //shouldn't happen if above check passed
}
int index = invalidMap.begin()->first; //need to take first because first contains the indexing scheme
invalidMap.erase(invalidMap.begin());
allRecordMem[index].copy(oid,bid,0,0,globEvNum,index,weight,distance,radius,lookupWeight,mscalingUnits, ctx, (ctx->simTime()-Time::null()).toMilliseconds(), vMag);
cPropVec [index] = oid;
cacheProper [oid] = allRecordMem + index;
sanityCheck();
return true;
}
bool FCache::FCachePropDataStruct::remove(FCacheRecord* rec)
{
sanityCheck();
FCacheDataMap::iterator cPropIt = cacheProper.find(rec->objid);
if (cPropIt == cacheProper.end()) //cannot remove object that we do not own
{
assert(false);
sanityCheck();
return false;
}
//erase from cache proper
cacheProper.erase(cPropIt);
//say that the entry in cPropVec is now worthless.
invalidMap[rec->vecIndex] = true;
cPropVec[rec->vecIndex ] = UUID(); //should not be necessary, but will aid in debugging
sanityCheck();
return true;
}
int FCache::FCachePropDataStruct::getSize()
{
sanityCheck();
return (int)cacheProper.size();
}
FCache::FCachePropDataStruct::~FCachePropDataStruct()
{
delete [] allRecordMem;
sanityCheck();
cacheProper.clear();
cPropVec.clear();
invalidMap.clear();
}
//who I send this record to is not allowed to delete it!
FCacheRecord* FCache::FCachePropDataStruct::getRecord(const UUID&oid)
{
sanityCheck();
FCacheDataMap::iterator propIt;
propIt = cacheProper.find(oid);
if(propIt == cacheProper.end())
{
sanityCheck();
return NULL;
}
sanityCheck();
return propIt->second;
}
bool FCache::FCachePropDataStruct::hasRoom()
{
sanityCheck();
return ((int)cacheProper.size() < mMaxSize);
}
//This function removes the first record from the map
//whomever I send the record to is not allowed to delete it.
FCacheRecord* FCache::FCachePropDataStruct::popFirst()
{
sanityCheck();
if (cacheProper.empty()) //nothing to pop
{
assert(false);
sanityCheck();
return NULL;
}
FCacheRecord* rec = cacheProper.begin()->second;
if (rec == NULL)
assert (false);
invalidMap [rec->vecIndex] = true;
cPropVec [rec->vecIndex] = UUID(); //should not be necessary, but will aid in debugging
FCacheDataMap::iterator finder = cacheProper.find(rec->objid);
if(finder == cacheProper.end())
assert(false);
cacheProper.erase(finder);
sanityCheck();
return rec;
}
bool FCache::FCachePropDataStruct::empty()
{
sanityCheck();
return cacheProper.empty();
}
void FCache::FCachePropDataStruct::clear()
{
sanityCheck();
cacheProper.clear();
invalidMap.clear();
for (int s=0; s < mMaxSize; ++s)
invalidMap[s] = true;
//debugging
if (! empty())
assert (false);
std::cout.flush();
sanityCheck();
}
void FCache::FCachePropDataStruct::printInvalidMap()
{
FCacheValidMap::iterator it;
for (it = invalidMap.begin(); it != invalidMap.end(); ++it)
std::cout<<"\n"<<it->first;
}
void FCache::FCachePropDataStruct::printCPropVec()
{
std::cout<<"\n\n";
// for (int s=0; s < (int)cPropVec.size(); ++s)
// std::cout<<"\t"<<cPropVec[s];
std::cout<<"\n\n";
}
}
|
#include <string> // string
#include "Ammo.h" // Ammo, TESEquipEventHandler
#include "Helmet.h" // Helmet, BSAnimationGraphEventHandler
#include "PlayerUtil.h" // AnimationGraphEventHandler
#include "Settings.h" // Settings
#include "Shield.h" // Shield, BSAnimationGraphEventHandler
#include "version.h" // VERSION_VERSTRING, VERSION_MAJOR
#include "SKSE/API.h"
#include "RE/Skyrim.h"
namespace
{
enum
{
kSerializationVersion = 3,
kDynamicEquipmentManager = 'DNEM',
kAmmo = 'AMMO',
kHelmet = 'HELM',
kShield = 'SHLD'
};
std::string DecodeTypeCode(UInt32 a_typeCode)
{
constexpr auto SIZE = sizeof(UInt32);
std::string sig;
sig.resize(SIZE);
const auto iter = reinterpret_cast<char*>(&a_typeCode);
for (std::size_t i = 0, j = SIZE - 2; i < SIZE - 1; ++i, --j) {
sig[j] = iter[i];
}
_DMESSAGE(sig.c_str());
return sig;
}
void SaveCallback(SKSE::SerializationInterface* a_intfc)
{
auto ammo = Ammo::Ammo::GetSingleton();
if (!ammo->Save(a_intfc, kAmmo, kSerializationVersion)) {
_ERROR("Failed to save ammo!\n");
ammo->Clear();
}
auto shield = Shield::Shield::GetSingleton();
if (!shield->Save(a_intfc, kShield, kSerializationVersion)) {
_ERROR("Failed to save shield!\n");
shield->Clear();
}
auto helmet = Helmet::Helmet::GetSingleton();
if (!helmet->Save(a_intfc, kHelmet, kSerializationVersion)) {
_ERROR("Failed to save helmet!\n");
helmet->Clear();
}
_MESSAGE("Finished saving data");
}
void LoadCallback(SKSE::SerializationInterface* a_intfc)
{
auto helmet = Helmet::Helmet::GetSingleton();
helmet->Clear();
auto ammo = Ammo::Ammo::GetSingleton();
ammo->Clear();
auto shield = Shield::Shield::GetSingleton();
shield->Clear();
UInt32 type;
UInt32 version;
UInt32 length;
while (a_intfc->GetNextRecordInfo(type, version, length)) {
if (version != kSerializationVersion) {
_ERROR("Loaded data is out of date! Read (%u), expected (%u) for type code (%s)", version, kSerializationVersion, DecodeTypeCode(type).c_str());
continue;
}
switch (type) {
case kAmmo:
if (!ammo->Load(a_intfc)) {
_ERROR("Failed to load ammo!\n");
ammo->Clear();
}
break;
case kHelmet:
if (!helmet->Load(a_intfc)) {
_ERROR("Failed to load helmet!\n");
helmet->Clear();
}
break;
case kShield:
if (!shield->Load(a_intfc)) {
_ERROR("Failed to load shield!\n");
shield->Clear();
}
break;
default:
_ERROR("Unrecognized record type (%s)!", DecodeTypeCode(type).c_str());
break;
}
}
_MESSAGE("Finished loading data");
}
class TESObjectLoadedEventHandler final : public RE::BSTEventSink<RE::TESObjectLoadedEvent>
{
public:
using EventResult = RE::BSEventNotifyControl;
static TESObjectLoadedEventHandler* GetSingleton()
{
static TESObjectLoadedEventHandler singleton;
return std::addressof(singleton);
}
auto ProcessEvent(const RE::TESObjectLoadedEvent* a_event, RE::BSTEventSource<RE::TESObjectLoadedEvent>* a_eventSource)
-> EventResult override
{
if (!a_event) {
return EventResult::kContinue;
}
const auto player = RE::PlayerCharacter::GetSingleton();
if (a_event->formID == player->formID) {
if (*Settings::manageHelmet) {
if (AnimationGraphEventHandler(Helmet::BSAnimationGraphEventHandler::GetSingleton())) {
_MESSAGE("Registered helmet player animation event handler");
}
}
if (*Settings::manageShield) {
if (AnimationGraphEventHandler(Shield::BSAnimationGraphEventHandler::GetSingleton())) {
_MESSAGE("Registered shield player animation event handler");
}
}
}
return EventResult::kContinue;
}
TESObjectLoadedEventHandler(const TESObjectLoadedEventHandler&) = delete;
TESObjectLoadedEventHandler(TESObjectLoadedEventHandler&&) = delete;
TESObjectLoadedEventHandler& operator=(const TESObjectLoadedEventHandler&) = delete;
TESObjectLoadedEventHandler& operator=(TESObjectLoadedEventHandler&&) = delete;
protected:
TESObjectLoadedEventHandler() = default;
virtual ~TESObjectLoadedEventHandler() = default;
};
void MessageHandler(SKSE::MessagingInterface::Message* a_msg)
{
switch (a_msg->type) {
case SKSE::MessagingInterface::kDataLoaded:
{
auto sourceHolder = RE::ScriptEventSourceHolder::GetSingleton();
sourceHolder->AddEventSink(TESObjectLoadedEventHandler::GetSingleton());
_MESSAGE("Registered object loaded event handler");
if (*Settings::manageHelmet) {
sourceHolder->AddEventSink(Helmet::TESEquipEventHandler::GetSingleton());
_MESSAGE("Registered helmet equip event handler");
}
if (*Settings::manageAmmo) {
sourceHolder->AddEventSink(Ammo::TESEquipEventHandler::GetSingleton());
_MESSAGE("Registered ammo equip event handler");
}
if (*Settings::manageShield) {
sourceHolder->AddEventSink(Shield::TESEquipEventHandler::GetSingleton());
_MESSAGE("Registered shield equip event handler");
}
}
break;
default: ;
}
}
}
extern "C"
{
bool SKSEPlugin_Query(const SKSE::QueryInterface* a_skse, SKSE::PluginInfo* a_info)
{
SKSE::Logger::OpenRelative(FOLDERID_Documents, L"\\My Games\\Skyrim Special Edition\\SKSE\\DynamicEquipmentManagerSSE.log");
SKSE::Logger::SetPrintLevel(SKSE::Logger::Level::kDebugMessage);
SKSE::Logger::SetFlushLevel(SKSE::Logger::Level::kDebugMessage);
SKSE::Logger::UseLogStamp(true);
_MESSAGE("DynamicEquipmentManagerSSE - Updated v%s", DNEM_VERSION_VERSTRING);
a_info->infoVersion = SKSE::PluginInfo::kVersion;
a_info->name = "DynamicEquipmentManagerSSE-Updated";
a_info->version = DNEM_VERSION_MAJOR;
if (a_skse->IsEditor()) {
_FATALERROR("Loaded in editor, marking as incompatible!\n");
return false;
}
const auto ver = a_skse->RuntimeVersion();
if (ver <= SKSE::RUNTIME_1_5_39) {
_FATALERROR("Unsupported runtime version %s!", ver.GetString().c_str());
return false;
}
return true;
}
bool SKSEPlugin_Load(const SKSE::LoadInterface* a_skse)
{
_MESSAGE("DynamicEquipmentManagerSSE loaded");
if (!Init(a_skse)) {
return false;
}
if (Settings::LoadSettings()) {
_MESSAGE("Settings loaded successfully");
} else {
_FATALERROR("Failed to load settings!\n");
return false;
}
const auto messaging = SKSE::GetMessagingInterface();
if (messaging->RegisterListener("SKSE", MessageHandler)) {
_MESSAGE("Messaging interface registration successful");
} else {
_FATALERROR("Messaging interface registration failed!\n");
return false;
}
const auto serialization = SKSE::GetSerializationInterface();
serialization->SetUniqueID(kDynamicEquipmentManager);
serialization->SetSaveCallback(SaveCallback);
serialization->SetLoadCallback(LoadCallback);
if (*Settings::manageShield) {
// TODO : Update the hooks with new offset
//Shield::InstallHooks();
//_MESSAGE("Installed hooks for shield");
}
return true;
}
};
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
** Header: AppDomain.cpp
**
**
** Purpose: Implements AppDomain (loader domain) architecture
**
**
===========================================================*/
#ifndef _APPDOMAIN_H
#define _APPDOMAIN_H
#include "eventtrace.h"
#include "assembly.hpp"
#include "clsload.hpp"
#include "eehash.h"
#include "arraylist.h"
#include "comreflectioncache.hpp"
#include "comutilnative.h"
#include "domainfile.h"
#include "fptrstubs.h"
#include "gcheaputilities.h"
#include "gchandleutilities.h"
#include "rejit.h"
#ifdef FEATURE_MULTICOREJIT
#include "multicorejit.h"
#endif
#include "tieredcompilation.h"
#include "codeversion.h"
class BaseDomain;
class SystemDomain;
class AppDomain;
class GlobalStringLiteralMap;
class StringLiteralMap;
class MngStdInterfacesInfo;
class DomainAssembly;
class LoadLevelLimiter;
class TypeEquivalenceHashTable;
#ifdef FEATURE_COMINTEROP
class RCWCache;
#endif //FEATURE_COMINTEROP
#ifdef FEATURE_COMWRAPPERS
class RCWRefCache;
#endif // FEATURE_COMWRAPPERS
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4200) // Disable zero-sized array warning
#endif
GPTR_DECL(IdDispenser, g_pModuleIndexDispenser);
// We would like *ALLOCATECLASS_FLAG to AV (in order to catch errors), so don't change it
struct ClassInitFlags {
enum
{
INITIALIZED_FLAG_BIT = 0,
INITIALIZED_FLAG = 1<<INITIALIZED_FLAG_BIT,
ERROR_FLAG_BIT = 1,
ERROR_FLAG = 1<<ERROR_FLAG_BIT,
ALLOCATECLASS_FLAG_BIT = 2, // Bit to avoid racing for InstantiateStaticHandles
ALLOCATECLASS_FLAG = 1<<ALLOCATECLASS_FLAG_BIT,
COLLECTIBLE_FLAG_BIT = 3,
COLLECTIBLE_FLAG = 1<<COLLECTIBLE_FLAG_BIT
};
};
struct DomainLocalModule
{
friend class ClrDataAccess;
friend class CheckAsmOffsets;
friend struct ThreadLocalModule;
// After these macros complete, they may have returned an interior pointer into a gc object. This pointer will have been cast to a byte pointer
// It is critically important that no GC is allowed to occur before this pointer is used.
#define GET_DYNAMICENTRY_GCSTATICS_BASEPOINTER(pLoaderAllocator, dynamicClassInfoParam, pGCStatics) \
{\
DomainLocalModule::PTR_DynamicClassInfo dynamicClassInfo = dac_cast<DomainLocalModule::PTR_DynamicClassInfo>(dynamicClassInfoParam);\
DomainLocalModule::PTR_DynamicEntry pDynamicEntry = dac_cast<DomainLocalModule::PTR_DynamicEntry>((DomainLocalModule::DynamicEntry*)dynamicClassInfo->m_pDynamicEntry.Load()); \
if ((dynamicClassInfo->m_dwFlags) & ClassInitFlags::COLLECTIBLE_FLAG) \
{\
PTRARRAYREF objArray;\
objArray = (PTRARRAYREF)pLoaderAllocator->GetHandleValueFastCannotFailType2( \
(dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hGCStatics);\
*(pGCStatics) = dac_cast<PTR_BYTE>(PTR_READ(PTR_TO_TADDR(OBJECTREFToObject( objArray )) + offsetof(PtrArray, m_Array), objArray->GetNumComponents() * sizeof(void*))) ;\
}\
else\
{\
*(pGCStatics) = (dac_cast<DomainLocalModule::PTR_NormalDynamicEntry>(pDynamicEntry))->GetGCStaticsBasePointer();\
}\
}\
#define GET_DYNAMICENTRY_NONGCSTATICS_BASEPOINTER(pLoaderAllocator, dynamicClassInfoParam, pNonGCStatics) \
{\
DomainLocalModule::PTR_DynamicClassInfo dynamicClassInfo = dac_cast<DomainLocalModule::PTR_DynamicClassInfo>(dynamicClassInfoParam);\
DomainLocalModule::PTR_DynamicEntry pDynamicEntry = dac_cast<DomainLocalModule::PTR_DynamicEntry>((DomainLocalModule::DynamicEntry*)(dynamicClassInfo)->m_pDynamicEntry.Load()); \
if (((dynamicClassInfo)->m_dwFlags) & ClassInitFlags::COLLECTIBLE_FLAG) \
{\
if ((dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hNonGCStatics != 0) \
{ \
U1ARRAYREF objArray;\
objArray = (U1ARRAYREF)pLoaderAllocator->GetHandleValueFastCannotFailType2( \
(dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hNonGCStatics);\
*(pNonGCStatics) = dac_cast<PTR_BYTE>(PTR_READ( \
PTR_TO_TADDR(OBJECTREFToObject( objArray )) + sizeof(ArrayBase) - DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob(), \
objArray->GetNumComponents() * (DWORD)objArray->GetComponentSize() + DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob())); \
} else (*pNonGCStatics) = NULL; \
}\
else\
{\
*(pNonGCStatics) = dac_cast<DomainLocalModule::PTR_NormalDynamicEntry>(pDynamicEntry)->GetNonGCStaticsBasePointer();\
}\
}\
struct DynamicEntry
{
static DWORD GetOffsetOfDataBlob();
};
typedef DPTR(DynamicEntry) PTR_DynamicEntry;
struct CollectibleDynamicEntry : public DynamicEntry
{
LOADERHANDLE m_hGCStatics;
LOADERHANDLE m_hNonGCStatics;
};
typedef DPTR(CollectibleDynamicEntry) PTR_CollectibleDynamicEntry;
struct NormalDynamicEntry : public DynamicEntry
{
PTR_OBJECTREF m_pGCStatics;
#ifdef FEATURE_64BIT_ALIGNMENT
// Padding to make m_pDataBlob aligned at MAX_PRIMITIVE_FIELD_SIZE
// code:MethodTableBuilder::PlaceRegularStaticFields assumes that the start of the data blob is aligned
SIZE_T m_padding;
#endif
BYTE m_pDataBlob[0];
inline PTR_BYTE GetGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return dac_cast<PTR_BYTE>(m_pGCStatics);
}
inline PTR_BYTE GetNonGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT
SUPPORTS_DAC;
return dac_cast<PTR_BYTE>(this);
}
};
typedef DPTR(NormalDynamicEntry) PTR_NormalDynamicEntry;
struct DynamicClassInfo
{
VolatilePtr<DynamicEntry, PTR_DynamicEntry> m_pDynamicEntry;
Volatile<DWORD> m_dwFlags;
};
typedef DPTR(DynamicClassInfo) PTR_DynamicClassInfo;
inline UMEntryThunk * GetADThunkTable()
{
LIMITED_METHOD_CONTRACT
return m_pADThunkTable;
}
inline void SetADThunkTable(UMEntryThunk* pADThunkTable)
{
LIMITED_METHOD_CONTRACT
InterlockedCompareExchangeT(m_pADThunkTable.GetPointer(), pADThunkTable, NULL);
}
// Note the difference between:
//
// GetPrecomputedNonGCStaticsBasePointer() and
// GetPrecomputedStaticsClassData()
//
// GetPrecomputedNonGCStaticsBasePointer returns the pointer that should be added to field offsets to retrieve statics
// GetPrecomputedStaticsClassData returns a pointer to the first byte of the precomputed statics block
inline TADDR GetPrecomputedNonGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT
return dac_cast<TADDR>(this);
}
inline PTR_BYTE GetPrecomputedStaticsClassData()
{
LIMITED_METHOD_CONTRACT
return dac_cast<PTR_BYTE>(this) + offsetof(DomainLocalModule, m_pDataBlob);
}
static SIZE_T GetOffsetOfDataBlob() { return offsetof(DomainLocalModule, m_pDataBlob); }
static SIZE_T GetOffsetOfGCStaticPointer() { return offsetof(DomainLocalModule, m_pGCStatics); }
inline DomainFile* GetDomainFile()
{
LIMITED_METHOD_CONTRACT
SUPPORTS_DAC;
return m_pDomainFile;
}
#ifndef DACCESS_COMPILE
inline void SetDomainFile(DomainFile* pDomainFile)
{
LIMITED_METHOD_CONTRACT
m_pDomainFile = pDomainFile;
}
#endif
inline PTR_OBJECTREF GetPrecomputedGCStaticsBasePointer()
{
LIMITED_METHOD_CONTRACT
return m_pGCStatics;
}
inline PTR_OBJECTREF * GetPrecomputedGCStaticsBasePointerAddress()
{
LIMITED_METHOD_CONTRACT
return &m_pGCStatics;
}
// Returns bytes so we can add offsets
inline PTR_BYTE GetGCStaticsBasePointer(MethodTable * pMT)
{
WRAPPER_NO_CONTRACT
SUPPORTS_DAC;
if (pMT->IsDynamicStatics())
{
_ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
return GetDynamicEntryGCStaticsBasePointer(pMT->GetModuleDynamicEntryID(), pMT->GetLoaderAllocator());
}
else
{
return dac_cast<PTR_BYTE>(m_pGCStatics);
}
}
inline PTR_BYTE GetNonGCStaticsBasePointer(MethodTable * pMT)
{
WRAPPER_NO_CONTRACT
SUPPORTS_DAC;
if (pMT->IsDynamicStatics())
{
_ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
return GetDynamicEntryNonGCStaticsBasePointer(pMT->GetModuleDynamicEntryID(), pMT->GetLoaderAllocator());
}
else
{
return dac_cast<PTR_BYTE>(this);
}
}
inline DynamicClassInfo* GetDynamicClassInfo(DWORD n)
{
LIMITED_METHOD_CONTRACT
SUPPORTS_DAC;
_ASSERTE(m_pDynamicClassTable.Load() && m_aDynamicEntries > n);
dac_cast<PTR_DynamicEntry>(m_pDynamicClassTable[n].m_pDynamicEntry.Load());
return &m_pDynamicClassTable[n];
}
// These helpers can now return null, as the debugger may do queries on a type
// before the calls to PopulateClass happen
inline PTR_BYTE GetDynamicEntryGCStaticsBasePointer(DWORD n, PTR_LoaderAllocator pLoaderAllocator)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (n >= m_aDynamicEntries)
{
return NULL;
}
DynamicClassInfo* pClassInfo = GetDynamicClassInfo(n);
if (!pClassInfo->m_pDynamicEntry)
{
return NULL;
}
PTR_BYTE retval = NULL;
GET_DYNAMICENTRY_GCSTATICS_BASEPOINTER(pLoaderAllocator, pClassInfo, &retval);
return retval;
}
inline PTR_BYTE GetDynamicEntryNonGCStaticsBasePointer(DWORD n, PTR_LoaderAllocator pLoaderAllocator)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (n >= m_aDynamicEntries)
{
return NULL;
}
DynamicClassInfo* pClassInfo = GetDynamicClassInfo(n);
if (!pClassInfo->m_pDynamicEntry)
{
return NULL;
}
PTR_BYTE retval = NULL;
GET_DYNAMICENTRY_NONGCSTATICS_BASEPOINTER(pLoaderAllocator, pClassInfo, &retval);
return retval;
}
FORCEINLINE PTR_DynamicClassInfo GetDynamicClassInfoIfInitialized(DWORD n)
{
WRAPPER_NO_CONTRACT;
// m_aDynamicEntries is set last, it needs to be checked first
if (n >= m_aDynamicEntries)
{
return NULL;
}
_ASSERTE(m_pDynamicClassTable.Load() != NULL);
PTR_DynamicClassInfo pDynamicClassInfo = (PTR_DynamicClassInfo)(m_pDynamicClassTable.Load() + n);
// INITIALIZED_FLAG is set last, it needs to be checked first
if ((pDynamicClassInfo->m_dwFlags & ClassInitFlags::INITIALIZED_FLAG) == 0)
{
return NULL;
}
PREFIX_ASSUME(pDynamicClassInfo != NULL);
return pDynamicClassInfo;
}
// iClassIndex is slightly expensive to compute, so if we already know
// it, we can use this helper
inline BOOL IsClassInitialized(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
{
WRAPPER_NO_CONTRACT;
return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::INITIALIZED_FLAG) != 0;
}
inline BOOL IsPrecomputedClassInitialized(DWORD classID)
{
return GetPrecomputedStaticsClassData()[classID] & ClassInitFlags::INITIALIZED_FLAG;
}
inline BOOL IsClassAllocated(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
{
WRAPPER_NO_CONTRACT;
return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::ALLOCATECLASS_FLAG) != 0;
}
BOOL IsClassInitError(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
{
WRAPPER_NO_CONTRACT;
return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::ERROR_FLAG) != 0;
}
void SetClassInitialized(MethodTable* pMT);
void SetClassInitError(MethodTable* pMT);
void EnsureDynamicClassIndex(DWORD dwID);
void AllocateDynamicClass(MethodTable *pMT);
void PopulateClass(MethodTable *pMT);
#ifdef DACCESS_COMPILE
void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
#endif
static DWORD OffsetOfDataBlob()
{
LIMITED_METHOD_CONTRACT;
return offsetof(DomainLocalModule, m_pDataBlob);
}
FORCEINLINE MethodTable * GetMethodTableFromClassDomainID(DWORD dwClassDomainID)
{
DWORD rid = (DWORD)(dwClassDomainID) + 1;
TypeHandle th = GetDomainFile()->GetModule()->LookupTypeDef(TokenFromRid(rid, mdtTypeDef));
_ASSERTE(!th.IsNull());
MethodTable * pMT = th.AsMethodTable();
PREFIX_ASSUME(pMT != NULL);
return pMT;
}
private:
friend void EmitFastGetSharedStaticBase(CPUSTUBLINKER *psl, CodeLabel *init, bool bCCtorCheck);
void SetClassFlags(MethodTable* pMT, DWORD dwFlags);
DWORD GetClassFlags(MethodTable* pMT, DWORD iClassIndex);
PTR_DomainFile m_pDomainFile;
VolatilePtr<DynamicClassInfo, PTR_DynamicClassInfo> m_pDynamicClassTable; // used for generics and reflection.emit in memory
Volatile<SIZE_T> m_aDynamicEntries; // number of entries in dynamic table
VolatilePtr<UMEntryThunk> m_pADThunkTable;
PTR_OBJECTREF m_pGCStatics; // Handle to GC statics of the module
// In addition to storing the ModuleIndex in the Module class, we also
// keep a copy of the ModuleIndex in the DomainLocalModule class. This
// allows the thread static JIT helpers to quickly convert a pointer to
// a DomainLocalModule into a ModuleIndex.
ModuleIndex m_ModuleIndex;
// Note that the static offset calculation in code:Module::BuildStaticsOffsets takes the offset m_pDataBlob
// into consideration for alignment so we do not need any padding to ensure that the start of the data blob is aligned
BYTE m_pDataBlob[0]; // First byte of the statics blob
// Layout of m_pDataBlob is:
// ClassInit bytes (hold flags for cctor run, cctor error, etc)
// Non GC Statics
public:
// The Module class need to be able to initialized ModuleIndex,
// so for now I will make it a friend..
friend class Module;
FORCEINLINE ModuleIndex GetModuleIndex()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_ModuleIndex;
}
}; // struct DomainLocalModule
#define OFFSETOF__DomainLocalModule__m_pDataBlob_ (6 * TARGET_POINTER_SIZE)
#ifdef FEATURE_64BIT_ALIGNMENT
#define OFFSETOF__DomainLocalModule__NormalDynamicEntry__m_pDataBlob (TARGET_POINTER_SIZE /* m_pGCStatics */ + TARGET_POINTER_SIZE /* m_padding */)
#else
#define OFFSETOF__DomainLocalModule__NormalDynamicEntry__m_pDataBlob TARGET_POINTER_SIZE /* m_pGCStatics */
#endif
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// The pinned heap handle bucket class is used to contain handles allocated
// from an array contained in the pinned heap.
class PinnedHeapHandleBucket
{
public:
// Constructor and desctructor.
PinnedHeapHandleBucket(PinnedHeapHandleBucket *pNext, DWORD Size, BaseDomain *pDomain);
~PinnedHeapHandleBucket();
// This returns the next bucket.
PinnedHeapHandleBucket *GetNext()
{
LIMITED_METHOD_CONTRACT;
return m_pNext;
}
// This returns the number of remaining handle slots.
DWORD GetNumRemainingHandles()
{
LIMITED_METHOD_CONTRACT;
return m_ArraySize - m_CurrentPos;
}
void ConsumeRemaining()
{
LIMITED_METHOD_CONTRACT;
m_CurrentPos = m_ArraySize;
}
OBJECTREF *TryAllocateEmbeddedFreeHandle();
// Allocate handles from the bucket.
OBJECTREF* AllocateHandles(DWORD nRequested);
OBJECTREF* CurrentPos()
{
LIMITED_METHOD_CONTRACT;
return m_pArrayDataPtr + m_CurrentPos;
}
void EnumStaticGCRefs(promote_func* fn, ScanContext* sc);
private:
PinnedHeapHandleBucket *m_pNext;
int m_ArraySize;
int m_CurrentPos;
int m_CurrentEmbeddedFreePos;
OBJECTHANDLE m_hndHandleArray;
OBJECTREF *m_pArrayDataPtr;
};
// The pinned heap handle table is used to allocate handles that are pointers
// to objects stored in an array in the pinned object heap.
class PinnedHeapHandleTable
{
public:
// Constructor and desctructor.
PinnedHeapHandleTable(BaseDomain *pDomain, DWORD InitialBucketSize);
~PinnedHeapHandleTable();
// Allocate handles from the pinned heap handle table.
OBJECTREF* AllocateHandles(DWORD nRequested);
// Release object handles allocated using AllocateHandles().
void ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased);
void EnumStaticGCRefs(promote_func* fn, ScanContext* sc);
private:
// The buckets of object handles.
PinnedHeapHandleBucket *m_pHead;
// We need to know the containing domain so we know where to allocate handles
BaseDomain *m_pDomain;
// The size of the PinnedHeapHandleBucket.
DWORD m_NextBucketSize;
// for finding and re-using embedded free items in the list
PinnedHeapHandleBucket *m_pFreeSearchHint;
DWORD m_cEmbeddedFree;
#ifdef _DEBUG
// these functions are present to enforce that there is a locking mechanism in place
// for each PinnedHeapHandleTable even though the code itself does not do the locking
// you must tell the table which lock you intend to use and it will verify that it has
// in fact been taken before performing any operations
public:
void RegisterCrstDebug(CrstBase *pCrst)
{
LIMITED_METHOD_CONTRACT;
// this function must be called exactly once
_ASSERTE(pCrst != NULL);
_ASSERTE(m_pCrstDebug == NULL);
m_pCrstDebug = pCrst;
}
private:
// we will assert that this Crst is held before using the object
CrstBase *m_pCrstDebug;
#endif
};
class PinnedHeapHandleBlockHolder;
void PinnedHeapHandleBlockHolder__StaticFree(PinnedHeapHandleBlockHolder*);
class PinnedHeapHandleBlockHolder:public Holder<PinnedHeapHandleBlockHolder*,DoNothing,PinnedHeapHandleBlockHolder__StaticFree>
{
PinnedHeapHandleTable* m_pTable;
DWORD m_Count;
OBJECTREF* m_Data;
public:
FORCEINLINE PinnedHeapHandleBlockHolder(PinnedHeapHandleTable* pOwner, DWORD nCount)
{
WRAPPER_NO_CONTRACT;
m_Data = pOwner->AllocateHandles(nCount);
m_Count=nCount;
m_pTable=pOwner;
};
FORCEINLINE void FreeData()
{
WRAPPER_NO_CONTRACT;
for (DWORD i=0;i< m_Count;i++)
ClearObjectReference(m_Data+i);
m_pTable->ReleaseHandles(m_Data, m_Count);
};
FORCEINLINE OBJECTREF* operator[] (DWORD idx)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(idx<m_Count);
return &(m_Data[idx]);
}
};
FORCEINLINE void PinnedHeapHandleBlockHolder__StaticFree(PinnedHeapHandleBlockHolder* pHolder)
{
WRAPPER_NO_CONTRACT;
pHolder->FreeData();
};
// The large heap handle bucket class is used to contain handles allocated
// from an array contained in the large heap.
class ThreadStaticHandleBucket
{
public:
// Constructor and desctructor.
ThreadStaticHandleBucket(ThreadStaticHandleBucket *pNext, DWORD Size, BaseDomain *pDomain);
~ThreadStaticHandleBucket();
// This returns the next bucket.
ThreadStaticHandleBucket *GetNext()
{
LIMITED_METHOD_CONTRACT;
return m_pNext;
}
// Allocate handles from the bucket.
OBJECTHANDLE GetHandles();
private:
ThreadStaticHandleBucket *m_pNext;
int m_ArraySize;
OBJECTHANDLE m_hndHandleArray;
};
// The large heap handle table is used to allocate handles that are pointers
// to objects stored in an array in the large object heap.
class ThreadStaticHandleTable
{
public:
// Constructor and desctructor.
ThreadStaticHandleTable(BaseDomain *pDomain);
~ThreadStaticHandleTable();
// Allocate handles from the large heap handle table.
OBJECTHANDLE AllocateHandles(DWORD nRequested);
private:
// The buckets of object handles.
ThreadStaticHandleBucket *m_pHead;
// We need to know the containing domain so we know where to allocate handles
BaseDomain *m_pDomain;
};
//--------------------------------------------------------------------------------------
// Base class for domains. It provides an abstract way of finding the first assembly and
// for creating assemblies in the the domain. The system domain only has one assembly, it
// contains the classes that are logically shared between domains. All other domains can
// have multiple assemblies. Iteration is done be getting the first assembly and then
// calling the Next() method on the assembly.
//
// The system domain should be as small as possible, it includes object, exceptions, etc.
// which are the basic classes required to load other assemblies. All other classes
// should be loaded into the domain. Of coarse there is a trade off between loading the
// same classes multiple times, requiring all domains to load certain assemblies (working
// set) and being able to specify specific versions.
//
#define LOW_FREQUENCY_HEAP_RESERVE_SIZE (3 * GetOsPageSize())
#define LOW_FREQUENCY_HEAP_COMMIT_SIZE (1 * GetOsPageSize())
#define HIGH_FREQUENCY_HEAP_RESERVE_SIZE (10 * GetOsPageSize())
#define HIGH_FREQUENCY_HEAP_COMMIT_SIZE (1 * GetOsPageSize())
#define STUB_HEAP_RESERVE_SIZE (3 * GetOsPageSize())
#define STUB_HEAP_COMMIT_SIZE (1 * GetOsPageSize())
// --------------------------------------------------------------------------------
// PE File List lock - for creating list locks on PE files
// --------------------------------------------------------------------------------
class PEFileListLock : public ListLock
{
public:
#ifndef DACCESS_COMPILE
ListLockEntry *FindFileLock(PEFile *pFile)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
PRECONDITION(HasLock());
ListLockEntry *pEntry;
for (pEntry = m_pHead;
pEntry != NULL;
pEntry = pEntry->m_pNext)
{
if (((PEFile *)pEntry->m_data)->Equals(pFile))
{
return pEntry;
}
}
return NULL;
}
#endif // DACCESS_COMPILE
DEBUG_NOINLINE static void HolderEnter(PEFileListLock *pThis)
{
WRAPPER_NO_CONTRACT;
ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
pThis->Enter();
}
DEBUG_NOINLINE static void HolderLeave(PEFileListLock *pThis)
{
WRAPPER_NO_CONTRACT;
ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
pThis->Leave();
}
typedef Wrapper<PEFileListLock*, PEFileListLock::HolderEnter, PEFileListLock::HolderLeave> Holder;
};
typedef PEFileListLock::Holder PEFileListLockHolder;
// Loading infrastructure:
//
// a DomainFile is a file being loaded. Files are loaded in layers to enable loading in the
// presence of dependency loops.
//
// FileLoadLevel describes the various levels available. These are implemented slightly
// differently for assemblies and modules, but the basic structure is the same.
//
// LoadLock and FileLoadLock form the ListLock data structures for files. The FileLoadLock
// is specialized in that it allows taking a lock at a particular level. Basicall any
// thread may obtain the lock at a level at which the file has previously been loaded to, but
// only one thread may obtain the lock at its current level.
//
// The PendingLoadQueue is a per thread data structure which serves two purposes. First, it
// holds a "load limit" which automatically restricts the level of recursive loads to be
// one less than the current load which is preceding. This, together with the AppDomain
// LoadLock level behavior, will prevent any deadlocks from occuring due to circular
// dependencies. (Note that it is important that the loading logic understands this restriction,
// and any given level of loading must deal with the fact that any recursive loads will be partially
// unfulfilled in a specific way.)
//
// The second function is to queue up any unfulfilled load requests for the thread. These
// are then delivered immediately after the current load request is dealt with.
class FileLoadLock : public ListLockEntry
{
private:
FileLoadLevel m_level;
DomainFile *m_pDomainFile;
HRESULT m_cachedHR;
public:
static FileLoadLock *Create(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile);
~FileLoadLock();
DomainFile *GetDomainFile();
FileLoadLevel GetLoadLevel();
// CanAcquire will return FALSE if Acquire will definitely not take the lock due
// to levels or deadlock.
// (Note that there is a race exiting from the function, where Acquire may end
// up not taking the lock anyway if another thread did work in the meantime.)
BOOL CanAcquire(FileLoadLevel targetLevel);
// Acquire will return FALSE and not take the lock if the file
// has already been loaded to the target level. Otherwise,
// it will return TRUE and take the lock.
//
// Note that the taker must release the lock via IncrementLoadLevel.
BOOL Acquire(FileLoadLevel targetLevel);
// CompleteLoadLevel can be called after Acquire returns true
// returns TRUE if it updated load level, FALSE if the level was set already
BOOL CompleteLoadLevel(FileLoadLevel level, BOOL success);
void SetError(Exception *ex);
void AddRef();
UINT32 Release() DAC_EMPTY_RET(0);
private:
FileLoadLock(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile);
static void HolderLeave(FileLoadLock *pThis);
public:
typedef Wrapper<FileLoadLock *, DoNothing, FileLoadLock::HolderLeave> Holder;
};
typedef FileLoadLock::Holder FileLoadLockHolder;
#ifndef DACCESS_COMPILE
typedef ReleaseHolder<FileLoadLock> FileLoadLockRefHolder;
#endif // DACCESS_COMPILE
typedef ListLockBase<NativeCodeVersion> JitListLock;
typedef ListLockEntryBase<NativeCodeVersion> JitListLockEntry;
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning (disable: 4324) //sometimes 64bit compilers complain about alignment
#endif
class LoadLevelLimiter
{
FileLoadLevel m_currentLevel;
LoadLevelLimiter* m_previousLimit;
BOOL m_bActive;
public:
LoadLevelLimiter()
: m_currentLevel(FILE_ACTIVE),
m_previousLimit(NULL),
m_bActive(FALSE)
{
LIMITED_METHOD_CONTRACT;
}
void Activate()
{
WRAPPER_NO_CONTRACT;
m_previousLimit= GetThread()->GetLoadLevelLimiter();
if(m_previousLimit)
m_currentLevel=m_previousLimit->GetLoadLevel();
GetThread()->SetLoadLevelLimiter(this);
m_bActive=TRUE;
}
void Deactivate()
{
WRAPPER_NO_CONTRACT;
if (m_bActive)
{
GetThread()->SetLoadLevelLimiter(m_previousLimit);
m_bActive=FALSE;
}
}
~LoadLevelLimiter()
{
WRAPPER_NO_CONTRACT;
// PendingLoadQueues are allocated on the stack during a load, and
// shared with all nested loads on the same thread.
// Make sure the thread pointer gets reset after the
// top level queue goes out of scope.
if(m_bActive)
{
Deactivate();
}
}
FileLoadLevel GetLoadLevel()
{
LIMITED_METHOD_CONTRACT;
return m_currentLevel;
}
void SetLoadLevel(FileLoadLevel level)
{
LIMITED_METHOD_CONTRACT;
m_currentLevel = level;
}
};
#ifdef _MSC_VER
#pragma warning (pop) //4324
#endif
#define OVERRIDE_LOAD_LEVEL_LIMIT(newLimit) \
LoadLevelLimiter __newLimit; \
__newLimit.Activate(); \
__newLimit.SetLoadLevel(newLimit);
// A BaseDomain much basic information in a code:AppDomain including
//
// * code:#AppdomainHeaps - Heaps for any data structures that will be freed on appdomain unload
//
class BaseDomain
{
friend class Assembly;
friend class AssemblySpec;
friend class AppDomain;
friend class AppDomainNative;
VPTR_BASE_VTABLE_CLASS(BaseDomain)
VPTR_UNIQUE(VPTR_UNIQUE_BaseDomain)
public:
class AssemblyIterator;
friend class AssemblyIterator;
// Static initialization.
static void Attach();
//****************************************************************************************
//
// Initialization/shutdown routines for every instance of an BaseDomain.
BaseDomain();
virtual ~BaseDomain() {}
void Init();
void Stop();
virtual BOOL IsAppDomain() { LIMITED_METHOD_DAC_CONTRACT; return FALSE; }
PTR_LoaderAllocator GetLoaderAllocator();
virtual PTR_AppDomain AsAppDomain()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!"Not an AppDomain");
return NULL;
}
#ifdef FEATURE_COMINTEROP
MngStdInterfacesInfo * GetMngStdInterfacesInfo()
{
LIMITED_METHOD_CONTRACT;
return m_pMngStdInterfacesInfo;
}
#endif // FEATURE_COMINTEROP
#ifdef _DEBUG
BOOL OwnDomainLocalBlockLock()
{
WRAPPER_NO_CONTRACT;
return m_DomainLocalBlockCrst.OwnedByCurrentThread();
}
#endif
//****************************************************************************************
// Get the class init lock. The method is limited to friends because inappropriate use
// will cause deadlocks in the system
ListLock* GetClassInitLock()
{
LIMITED_METHOD_CONTRACT;
return &m_ClassInitLock;
}
JitListLock* GetJitLock()
{
LIMITED_METHOD_CONTRACT;
return &m_JITLock;
}
ListLock* GetILStubGenLock()
{
LIMITED_METHOD_CONTRACT;
return &m_ILStubGenLock;
}
ListLock* GetNativeTypeLoadLock()
{
LIMITED_METHOD_CONTRACT;
return &m_NativeTypeLoadLock;
}
STRINGREF *IsStringInterned(STRINGREF *pString);
STRINGREF *GetOrInternString(STRINGREF *pString);
// Returns an array of OBJECTREF* that can be used to store domain specific data.
// Statics and reflection info (Types, MemberInfo,..) are stored this way
// If ppLazyAllocate != 0, allocation will only take place if *ppLazyAllocate != 0 (and the allocation
// will be properly serialized)
OBJECTREF *AllocateObjRefPtrsInLargeTable(int nRequested, OBJECTREF** ppLazyAllocate = NULL);
//****************************************************************************************
// Handles
#if !defined(DACCESS_COMPILE)
IGCHandleStore* GetHandleStore()
{
LIMITED_METHOD_CONTRACT;
return m_handleStore;
}
OBJECTHANDLE CreateTypedHandle(OBJECTREF object, HandleType type)
{
WRAPPER_NO_CONTRACT;
return ::CreateHandleCommon(m_handleStore, object, type);
}
OBJECTHANDLE CreateHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
CONDITIONAL_CONTRACT_VIOLATION(ModeViolation, object == NULL)
return ::CreateHandle(m_handleStore, object);
}
OBJECTHANDLE CreateWeakHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateWeakHandle(m_handleStore, object);
}
OBJECTHANDLE CreateShortWeakHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateShortWeakHandle(m_handleStore, object);
}
OBJECTHANDLE CreateLongWeakHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
CONDITIONAL_CONTRACT_VIOLATION(ModeViolation, object == NULL)
return ::CreateLongWeakHandle(m_handleStore, object);
}
OBJECTHANDLE CreateStrongHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateStrongHandle(m_handleStore, object);
}
OBJECTHANDLE CreatePinningHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreatePinningHandle(m_handleStore, object);
}
OBJECTHANDLE CreateSizedRefHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
OBJECTHANDLE h;
if (GCHeapUtilities::IsServerHeap())
{
h = ::CreateSizedRefHandle(m_handleStore, object, m_dwSizedRefHandles % m_iNumberOfProcessors);
}
else
{
h = ::CreateSizedRefHandle(m_handleStore, object);
}
InterlockedIncrement((LONG*)&m_dwSizedRefHandles);
return h;
}
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_COMWRAPPERS)
OBJECTHANDLE CreateRefcountedHandle(OBJECTREF object)
{
WRAPPER_NO_CONTRACT;
return ::CreateRefcountedHandle(m_handleStore, object);
}
OBJECTHANDLE CreateNativeComWeakHandle(OBJECTREF object, NativeComWeakHandleInfo* pComWeakHandleInfo)
{
WRAPPER_NO_CONTRACT;
return ::CreateNativeComWeakHandle(m_handleStore, object, pComWeakHandleInfo);
}
#endif // FEATURE_COMINTEROP || FEATURE_COMWRAPPERS
OBJECTHANDLE CreateVariableHandle(OBJECTREF object, UINT type)
{
WRAPPER_NO_CONTRACT;
return ::CreateVariableHandle(m_handleStore, object, type);
}
OBJECTHANDLE CreateDependentHandle(OBJECTREF primary, OBJECTREF secondary)
{
WRAPPER_NO_CONTRACT;
return ::CreateDependentHandle(m_handleStore, primary, secondary);
}
#endif // DACCESS_COMPILE
DefaultAssemblyBinder *GetTPABinderContext() {LIMITED_METHOD_CONTRACT; return m_pTPABinderContext; }
CrstExplicitInit * GetLoaderAllocatorReferencesLock()
{
LIMITED_METHOD_CONTRACT;
return &m_crstLoaderAllocatorReferences;
}
protected:
//****************************************************************************************
// Helper method to initialize the large heap handle table.
void InitPinnedHeapHandleTable();
// Critical sections & locks
PEFileListLock m_FileLoadLock; // Protects the list of assemblies in the domain
CrstExplicitInit m_DomainCrst; // General Protection for the Domain
CrstExplicitInit m_DomainCacheCrst; // Protects the Assembly and Unmanaged caches
CrstExplicitInit m_DomainLocalBlockCrst;
// Used to protect the reference lists in the collectible loader allocators attached to this appdomain
CrstExplicitInit m_crstLoaderAllocatorReferences;
//#AssemblyListLock
// Used to protect the assembly list. Taken also by GC or debugger thread, therefore we have to avoid
// triggering GC while holding this lock (by switching the thread to GC_NOTRIGGER while it is held).
CrstExplicitInit m_crstAssemblyList;
ListLock m_ClassInitLock;
JitListLock m_JITLock;
ListLock m_ILStubGenLock;
ListLock m_NativeTypeLoadLock;
DefaultAssemblyBinder *m_pTPABinderContext; // Reference to the binding context that holds TPA list details
IGCHandleStore* m_handleStore;
// The pinned heap handle table.
PinnedHeapHandleTable *m_pPinnedHeapHandleTable;
// The pinned heap handle table critical section.
CrstExplicitInit m_PinnedHeapHandleTableCrst;
#ifdef FEATURE_COMINTEROP
// Information regarding the managed standard interfaces.
MngStdInterfacesInfo *m_pMngStdInterfacesInfo;
#endif // FEATURE_COMINTEROP
// Protects allocation of slot IDs for thread statics
static CrstStatic m_SpecialStaticsCrst;
public:
// Only call this routine when you can guarantee there are no
// loads in progress.
void ClearBinderContext();
//****************************************************************************************
// Synchronization holders.
class LockHolder : public CrstHolder
{
public:
LockHolder(BaseDomain *pD)
: CrstHolder(&pD->m_DomainCrst)
{
WRAPPER_NO_CONTRACT;
}
};
friend class LockHolder;
// To be used when the thread will remain in preemptive GC mode while holding the lock
class DomainCacheCrstHolderForGCPreemp : private CrstHolder
{
public:
DomainCacheCrstHolderForGCPreemp(BaseDomain *pD)
: CrstHolder(&pD->m_DomainCacheCrst)
{
WRAPPER_NO_CONTRACT;
}
};
// To be used when the thread may enter cooperative GC mode while holding the lock. The thread enters a
// forbid-suspend-for-debugger region along with acquiring the lock, such that it would not suspend for the debugger while
// holding the lock, as that may otherwise cause a FuncEval to deadlock when trying to acquire the lock.
class DomainCacheCrstHolderForGCCoop : private CrstAndForbidSuspendForDebuggerHolder
{
public:
DomainCacheCrstHolderForGCCoop(BaseDomain *pD)
: CrstAndForbidSuspendForDebuggerHolder(&pD->m_DomainCacheCrst)
{
WRAPPER_NO_CONTRACT;
}
};
class DomainLocalBlockLockHolder : public CrstHolder
{
public:
DomainLocalBlockLockHolder(BaseDomain *pD)
: CrstHolder(&pD->m_DomainLocalBlockCrst)
{
WRAPPER_NO_CONTRACT;
}
};
friend class DomainLocalBlockLockHolder;
class LoadLockHolder : public PEFileListLockHolder
{
public:
LoadLockHolder(BaseDomain *pD, BOOL Take = TRUE)
: PEFileListLockHolder(&pD->m_FileLoadLock, Take)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
}
};
friend class LoadLockHolder;
public:
void InitVSD();
RangeList *GetCollectibleVSDRanges() { return &m_collVSDRanges; }
private:
TypeIDMap m_typeIDMap;
// Range list for collectible types. Maps VSD PCODEs back to the VirtualCallStubManager they belong to
LockedRangeList m_collVSDRanges;
public:
UINT32 GetTypeID(PTR_MethodTable pMT);
UINT32 LookupTypeID(PTR_MethodTable pMT);
PTR_MethodTable LookupType(UINT32 id);
#ifndef DACCESS_COMPILE
void RemoveTypesFromTypeIDMap(LoaderAllocator* pLoaderAllocator);
#endif // DACCESS_COMPILE
private:
// I have yet to figure out an efficent way to get the number of handles
// of a particular type that's currently used by the process without
// spending more time looking at the handle table code. We know that
// our only customer (asp.net) in Dev10 is not going to create many of
// these handles so I am taking a shortcut for now and keep the sizedref
// handle count on the AD itself.
DWORD m_dwSizedRefHandles;
static int m_iNumberOfProcessors;
public:
// Called by DestroySizedRefHandle
void DecNumSizedRefHandles()
{
WRAPPER_NO_CONTRACT;
LONG result;
result = InterlockedDecrement((LONG*)&m_dwSizedRefHandles);
_ASSERTE(result >= 0);
}
DWORD GetNumSizedRefHandles()
{
return m_dwSizedRefHandles;
}
#ifdef FEATURE_CODE_VERSIONING
private:
CodeVersionManager m_codeVersionManager;
public:
CodeVersionManager* GetCodeVersionManager() { return &m_codeVersionManager; }
#endif //FEATURE_CODE_VERSIONING
#ifdef DACCESS_COMPILE
public:
virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis);
#endif
}; // class BaseDomain
enum
{
ATTACH_ASSEMBLY_LOAD = 0x1,
ATTACH_MODULE_LOAD = 0x2,
ATTACH_CLASS_LOAD = 0x4,
ATTACH_ALL = 0x7
};
// This filters the output of IterateAssemblies. This ought to be declared more locally
// but it would result in really verbose callsites.
//
// Assemblies can be categorized by their load status (loaded, loading, or loaded just
// enough that they would be made available to profilers)
// Independently, they can also be categorized as execution or introspection.
//
// An assembly will be included in the results of IterateAssemblies only if
// the appropriate bit is set for *both* characterizations.
//
// The flags can be combined so if you want all loaded assemblies, you must specify:
//
/// kIncludeLoaded|kIncludeExecution
enum AssemblyIterationFlags
{
// load status flags
kIncludeLoaded = 0x00000001, // include assemblies that are already loaded
// (m_level >= code:FILE_LOAD_DELIVER_EVENTS)
kIncludeLoading = 0x00000002, // include assemblies that are still in the process of loading
// (all m_level values)
kIncludeAvailableToProfilers
= 0x00000020, // include assemblies available to profilers
// See comment at code:DomainFile::IsAvailableToProfilers
// Execution / introspection flags
kIncludeExecution = 0x00000004, // include assemblies that are loaded for execution only
kIncludeFailedToLoad = 0x00000010, // include assemblies that failed to load
// Collectible assemblies flags
kExcludeCollectible = 0x00000040, // Exclude all collectible assemblies
kIncludeCollected = 0x00000080,
// Include assemblies which were collected and cannot be referenced anymore. Such assemblies are not
// AddRef-ed. Any manipulation with them should be protected by code:GetAssemblyListLock.
// Should be used only by code:LoaderAllocator::GCLoaderAllocators.
}; // enum AssemblyIterationFlags
//---------------------------------------------------------------------------------------
//
// Base class for holder code:CollectibleAssemblyHolder (see code:HolderBase).
// Manages AddRef/Release for collectible assemblies. It is no-op for 'normal' non-collectible assemblies.
//
// Each type of type parameter needs 2 methods implemented:
// code:CollectibleAssemblyHolderBase::GetLoaderAllocator
// code:CollectibleAssemblyHolderBase::IsCollectible
//
template<typename _Type>
class CollectibleAssemblyHolderBase
{
protected:
_Type m_value;
public:
CollectibleAssemblyHolderBase(const _Type & value = NULL)
{
LIMITED_METHOD_CONTRACT;
m_value = value;
}
void DoAcquire()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// We don't need to keep the assembly alive in DAC - see code:#CAH_DAC
#ifndef DACCESS_COMPILE
if (this->IsCollectible(m_value))
{
LoaderAllocator * pLoaderAllocator = GetLoaderAllocator(m_value);
pLoaderAllocator->AddReference();
}
#endif //!DACCESS_COMPILE
}
void DoRelease()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
if (this->IsCollectible(m_value))
{
LoaderAllocator * pLoaderAllocator = GetLoaderAllocator(m_value);
pLoaderAllocator->Release();
}
#endif //!DACCESS_COMPILE
}
private:
LoaderAllocator * GetLoaderAllocator(DomainAssembly * pDomainAssembly)
{
WRAPPER_NO_CONTRACT;
return pDomainAssembly->GetLoaderAllocator();
}
BOOL IsCollectible(DomainAssembly * pDomainAssembly)
{
WRAPPER_NO_CONTRACT;
return pDomainAssembly->IsCollectible();
}
LoaderAllocator * GetLoaderAllocator(Assembly * pAssembly)
{
WRAPPER_NO_CONTRACT;
return pAssembly->GetLoaderAllocator();
}
BOOL IsCollectible(Assembly * pAssembly)
{
WRAPPER_NO_CONTRACT;
return pAssembly->IsCollectible();
}
}; // class CollectibleAssemblyHolderBase<>
//---------------------------------------------------------------------------------------
//
// Holder of assembly reference which keeps collectible assembly alive while the holder is valid.
//
// Collectible assembly can be collected at any point when GC happens. Almost instantly all native data
// structures of the assembly (e.g. code:DomainAssembly, code:Assembly) could be deallocated.
// Therefore any usage of (collectible) assembly data structures from native world, has to prevent the
// deallocation by increasing ref-count on the assembly / associated loader allocator.
//
// #CAH_DAC
// In DAC we don't AddRef/Release as the assembly doesn't have to be kept alive: The process is stopped when
// DAC is used and therefore the assembly cannot just disappear.
//
template<typename _Type>
class CollectibleAssemblyHolder : public BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >
{
public:
FORCEINLINE
CollectibleAssemblyHolder(const _Type & value = NULL, BOOL fTake = TRUE)
: BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >(value, fTake)
{
STATIC_CONTRACT_WRAPPER;
}
FORCEINLINE
CollectibleAssemblyHolder &
operator=(const _Type & value)
{
STATIC_CONTRACT_WRAPPER;
BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >::operator=(value);
return *this;
}
// Operator & is overloaded in parent, therefore we have to get to 'this' pointer explicitly.
FORCEINLINE
CollectibleAssemblyHolder<_Type> *
This()
{
LIMITED_METHOD_CONTRACT;
return this;
}
}; // class CollectibleAssemblyHolder<>
//---------------------------------------------------------------------------------------
//
// Stores binding information about failed assembly loads for DAC
//
struct FailedAssembly {
SString displayName;
SString location;
HRESULT error;
void Initialize(AssemblySpec *pSpec, Exception *ex)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
displayName.SetASCII(pSpec->GetName());
location.Set(pSpec->GetCodeBase());
error = ex->GetHR();
//
// Determine the binding context assembly would have been in.
// If the parent has been set, use its binding context.
// If the parent hasn't been set but the code base has, use LoadFrom.
// Otherwise, use the default.
//
}
};
class AppDomainIterator;
const DWORD DefaultADID = 1;
// An Appdomain is the managed equivalent of a process. It is an isolation unit (conceptually you don't
// have pointers directly from one appdomain to another, but rather go through remoting proxies). It is
// also a unit of unloading.
//
// Threads are always running in the context of a particular AppDomain. See
// file:threads.h#RuntimeThreadLocals for more details.
//
// see code:BaseDomain for much of the meat of a AppDomain (heaps locks, etc)
// * code:AppDomain.m_Assemblies - is a list of code:Assembly in the appdomain
//
class AppDomain : public BaseDomain
{
friend class SystemDomain;
friend class AppDomainNative;
friend class AssemblyNative;
friend class AssemblySpec;
friend class ClassLoader;
friend class ThreadNative;
friend class ClrDataAccess;
friend class CheckAsmOffsets;
VPTR_VTABLE_CLASS(AppDomain, BaseDomain)
public:
#ifndef DACCESS_COMPILE
AppDomain();
virtual ~AppDomain();
static void Create();
#endif
//-----------------------------------------------------------------------------------------------------------------
// Convenience wrapper for ::GetAppDomain to provide better encapsulation.
static PTR_AppDomain GetCurrentDomain()
{ return m_pTheAppDomain; }
//-----------------------------------------------------------------------------------------------------------------
// Initializes an AppDomain. (this functions is not called from the SystemDomain)
void Init();
bool MustForceTrivialWaitOperations();
void SetForceTrivialWaitOperations();
//****************************************************************************************
//
// Stop deletes all the assemblies but does not remove other resources like
// the critical sections
void Stop();
// final assembly cleanup
void ShutdownFreeLoaderAllocators();
virtual BOOL IsAppDomain() { LIMITED_METHOD_DAC_CONTRACT; return TRUE; }
virtual PTR_AppDomain AsAppDomain() { LIMITED_METHOD_CONTRACT; return dac_cast<PTR_AppDomain>(this); }
OBJECTREF GetRawExposedObject() { LIMITED_METHOD_CONTRACT; return NULL; }
OBJECTHANDLE GetRawExposedObjectHandleForDebugger() { LIMITED_METHOD_DAC_CONTRACT; return NULL; }
#ifndef DACCESS_COMPILE
PTR_NativeImage GetNativeImage(LPCUTF8 compositeFileName);
PTR_NativeImage SetNativeImage(LPCUTF8 compositeFileName, PTR_NativeImage pNativeImage);
#endif // DACCESS_COMPILE
//****************************************************************************************
protected:
// Multi-thread safe access to the list of assemblies
class DomainAssemblyList
{
private:
ArrayList m_array;
#ifdef _DEBUG
AppDomain * dbg_m_pAppDomain;
public:
void Debug_SetAppDomain(AppDomain * pAppDomain)
{
dbg_m_pAppDomain = pAppDomain;
}
#endif //_DEBUG
public:
bool IsEmpty()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
// This function can be reliably called without taking the lock, because the first assembly
// added to the arraylist is non-collectible, and the ArrayList itself allows lockless read access
return (m_array.GetCount() == 0);
}
void Clear(AppDomain * pAppDomain)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
m_array.Clear();
}
DWORD GetCount(AppDomain * pAppDomain)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
return GetCount_Unlocked();
}
DWORD GetCount_Unlocked()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
#ifndef DACCESS_COMPILE
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
#endif
// code:Append_Unlock guarantees that we do not have more than MAXDWORD items
return m_array.GetCount();
}
void Get(AppDomain * pAppDomain, DWORD index, CollectibleAssemblyHolder<DomainAssembly *> * pAssemblyHolder)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
Get_Unlocked(index, pAssemblyHolder);
}
void Get_Unlocked(DWORD index, CollectibleAssemblyHolder<DomainAssembly *> * pAssemblyHolder)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
*pAssemblyHolder = dac_cast<PTR_DomainAssembly>(m_array.Get(index));
}
// Doesn't lock the assembly list (caller has to hold the lock already).
// Doesn't AddRef the returned assembly (if collectible).
DomainAssembly * Get_UnlockedNoReference(DWORD index)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifndef DACCESS_COMPILE
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
#endif
return dac_cast<PTR_DomainAssembly>(m_array.Get(index));
}
#ifndef DACCESS_COMPILE
void Set(AppDomain * pAppDomain, DWORD index, DomainAssembly * pAssembly)
{
CONTRACTL {
NOTHROW;
WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain == pAppDomain);
CrstHolder ch(pAppDomain->GetAssemblyListLock());
return Set_Unlocked(index, pAssembly);
}
void Set_Unlocked(DWORD index, DomainAssembly * pAssembly)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
m_array.Set(index, pAssembly);
}
HRESULT Append_Unlocked(DomainAssembly * pAssembly)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
} CONTRACTL_END;
_ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
return m_array.Append(pAssembly);
}
#else //DACCESS_COMPILE
void
EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
m_array.EnumMemoryRegions(flags);
}
#endif // DACCESS_COMPILE
// Should be used only by code:AssemblyIterator::Create
ArrayList::Iterator GetArrayListIterator()
{
return m_array.Iterate();
}
}; // class DomainAssemblyList
// Conceptually a list of code:Assembly structures, protected by lock code:GetAssemblyListLock
DomainAssemblyList m_Assemblies;
public:
// Note that this lock switches thread into GC_NOTRIGGER region as GC can take it too.
CrstExplicitInit * GetAssemblyListLock()
{
LIMITED_METHOD_CONTRACT;
return &m_crstAssemblyList;
}
public:
class AssemblyIterator
{
// AppDomain context with the assembly list
AppDomain * m_pAppDomain;
ArrayList::Iterator m_Iterator;
AssemblyIterationFlags m_assemblyIterationFlags;
public:
BOOL Next(CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder);
// Note: Does not lock the assembly list, but AddRefs collectible assemblies.
BOOL Next_Unlocked(CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder);
private:
inline DWORD GetIndex()
{
LIMITED_METHOD_CONTRACT;
return m_Iterator.GetIndex();
}
private:
friend class AppDomain;
// Cannot have constructor so this iterator can be used inside a union
static AssemblyIterator Create(AppDomain * pAppDomain, AssemblyIterationFlags assemblyIterationFlags)
{
LIMITED_METHOD_CONTRACT;
AssemblyIterator i;
i.m_pAppDomain = pAppDomain;
i.m_Iterator = pAppDomain->m_Assemblies.GetArrayListIterator();
i.m_assemblyIterationFlags = assemblyIterationFlags;
return i;
}
}; // class AssemblyIterator
AssemblyIterator IterateAssembliesEx(AssemblyIterationFlags assemblyIterationFlags)
{
LIMITED_METHOD_CONTRACT;
return AssemblyIterator::Create(this, assemblyIterationFlags);
}
public:
class PathIterator
{
friend class AppDomain;
ArrayList::Iterator m_i;
public:
BOOL Next()
{
WRAPPER_NO_CONTRACT;
return m_i.Next();
}
SString* GetPath()
{
WRAPPER_NO_CONTRACT;
return dac_cast<PTR_SString>(m_i.GetElement());
}
};
PathIterator IterateNativeDllSearchDirectories();
void SetNativeDllSearchDirectories(LPCWSTR paths);
BOOL HasNativeDllSearchDirectories();
public:
SIZE_T GetAssemblyCount()
{
WRAPPER_NO_CONTRACT;
return m_Assemblies.GetCount(this);
}
CHECK CheckCanLoadTypes(Assembly *pAssembly);
CHECK CheckCanExecuteManagedCode(MethodDesc* pMD);
CHECK CheckLoading(DomainFile *pFile, FileLoadLevel level);
FileLoadLevel GetDomainFileLoadLevel(DomainFile *pFile);
BOOL IsLoading(DomainFile *pFile, FileLoadLevel level);
static FileLoadLevel GetThreadFileLoadLevel();
void LoadDomainFile(DomainFile *pFile,
FileLoadLevel targetLevel);
enum FindAssemblyOptions
{
FindAssemblyOptions_None = 0x0,
FindAssemblyOptions_IncludeFailedToLoad = 0x1
};
DomainAssembly * FindAssembly(PEAssembly * pFile, FindAssemblyOptions options = FindAssemblyOptions_None) DAC_EMPTY_RET(NULL);
Assembly *LoadAssembly(AssemblySpec* pIdentity,
PEAssembly *pFile,
FileLoadLevel targetLevel);
// this function does not provide caching, you must use LoadDomainAssembly
// unless the call is guaranteed to succeed or you don't need the caching
// (e.g. if you will FailFast or tear down the AppDomain anyway)
// The main point that you should not bypass caching if you might try to load the same file again,
// resulting in multiple DomainAssembly objects that share the same PEAssembly for ngen image
//which is violating our internal assumptions
DomainAssembly *LoadDomainAssemblyInternal( AssemblySpec* pIdentity,
PEAssembly *pFile,
FileLoadLevel targetLevel);
DomainAssembly *LoadDomainAssembly( AssemblySpec* pIdentity,
PEAssembly *pFile,
FileLoadLevel targetLevel);
CHECK CheckValidModule(Module *pModule);
// private:
void LoadSystemAssemblies();
DomainFile *LoadDomainFile(FileLoadLock *pLock,
FileLoadLevel targetLevel);
void TryIncrementalLoad(DomainFile *pFile, FileLoadLevel workLevel, FileLoadLockHolder &lockHolder);
#ifndef DACCESS_COMPILE // needs AssemblySpec
//****************************************************************************************
// Returns and Inserts assemblies into a lookup cache based on the binding information
// in the AssemblySpec. There can be many AssemblySpecs to a single assembly.
DomainAssembly* FindCachedAssembly(AssemblySpec* pSpec, BOOL fThrow=TRUE)
{
WRAPPER_NO_CONTRACT;
return m_AssemblyCache.LookupAssembly(pSpec, fThrow);
}
PEAssembly* FindCachedFile(AssemblySpec* pSpec, BOOL fThrow = TRUE);
BOOL IsCached(AssemblySpec *pSpec);
#endif // DACCESS_COMPILE
BOOL AddFileToCache(AssemblySpec* pSpec, PEAssembly *pFile, BOOL fAllowFailure = FALSE);
BOOL RemoveFileFromCache(PEAssembly *pFile);
BOOL AddAssemblyToCache(AssemblySpec* pSpec, DomainAssembly *pAssembly);
BOOL RemoveAssemblyFromCache(DomainAssembly* pAssembly);
BOOL AddExceptionToCache(AssemblySpec* pSpec, Exception *ex);
void AddUnmanagedImageToCache(LPCWSTR libraryName, NATIVE_LIBRARY_HANDLE hMod);
NATIVE_LIBRARY_HANDLE FindUnmanagedImageInCache(LPCWSTR libraryName);
//****************************************************************************************
//
// Adds or removes an assembly to the domain.
void AddAssembly(DomainAssembly * assem);
void RemoveAssembly(DomainAssembly * pAsm);
BOOL ContainsAssembly(Assembly * assem);
//****************************************************************************************
//
// Reference count. When an appdomain is first created the reference is bump
// to one when it is added to the list of domains (see SystemDomain). An explicit
// Removal from the list is necessary before it will be deleted.
ULONG AddRef(void);
ULONG Release(void) DAC_EMPTY_RET(0);
//****************************************************************************************
LPCWSTR GetFriendlyName(BOOL fDebuggerCares = TRUE);
LPCWSTR GetFriendlyNameForDebugger();
LPCWSTR GetFriendlyNameForLogging();
#ifdef DACCESS_COMPILE
PVOID GetFriendlyNameNoSet(bool* isUtf8);
#endif
void SetFriendlyName(LPCWSTR pwzFriendlyName, BOOL fDebuggerCares = TRUE);
//****************************************************************************************
// This can be used to override the binding behavior of the appdomain. It
// is overridden in the compilation domain. It is important that all
// static binding goes through this path.
virtual PEAssembly * BindAssemblySpec(
AssemblySpec *pSpec,
BOOL fThrowOnFileNotFound) DAC_EMPTY_RET(NULL);
//****************************************************************************************
//
//****************************************************************************************
//
// Uses the first assembly to add an application base to the Context. This is done
// in a lazy fashion so executables do not take the perf hit unless the load other
// assemblies
#ifndef DACCESS_COMPILE
static BOOL OnUnhandledException(OBJECTREF *pThrowable, BOOL isTerminating = TRUE);
#endif
// True iff a debugger is attached to the process (same as CORDebuggerAttached)
BOOL IsDebuggerAttached (void);
#ifdef DEBUGGING_SUPPORTED
// Notify debugger of all assemblies, modules, and possibly classes in this AppDomain
BOOL NotifyDebuggerLoad(int flags, BOOL attaching);
// Send unload notifications to the debugger for all assemblies, modules and classes in this AppDomain
void NotifyDebuggerUnload();
#endif // DEBUGGING_SUPPORTED
#ifndef DACCESS_COMPILE
OBJECTREF* AllocateStaticFieldObjRefPtrs(int nRequested, OBJECTREF** ppLazyAllocate = NULL)
{
WRAPPER_NO_CONTRACT;
return AllocateObjRefPtrsInLargeTable(nRequested, ppLazyAllocate);
}
#endif // DACCESS_COMPILE
void EnumStaticGCRefs(promote_func* fn, ScanContext* sc);
void SetupSharedStatics();
#ifdef FEATURE_COMINTEROP
public:
OBJECTREF GetMissingObject(); // DispatchInfo will call function to retrieve the Missing.Value object.
RCWCache *GetRCWCache()
{
WRAPPER_NO_CONTRACT;
if (m_pRCWCache)
return m_pRCWCache;
// By separating the cache creation from the common lookup, we
// can keep the (x86) EH prolog/epilog off the path.
return CreateRCWCache();
}
private:
RCWCache *CreateRCWCache();
public:
RCWCache *GetRCWCacheNoCreate()
{
LIMITED_METHOD_CONTRACT;
return m_pRCWCache;
}
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_COMWRAPPERS
public:
RCWRefCache *GetRCWRefCache();
#endif // FEATURE_COMWRAPPERS
TPIndex GetTPIndex()
{
LIMITED_METHOD_CONTRACT;
return m_tpIndex;
}
DefaultAssemblyBinder *CreateBinderContext();
void SetIgnoreUnhandledExceptions()
{
LIMITED_METHOD_CONTRACT;
m_dwFlags |= IGNORE_UNHANDLED_EXCEPTIONS;
}
BOOL IgnoreUnhandledExceptions()
{
LIMITED_METHOD_CONTRACT;
return (m_dwFlags & IGNORE_UNHANDLED_EXCEPTIONS);
}
static void ExceptionUnwind(Frame *pFrame);
#ifdef _DEBUG
BOOL IsHeldByIterator()
{
LIMITED_METHOD_CONTRACT;
return m_dwIterHolders>0;
}
void IteratorRelease()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dwIterHolders);
FastInterlockDecrement(&m_dwIterHolders);
}
void IteratorAcquire()
{
LIMITED_METHOD_CONTRACT;
FastInterlockIncrement(&m_dwIterHolders);
}
#endif
BOOL IsActive()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_Stage >= STAGE_ACTIVE;
}
BOOL IsValid()
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef DACCESS_COMPILE
// We want to see all appdomains in SOS, even the about to be destructed ones.
// There is no risk of races under DAC, so we will pretend to be unconditionally valid.
return TRUE;
#else
return m_Stage > STAGE_CREATING;
#endif
}
static void RaiseExitProcessEvent();
Assembly* RaiseResourceResolveEvent(DomainAssembly* pAssembly, LPCSTR szName);
DomainAssembly* RaiseTypeResolveEventThrowing(DomainAssembly* pAssembly, LPCSTR szName, ASSEMBLYREF *pResultingAssemblyRef);
Assembly* RaiseAssemblyResolveEvent(AssemblySpec *pSpec);
private:
CrstExplicitInit m_ReflectionCrst;
CrstExplicitInit m_RefClassFactCrst;
EEClassFactoryInfoHashTable *m_pRefClassFactHash; // Hash table that maps a class factory info to a COM comp.
#ifdef FEATURE_COMINTEROP
DispIDCache *m_pRefDispIDCache;
OBJECTHANDLE m_hndMissing; //Handle points to Missing.Value Object which is used for [Optional] arg scenario during IDispatch CCW Call
#endif // FEATURE_COMINTEROP
public:
CrstBase *GetRefClassFactCrst()
{
LIMITED_METHOD_CONTRACT;
return &m_RefClassFactCrst;
}
#ifndef DACCESS_COMPILE
EEClassFactoryInfoHashTable* GetClassFactHash()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
if (m_pRefClassFactHash != NULL) {
return m_pRefClassFactHash;
}
return SetupClassFactHash();
}
#endif // DACCESS_COMPILE
#ifdef FEATURE_COMINTEROP
DispIDCache* GetRefDispIDCache()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
if (m_pRefDispIDCache != NULL) {
return m_pRefDispIDCache;
}
return SetupRefDispIDCache();
}
#endif // FEATURE_COMINTEROP
PTR_LoaderHeap GetStubHeap();
PTR_LoaderHeap GetLowFrequencyHeap();
PTR_LoaderHeap GetHighFrequencyHeap();
private:
size_t EstimateSize();
EEClassFactoryInfoHashTable* SetupClassFactHash();
#ifdef FEATURE_COMINTEROP
DispIDCache* SetupRefDispIDCache();
#endif // FEATURE_COMINTEROP
private:
PEAssembly *TryResolveAssemblyUsingEvent(AssemblySpec *pSpec);
BOOL PostBindResolveAssembly(AssemblySpec *pPrePolicySpec,
AssemblySpec *pPostPolicySpec,
HRESULT hrBindResult,
AssemblySpec **ppFailedSpec);
#ifdef FEATURE_COMINTEROP
public:
void ReleaseRCWs(LPVOID pCtxCookie);
void DetachRCWs();
#endif // FEATURE_COMINTEROP
private:
void RaiseLoadingAssemblyEvent(DomainAssembly* pAssembly);
friend class DomainAssembly;
private:
BOOL RaiseUnhandledExceptionEvent(OBJECTREF *pThrowable, BOOL isTerminating);
enum Stage {
STAGE_CREATING,
STAGE_READYFORMANAGEDCODE,
STAGE_ACTIVE,
STAGE_OPEN,
// Don't delete the following *_DONOTUSE members and in case a new member needs to be added,
// add it at the end. The reason is that debugger stuff has its own copy of this enum and
// it can use the members that are marked as *_DONOTUSE here when debugging older version
// of the runtime.
STAGE_UNLOAD_REQUESTED_DONOTUSE,
STAGE_EXITING_DONOTUSE,
STAGE_EXITED_DONOTUSE,
STAGE_FINALIZING_DONOTUSE,
STAGE_FINALIZED_DONOTUSE,
STAGE_HANDLETABLE_NOACCESS_DONOTUSE,
STAGE_CLEARED_DONOTUSE,
STAGE_COLLECTED_DONOTUSE,
STAGE_CLOSED_DONOTUSE
};
void SetStage(Stage stage)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
STRESS_LOG1(LF_APPDOMAIN, LL_INFO100,"Updating AD stage, stage=%d\n",stage);
Stage lastStage=m_Stage;
while (lastStage !=stage)
lastStage = (Stage)FastInterlockCompareExchange((LONG*)&m_Stage,stage,lastStage);
};
// List of unloaded LoaderAllocators, protected by code:GetLoaderAllocatorReferencesLock (for now)
LoaderAllocator * m_pDelayedLoaderAllocatorUnloadList;
public:
// Register the loader allocator for deletion in code:ShutdownFreeLoaderAllocators.
void RegisterLoaderAllocatorForDeletion(LoaderAllocator * pLoaderAllocator);
public:
void SetGCRefPoint(int gccounter)
{
LIMITED_METHOD_CONTRACT;
GetLoaderAllocator()->SetGCRefPoint(gccounter);
}
int GetGCRefPoint()
{
LIMITED_METHOD_CONTRACT;
return GetLoaderAllocator()->GetGCRefPoint();
}
void AddMemoryPressure();
void RemoveMemoryPressure();
Assembly *GetRootAssembly()
{
LIMITED_METHOD_CONTRACT;
return m_pRootAssembly;
}
#ifndef DACCESS_COMPILE
void SetRootAssembly(Assembly *pAssembly)
{
LIMITED_METHOD_CONTRACT;
m_pRootAssembly = pAssembly;
}
#endif
private:
// The one and only AppDomain
SPTR_DECL(AppDomain, m_pTheAppDomain);
SString m_friendlyName;
PTR_Assembly m_pRootAssembly;
// General purpose flags.
DWORD m_dwFlags;
// When an application domain is created the ref count is artifically incremented
// by one. For it to hit zero an explicit close must have happened.
LONG m_cRef; // Ref count.
// Map of loaded composite native images indexed by base load addresses
CrstExplicitInit m_nativeImageLoadCrst;
MapSHash<LPCUTF8, PTR_NativeImage, NativeImageIndexTraits> m_nativeImageMap;
#ifdef FEATURE_COMINTEROP
// this cache stores the RCWs in this domain
RCWCache *m_pRCWCache;
#endif //FEATURE_COMINTEROP
#ifdef FEATURE_COMWRAPPERS
// this cache stores the RCW -> CCW references in this domain
RCWRefCache *m_pRCWRefCache;
#endif // FEATURE_COMWRAPPERS
// The thread-pool index of this app domain among existing app domains (starting from 1)
TPIndex m_tpIndex;
Volatile<Stage> m_Stage;
ArrayList m_failedAssemblies;
#ifdef _DEBUG
Volatile<LONG> m_dwIterHolders;
#endif
//
// DAC iterator for failed assembly loads
//
class FailedAssemblyIterator
{
ArrayList::Iterator m_i;
public:
BOOL Next()
{
WRAPPER_NO_CONTRACT;
return m_i.Next();
}
FailedAssembly *GetFailedAssembly()
{
WRAPPER_NO_CONTRACT;
return dac_cast<PTR_FailedAssembly>(m_i.GetElement());
}
SIZE_T GetIndex()
{
WRAPPER_NO_CONTRACT;
return m_i.GetIndex();
}
private:
friend class AppDomain;
// Cannot have constructor so this iterator can be used inside a union
static FailedAssemblyIterator Create(AppDomain *pDomain)
{
WRAPPER_NO_CONTRACT;
FailedAssemblyIterator i;
i.m_i = pDomain->m_failedAssemblies.Iterate();
return i;
}
};
friend class FailedAssemblyIterator;
FailedAssemblyIterator IterateFailedAssembliesEx()
{
WRAPPER_NO_CONTRACT;
return FailedAssemblyIterator::Create(this);
}
//---------------------------------------------------------
// Stub caches for Method stubs
//---------------------------------------------------------
public:
enum {
CONTEXT_INITIALIZED = 0x0001,
// unused = 0x0400,
IGNORE_UNHANDLED_EXCEPTIONS = 0x10000, // AppDomain was created using the APPDOMAIN_IGNORE_UNHANDLED_EXCEPTIONS flag
};
AssemblySpecBindingCache m_AssemblyCache;
size_t m_MemoryPressure;
ArrayList m_NativeDllSearchDirectories;
bool m_ForceTrivialWaitOperations;
private:
struct UnmanagedImageCacheEntry
{
LPCWSTR Name;
NATIVE_LIBRARY_HANDLE Handle;
};
class UnmanagedImageCacheTraits : public NoRemoveSHashTraits<DefaultSHashTraits<UnmanagedImageCacheEntry>>
{
public:
using key_t = LPCWSTR;
static const key_t GetKey(_In_ const element_t& e) { return e.Name; }
static count_t Hash(_In_ key_t key) { return HashString(key); }
static bool Equals(_In_ key_t lhs, _In_ key_t rhs) { return wcscmp(lhs, rhs) == 0; }
static bool IsNull(_In_ const element_t& e) { return e.Handle == NULL; }
static const element_t Null() { return UnmanagedImageCacheEntry(); }
};
SHash<UnmanagedImageCacheTraits> m_unmanagedCache;
#ifdef FEATURE_TYPEEQUIVALENCE
private:
VolatilePtr<TypeEquivalenceHashTable> m_pTypeEquivalenceTable;
CrstExplicitInit m_TypeEquivalenceCrst;
public:
TypeEquivalenceHashTable * GetTypeEquivalenceCache();
#endif
private:
#ifdef DACCESS_COMPILE
public:
virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis);
#endif
#ifdef FEATURE_MULTICOREJIT
private:
MulticoreJitManager m_MulticoreJitManager;
public:
MulticoreJitManager & GetMulticoreJitManager()
{
LIMITED_METHOD_CONTRACT;
return m_MulticoreJitManager;
}
#endif
#if defined(FEATURE_TIERED_COMPILATION)
public:
TieredCompilationManager * GetTieredCompilationManager()
{
LIMITED_METHOD_CONTRACT;
return &m_tieredCompilationManager;
}
private:
TieredCompilationManager m_tieredCompilationManager;
#endif
private:
//-----------------------------------------------------------
// Static BINDER_SPACE::Assembly -> DomainAssembly mapping functions.
// This map does not maintain a reference count to either key or value.
// PEFile maintains a reference count on the BINDER_SPACE::Assembly through its code:PEFile::m_pHostAssembly field.
// It is removed from this hash table by code:DomainAssembly::~DomainAssembly.
struct HostAssemblyHashTraits : public DefaultSHashTraits<PTR_DomainAssembly>
{
public:
typedef PTR_BINDER_SPACE_Assembly key_t;
static key_t GetKey(element_t const & elem)
{
STATIC_CONTRACT_WRAPPER;
return elem->GetFile()->GetHostAssembly();
}
static BOOL Equals(key_t key1, key_t key2)
{
LIMITED_METHOD_CONTRACT;
return dac_cast<TADDR>(key1) == dac_cast<TADDR>(key2);
}
static count_t Hash(key_t key)
{
STATIC_CONTRACT_LIMITED_METHOD;
//return reinterpret_cast<count_t>(dac_cast<TADDR>(key));
return (count_t)(dac_cast<TADDR>(key));
}
static element_t Null() { return NULL; }
static element_t Deleted() { return (element_t)(TADDR)-1; }
static bool IsNull(const element_t & e) { return e == NULL; }
static bool IsDeleted(const element_t & e) { return dac_cast<TADDR>(e) == (TADDR)-1; }
};
struct OriginalFileHostAssemblyHashTraits : public HostAssemblyHashTraits
{
public:
static key_t GetKey(element_t const & elem)
{
STATIC_CONTRACT_WRAPPER;
return elem->GetOriginalFile()->GetHostAssembly();
}
};
typedef SHash<HostAssemblyHashTraits> HostAssemblyMap;
typedef SHash<OriginalFileHostAssemblyHashTraits> OriginalFileHostAssemblyMap;
HostAssemblyMap m_hostAssemblyMap;
OriginalFileHostAssemblyMap m_hostAssemblyMapForOrigFile;
CrstExplicitInit m_crstHostAssemblyMap;
// Lock to serialize all Add operations (in addition to the "read-lock" above)
CrstExplicitInit m_crstHostAssemblyMapAdd;
public:
// Returns DomainAssembly.
PTR_DomainAssembly FindAssembly(PTR_BINDER_SPACE_Assembly pHostAssembly);
#ifndef DACCESS_COMPILE
private:
friend void DomainAssembly::Allocate();
friend DomainAssembly::~DomainAssembly();
// Called from DomainAssembly::Begin.
void PublishHostedAssembly(
DomainAssembly* pAssembly);
// Called from DomainAssembly::UpdatePEFile.
void UpdatePublishHostedAssembly(
DomainAssembly* pAssembly,
PTR_PEFile pFile);
// Called from DomainAssembly::~DomainAssembly
void UnPublishHostedAssembly(
DomainAssembly* pAssembly);
#endif // DACCESS_COMPILE
}; // class AppDomain
// Just a ref holder
typedef ReleaseHolder<AppDomain> AppDomainRefHolder;
typedef VPTR(class SystemDomain) PTR_SystemDomain;
class SystemDomain : public BaseDomain
{
friend class AppDomainNative;
friend class AppDomainIterator;
friend class UnsafeAppDomainIterator;
friend class ClrDataAccess;
VPTR_VTABLE_CLASS(SystemDomain, BaseDomain)
VPTR_UNIQUE(VPTR_UNIQUE_SystemDomain)
public:
static PTR_LoaderAllocator GetGlobalLoaderAllocator();
//****************************************************************************************
//
// To be run during the initial start up of the EE. This must be
// performed prior to any class operations.
static void Attach();
//****************************************************************************************
//
// To be run during shutdown. This must be done after all operations
// that require the use of system classes (i.e., exceptions).
// DetachBegin stops all domains, while DetachEnd deallocates domain resources.
static void DetachBegin();
//****************************************************************************************
//
// To be run during shutdown. This must be done after all operations
// that require the use of system classes (i.e., exceptions).
// DetachBegin stops release resources held by systemdomain and the default domain.
static void DetachEnd();
//****************************************************************************************
//
// Initializes and shutdowns the single instance of the SystemDomain
// in the EE
#ifndef DACCESS_COMPILE
void *operator new(size_t size, void *pInPlace);
void operator delete(void *pMem);
#endif
void Init();
void Stop();
static void LazyInitGlobalStringLiteralMap();
//****************************************************************************************
//
// Load the base system classes, these classes are required before
// any other classes are loaded
void LoadBaseSystemClasses();
AppDomain* DefaultDomain()
{
LIMITED_METHOD_DAC_CONTRACT;
return AppDomain::GetCurrentDomain();
}
//****************************************************************************************
//
// Global Static to get the one and only system domain
static SystemDomain * System()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pSystemDomain;
}
static PEAssembly* SystemFile()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_pSystemDomain);
return System()->m_pSystemFile;
}
static Assembly* SystemAssembly()
{
WRAPPER_NO_CONTRACT;
return System()->m_pSystemAssembly;
}
static Module* SystemModule()
{
WRAPPER_NO_CONTRACT;
return SystemAssembly()->GetManifestModule();
}
static BOOL IsSystemLoaded()
{
WRAPPER_NO_CONTRACT;
return System()->m_pSystemAssembly != NULL;
}
#ifndef DACCESS_COMPILE
static GlobalStringLiteralMap *GetGlobalStringLiteralMap()
{
WRAPPER_NO_CONTRACT;
if (m_pGlobalStringLiteralMap == NULL)
{
SystemDomain::LazyInitGlobalStringLiteralMap();
}
_ASSERTE(m_pGlobalStringLiteralMap);
return m_pGlobalStringLiteralMap;
}
static GlobalStringLiteralMap *GetGlobalStringLiteralMapNoCreate()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_pGlobalStringLiteralMap);
return m_pGlobalStringLiteralMap;
}
#endif // DACCESS_COMPILE
#if defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT)
static Thread::ApartmentState GetEntryPointThreadAptState(IMDInternalImport* pScope, mdMethodDef mdMethod);
static void SetThreadAptState(Thread::ApartmentState state);
#endif
//****************************************************************************************
// Methods used to get the callers module and hence assembly and app domain.
static MethodDesc* GetCallersMethod(StackCrawlMark* stackMark);
static MethodTable* GetCallersType(StackCrawlMark* stackMark);
static Module* GetCallersModule(StackCrawlMark* stackMark);
static Assembly* GetCallersAssembly(StackCrawlMark* stackMark);
static bool IsReflectionInvocationMethod(MethodDesc* pMeth);
#ifndef DACCESS_COMPILE
//****************************************************************************************
// Returns the domain associated with the current context. (this can only be a child domain)
static inline AppDomain * GetCurrentDomain()
{
WRAPPER_NO_CONTRACT;
return ::GetAppDomain();
}
#endif //!DACCESS_COMPILE
#ifdef DEBUGGING_SUPPORTED
//****************************************************************************************
// Debugger/Publisher helper function to indicate creation of new app domain to debugger
// and publishing it in the IPC block
static void PublishAppDomainAndInformDebugger (AppDomain *pDomain);
#endif // DEBUGGING_SUPPORTED
#ifdef PROFILING_SUPPORTED
//****************************************************************************************
// Tell profiler about system created domains which are created before the profiler is
// actually activated.
static void NotifyProfilerStartup();
//****************************************************************************************
// Tell profiler at shutdown that system created domains are going away. They are not
// torn down using the normal sequence.
static HRESULT NotifyProfilerShutdown();
#endif // PROFILING_SUPPORTED
#ifndef DACCESS_COMPILE
DWORD RequireAppDomainCleanup()
{
LIMITED_METHOD_CONTRACT;
return m_pDelayedUnloadListOfLoaderAllocators != 0;
}
void AddToDelayedUnloadList(LoaderAllocator * pAllocator)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
CrstHolder lh(&m_DelayedUnloadCrst);
pAllocator->m_pLoaderAllocatorDestroyNext=m_pDelayedUnloadListOfLoaderAllocators;
m_pDelayedUnloadListOfLoaderAllocators=pAllocator;
int iGCRefPoint=GCHeapUtilities::GetGCHeap()->CollectionCount(GCHeapUtilities::GetGCHeap()->GetMaxGeneration());
if (GCHeapUtilities::IsGCInProgress())
iGCRefPoint++;
pAllocator->SetGCRefPoint(iGCRefPoint);
}
void ProcessDelayedUnloadLoaderAllocators();
static void EnumAllStaticGCRefs(promote_func* fn, ScanContext* sc);
#endif // DACCESS_COMPILE
//****************************************************************************************
LPCWSTR BaseLibrary()
{
WRAPPER_NO_CONTRACT;
return m_BaseLibrary;
}
#ifndef DACCESS_COMPILE
BOOL IsBaseLibrary(SString &path)
{
WRAPPER_NO_CONTRACT;
// See if it is the installation path to CoreLib
if (path.EqualsCaseInsensitive(m_BaseLibrary))
return TRUE;
// Or, it might be the location of CoreLib
if (System()->SystemAssembly() != NULL
&& path.EqualsCaseInsensitive(System()->SystemAssembly()->GetManifestFile()->GetPath()))
return TRUE;
return FALSE;
}
BOOL IsBaseLibrarySatellite(SString &path)
{
WRAPPER_NO_CONTRACT;
// See if it is the installation path to corelib.resources
SString s(SString::Ascii,g_psBaseLibrarySatelliteAssemblyName);
if (path.EqualsCaseInsensitive(s))
return TRUE;
return FALSE;
}
#endif // DACCESS_COMPILE
// Return the system directory
LPCWSTR SystemDirectory()
{
WRAPPER_NO_CONTRACT;
return m_SystemDirectory;
}
private:
void CreatePreallocatedExceptions();
void PreallocateSpecialObjects();
//****************************************************************************************
//
static StackWalkAction CallersMethodCallback(CrawlFrame* pCrawlFrame, VOID* pClientData);
static StackWalkAction CallersMethodCallbackWithStackMark(CrawlFrame* pCrawlFrame, VOID* pClientData);
#ifndef DACCESS_COMPILE
// This class is not to be created through normal allocation.
SystemDomain()
{
STANDARD_VM_CONTRACT;
m_pDelayedUnloadListOfLoaderAllocators=NULL;
m_GlobalAllocator.Init(this);
}
#endif
PTR_PEAssembly m_pSystemFile; // Single assembly (here for quicker reference);
PTR_Assembly m_pSystemAssembly; // Single assembly (here for quicker reference);
GlobalLoaderAllocator m_GlobalAllocator;
InlineSString<100> m_BaseLibrary;
InlineSString<100> m_SystemDirectory;
// <TODO>@TODO: CTS, we can keep the com modules in a single assembly or in different assemblies.
// We are currently using different assemblies but this is potentitially to slow...</TODO>
// Global domain that every one uses
SPTR_DECL(SystemDomain, m_pSystemDomain);
LoaderAllocator * m_pDelayedUnloadListOfLoaderAllocators;
#ifndef DACCESS_COMPILE
static CrstStatic m_DelayedUnloadCrst;
static CrstStatic m_SystemDomainCrst;
static GlobalStringLiteralMap *m_pGlobalStringLiteralMap;
static DWORD m_dwLowestFreeIndex;
#endif // DACCESS_COMPILE
public:
//****************************************************************************************
//
#ifndef DACCESS_COMPILE
#ifdef _DEBUG
inline static BOOL IsUnderDomainLock() { LIMITED_METHOD_CONTRACT; return m_SystemDomainCrst.OwnedByCurrentThread();};
#endif
// This lock controls adding and removing domains from the system domain
class LockHolder : public CrstHolder
{
public:
LockHolder()
: CrstHolder(&m_SystemDomainCrst)
{
WRAPPER_NO_CONTRACT;
}
};
#endif // DACCESS_COMPILE
public:
DWORD GetTotalNumSizedRefHandles();
#ifdef DACCESS_COMPILE
public:
virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis);
#endif
}; // class SystemDomain
//
// an UnsafeAppDomainIterator is used to iterate over all existing domains
//
// The iteration is guaranteed to include all domains that exist at the
// start & end of the iteration. This iterator is considered unsafe because it does not
// reference count the various appdomains, and can only be used when the runtime is stopped,
// or external synchronization is used. (and therefore no other thread may cause the appdomain list to change.)
// In CoreCLR, this iterator doesn't use a list as there is at most 1 AppDomain, and instead will find the only AppDomain, or not.
//
class UnsafeAppDomainIterator
{
friend class SystemDomain;
public:
UnsafeAppDomainIterator(BOOL bOnlyActive)
{
m_bOnlyActive = bOnlyActive;
}
void Init()
{
LIMITED_METHOD_CONTRACT;
m_iterationCount = 0;
m_pCurrent = NULL;
}
BOOL Next()
{
WRAPPER_NO_CONTRACT;
if (m_iterationCount == 0)
{
m_iterationCount++;
m_pCurrent = AppDomain::GetCurrentDomain();
if (m_pCurrent != NULL &&
(m_bOnlyActive ?
m_pCurrent->IsActive() : m_pCurrent->IsValid()))
{
return TRUE;
}
}
m_pCurrent = NULL;
return FALSE;
}
AppDomain * GetDomain()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pCurrent;
}
private:
int m_iterationCount;
AppDomain * m_pCurrent;
BOOL m_bOnlyActive;
}; // class UnsafeAppDomainIterator
//
// an AppDomainIterator is used to iterate over all existing domains.
//
// The iteration is guaranteed to include all domains that exist at the
// start & end of the iteration. Any domains added or deleted during
// iteration may or may not be included. The iterator also guarantees
// that the current iterated appdomain (GetDomain()) will not be deleted.
//
class AppDomainIterator : public UnsafeAppDomainIterator
{
friend class SystemDomain;
public:
AppDomainIterator(BOOL bOnlyActive) : UnsafeAppDomainIterator(bOnlyActive)
{
WRAPPER_NO_CONTRACT;
Init();
}
~AppDomainIterator()
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
if (GetDomain() != NULL)
{
#ifdef _DEBUG
GetDomain()->IteratorRelease();
#endif
GetDomain()->Release();
}
#endif
}
BOOL Next()
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
if (GetDomain() != NULL)
{
#ifdef _DEBUG
GetDomain()->IteratorRelease();
#endif
GetDomain()->Release();
}
SystemDomain::LockHolder lh;
#endif
if (UnsafeAppDomainIterator::Next())
{
#ifndef DACCESS_COMPILE
GetDomain()->AddRef();
#ifdef _DEBUG
GetDomain()->IteratorAcquire();
#endif
#endif
return TRUE;
}
return FALSE;
}
}; // class AppDomainIterator
#include "comreflectioncache.inl"
#endif
|
/*
* Copyright 2016 by Philip N. Garner
*
* See the file COPYING for the licence associated with this software.
*
* Author(s):
* Phil Garner, October 2016
*/
#include <QApplication>
#include <QMainWindow>
#include <qwt_plot.h>
#include <qwt_plot_grid.h>
#include <qwt_plot_curve.h>
#include "lube/qwt.h"
namespace libube
{
// Statics so the QApplication call can pass references
static int sArgc = 0;
static char** sArgv = 0;
class MQwt : public qwt
{
public:
MQwt();
void exec() { mApp.exec(); };
void plot();
void curve(var iX, var iY, var iTitle);
void axes(var iXLabel, var iYLabel);
private:
QApplication mApp;
QMainWindow mMain;
QwtPlot *mPlot;
};
void factory(Module** oModule, var iArg)
{
*oModule = new MQwt;
}
}
using namespace libube;
MQwt::MQwt()
: mApp(sArgc, sArgv)
{
// 16:9
mMain.resize(800, 450);
}
void MQwt::curve(var iX, var iY, var iTitle)
{
QwtPlotCurve* curve = new QwtPlotCurve(iTitle.str());
curve->attach(mPlot);
curve->setRenderHint(QwtPlotItem::RenderAntialiased);
curve->setSamples(
iX.ptr<double>(), iY.ptr<double>(), std::min(iX.size(), iY.size())
);
}
void MQwt::axes(var iXLabel, var iYLabel)
{
mPlot->setAxisTitle(QwtPlot::xBottom, iXLabel.str());
mPlot->setAxisTitle(QwtPlot::yLeft, iYLabel.str());
}
void MQwt::plot()
{
mPlot = new QwtPlot(&mMain);
mPlot->setCanvasBackground(QColor("White"));
mPlot->setAutoReplot(true);
// Grid; optional but I like them
QwtPlotGrid *grid = new QwtPlotGrid;
grid->attach(mPlot);
grid->setMajorPen(Qt::black, 0, Qt::DotLine);
grid->setMinorPen(Qt::gray, 0, Qt::DotLine);
mMain.setCentralWidget(mPlot);
mMain.show();
}
|
/////////////////////////////////////////////////////////////////////////////
// Program: wxWidgets Widgets Sample
// Name: hyperlnk.cpp
// Purpose: Part of the widgets sample showing wxHyperlinkCtrl
// Author: Dimitri Schoolwerth, Vadim Zeitlin
// Created: 27 Sep 2003
// Copyright: (c) 2003 wxWindows team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_HYPERLINKCTRL
// for all others, include the necessary headers
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/log.h"
#include "wx/bitmap.h"
#include "wx/button.h"
#include "wx/checkbox.h"
#include "wx/radiobox.h"
#include "wx/statbox.h"
#include "wx/stattext.h"
#include "wx/textctrl.h"
#include "wx/sizer.h"
#endif
#include "wx/hyperlink.h"
#include "widgets.h"
#include "icons/hyperlnk.xpm"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// control ids
enum
{
HyperlinkPage_Reset = wxID_HIGHEST,
HyperlinkPage_SetLabel,
HyperlinkPage_SetURL,
HyperlinkPage_Ctrl
};
// alignment radiobox indices
enum
{
Align_Left,
Align_Centre,
Align_Right,
Align_Max
};
// ----------------------------------------------------------------------------
// CheckBoxWidgetsPage
// ----------------------------------------------------------------------------
class HyperlinkWidgetsPage : public WidgetsPage
{
public:
HyperlinkWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist);
virtual ~HyperlinkWidgetsPage() {}
virtual wxWindow *GetWidget() const wxOVERRIDE { return m_hyperlink; }
virtual void RecreateWidget() wxOVERRIDE { CreateHyperlink(); }
// lazy creation of the content
virtual void CreateContent() wxOVERRIDE;
protected:
// event handlers
void OnButtonSetLabel(wxCommandEvent& event);
void OnButtonSetURL(wxCommandEvent& event);
void OnButtonReset(wxCommandEvent& event);
void OnAlignment(wxCommandEvent& event);
void OnGeneric(wxCommandEvent& event);
// reset the control parameters
void Reset();
// (re)create the hyperctrl
void CreateHyperlink();
void CreateHyperlinkLong(long align);
// the controls
// ------------
// the checkbox itself and the sizer it is in
wxGenericHyperlinkCtrl *m_hyperlink;
wxGenericHyperlinkCtrl *m_hyperlinkLong;
wxTextCtrl *m_label;
wxTextCtrl *m_url;
wxStaticText *m_visit;
wxStaticText *m_fun;
// the text entries for command parameters
wxTextCtrl *m_textLabel;
wxRadioBox *m_radioAlignMode;
wxCheckBox *m_checkGeneric;
private:
wxDECLARE_EVENT_TABLE();
DECLARE_WIDGETS_PAGE(HyperlinkWidgetsPage)
};
// ----------------------------------------------------------------------------
// event tables
// ----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(HyperlinkWidgetsPage, WidgetsPage)
EVT_BUTTON(HyperlinkPage_Reset, HyperlinkWidgetsPage::OnButtonReset)
EVT_BUTTON(HyperlinkPage_SetLabel, HyperlinkWidgetsPage::OnButtonSetLabel)
EVT_BUTTON(HyperlinkPage_SetURL, HyperlinkWidgetsPage::OnButtonSetURL)
EVT_RADIOBOX(wxID_ANY, HyperlinkWidgetsPage::OnAlignment)
EVT_CHECKBOX(wxID_ANY, HyperlinkWidgetsPage::OnGeneric)
wxEND_EVENT_TABLE()
// ============================================================================
// implementation
// ============================================================================
IMPLEMENT_WIDGETS_PAGE(HyperlinkWidgetsPage, "Hyperlink",
GENERIC_CTRLS
);
HyperlinkWidgetsPage::HyperlinkWidgetsPage(WidgetsBookCtrl *book,
wxImageList *imaglist)
:WidgetsPage(book, imaglist, hyperlnk_xpm)
{
}
void HyperlinkWidgetsPage::CreateContent()
{
wxSizer *sizerTop = new wxBoxSizer(wxHORIZONTAL);
// left pane
wxStaticBox *box = new wxStaticBox(this, wxID_ANY, "Hyperlink details");
wxSizer *sizerLeft = new wxStaticBoxSizer(box, wxVERTICAL);
sizerLeft->Add( CreateSizerWithTextAndButton( HyperlinkPage_SetLabel , "Set &Label", wxID_ANY, &m_label ),
0, wxALL | wxALIGN_RIGHT , 5 );
sizerLeft->Add( CreateSizerWithTextAndButton( HyperlinkPage_SetURL , "Set &URL", wxID_ANY, &m_url ),
0, wxALL | wxALIGN_RIGHT , 5 );
static const wxString alignments[] =
{
"&left",
"¢re",
"&right"
};
wxCOMPILE_TIME_ASSERT( WXSIZEOF(alignments) == Align_Max,
AlignMismatch );
m_radioAlignMode = new wxRadioBox(this, wxID_ANY, "alignment",
wxDefaultPosition, wxDefaultSize,
WXSIZEOF(alignments), alignments);
m_radioAlignMode->SetSelection(1); // start with "centre" selected since
// wxHL_DEFAULT_STYLE contains wxHL_ALIGN_CENTRE
sizerLeft->Add(m_radioAlignMode, 0, wxALL|wxGROW, 5);
m_checkGeneric = new wxCheckBox(this, wxID_ANY, "Use generic version",
wxDefaultPosition, wxDefaultSize);
sizerLeft->Add(m_checkGeneric, 0, wxALL|wxGROW, 5);
// right pane
wxSizer *szHyperlinkLong = new wxBoxSizer(wxVERTICAL);
wxSizer *szHyperlink = new wxBoxSizer(wxHORIZONTAL);
m_visit = new wxStaticText(this, wxID_ANY, "Visit ");
if (m_checkGeneric->IsChecked())
{
m_hyperlink = new wxGenericHyperlinkCtrl(this,
HyperlinkPage_Ctrl,
"wxWidgets website",
"www.wxwidgets.org");
}
else
{
m_hyperlink = new wxHyperlinkCtrl(this,
HyperlinkPage_Ctrl,
"wxWidgets website",
"www.wxwidgets.org");
}
m_fun = new wxStaticText(this, wxID_ANY, " for fun!");
szHyperlink->Add(0, 0, 1, wxCENTRE);
szHyperlink->Add(m_visit, 0, wxCENTRE);
szHyperlink->Add(m_hyperlink, 0, wxCENTRE);
szHyperlink->Add(m_fun, 0, wxCENTRE);
szHyperlink->Add(0, 0, 1, wxCENTRE);
szHyperlink->SetMinSize(150, 0);
if (m_checkGeneric->IsChecked())
{
m_hyperlinkLong = new wxGenericHyperlinkCtrl(this,
wxID_ANY,
"This is a long hyperlink",
"www.wxwidgets.org");
}
else
{
m_hyperlinkLong = new wxHyperlinkCtrl(this,
wxID_ANY,
"This is a long hyperlink",
"www.wxwidgets.org");
}
szHyperlinkLong->Add(0, 0, 1, wxCENTRE);
szHyperlinkLong->Add(szHyperlink, 0, wxCENTRE|wxGROW);
szHyperlinkLong->Add(0, 0, 1, wxCENTRE);
szHyperlinkLong->Add(m_hyperlinkLong, 0, wxGROW);
szHyperlinkLong->Add(0, 0, 1, wxCENTRE);
// the 3 panes panes compose the window
sizerTop->Add(sizerLeft, 0, (wxALL & ~wxLEFT), 10);
sizerTop->Add(szHyperlinkLong, 1, wxGROW | (wxALL & ~wxRIGHT), 10);
// final initializations
Reset();
SetSizer(sizerTop);
}
void HyperlinkWidgetsPage::Reset()
{
m_label->SetValue(m_hyperlink->GetLabel());
m_url->SetValue(m_hyperlink->GetURL());
}
void HyperlinkWidgetsPage::CreateHyperlink()
{
const wxString label = m_hyperlink->GetLabel();
const wxString url = m_hyperlink->GetURL();
long style = GetAttrs().m_defaultFlags;
style |= wxHL_DEFAULT_STYLE & ~wxBORDER_MASK;
wxGenericHyperlinkCtrl *hyp;
if (m_checkGeneric->IsChecked())
{
hyp = new wxGenericHyperlinkCtrl(this,
HyperlinkPage_Ctrl,
label,
url,
wxDefaultPosition,
wxDefaultSize,
style);
}
else
{
hyp = new wxHyperlinkCtrl(this,
HyperlinkPage_Ctrl,
label,
url,
wxDefaultPosition,
wxDefaultSize,
style);
}
// update sizer's child window
GetSizer()->Replace(m_hyperlink, hyp, true);
// update our pointer
delete m_hyperlink;
m_hyperlink = hyp;
// relayout the sizer
GetSizer()->Layout();
}
void HyperlinkWidgetsPage::CreateHyperlinkLong(long align)
{
long style = GetAttrs().m_defaultFlags;
style |= align;
style |= wxHL_DEFAULT_STYLE & ~(wxHL_ALIGN_CENTRE | wxBORDER_MASK);
wxGenericHyperlinkCtrl *hyp;
if (m_checkGeneric->IsChecked())
{
hyp = new wxGenericHyperlinkCtrl(this,
wxID_ANY,
"This is a long hyperlink",
"www.wxwidgets.org",
wxDefaultPosition,
wxDefaultSize,
style);
}
else
{
hyp = new wxHyperlinkCtrl(this,
wxID_ANY,
"This is a long hyperlink",
"www.wxwidgets.org",
wxDefaultPosition,
wxDefaultSize,
style);
}
// update sizer's child window
GetSizer()->Replace(m_hyperlinkLong, hyp, true);
// update our pointer
delete m_hyperlinkLong;
m_hyperlinkLong = hyp;
// relayout the sizer
GetSizer()->Layout();
}
// ----------------------------------------------------------------------------
// event handlers
// ----------------------------------------------------------------------------
void HyperlinkWidgetsPage::OnButtonReset(wxCommandEvent& WXUNUSED(event))
{
Reset();
CreateHyperlink();
}
void HyperlinkWidgetsPage::OnButtonSetLabel(wxCommandEvent& WXUNUSED(event))
{
m_hyperlink->SetLabel(m_label->GetValue());
CreateHyperlink();
}
void HyperlinkWidgetsPage::OnButtonSetURL(wxCommandEvent& WXUNUSED(event))
{
m_hyperlink->SetURL(m_url->GetValue());
CreateHyperlink();
}
void HyperlinkWidgetsPage::OnAlignment(wxCommandEvent& WXUNUSED(event))
{
long addstyle;
switch ( m_radioAlignMode->GetSelection() )
{
default:
case Align_Max:
wxFAIL_MSG( "unknown alignment" );
wxFALLTHROUGH;
case Align_Left:
addstyle = wxHL_ALIGN_LEFT;
break;
case Align_Centre:
addstyle = wxHL_ALIGN_CENTRE;
break;
case Align_Right:
addstyle = wxHL_ALIGN_RIGHT;
break;
}
CreateHyperlinkLong(addstyle);
}
void HyperlinkWidgetsPage::OnGeneric(wxCommandEvent& event)
{
CreateHyperlink();
OnAlignment(event);
}
#endif // wxUSE_HYPERLINKCTRL
|
// generated from rosidl_generator_cpp/resource/idl.hpp.em
// generated code does not contain a copyright notice
#ifndef RCL_INTERFACES__MSG__SET_PARAMETERS_RESULT_HPP_
#define RCL_INTERFACES__MSG__SET_PARAMETERS_RESULT_HPP_
#include "rcl_interfaces/msg/set_parameters_result__struct.hpp"
#include "rcl_interfaces/msg/set_parameters_result__traits.hpp"
#endif // RCL_INTERFACES__MSG__SET_PARAMETERS_RESULT_HPP_
|
//
// main.cpp
// Exercise 2
//
// Created by Zhehao Li on 2020/2/28.
// Copyright © 2020 Zhehao Li. All rights reserved.
//
// Test Point class -- Pass argumeent by reference to Distance()
#include "Point.hpp"
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
// Create two double objects to for x- and y-coordinates
double x;
double y;
// Ask the user for x- and y-coordinates
cout << "Please enter the x- and y-coordinates:" << endl;
cin >> x >> y; // Pass the value of input stream to objects
// Create a Point object
Point pt; // Initialize with default constructor
pt.SetX(x); // Reset the value of x-coordinates
pt.SetY(y); // Reset the value of y-coordinates
// Create a string object
string str_pt;
str_pt = pt.ToString(); // Get the description of Point object pt
cout << str_pt << endl; // Print the descriotion of Point object pt
cout << "Point(" << pt.GetX() << "," << pt.GetY() << ")" << endl; // Print the coordinates of Point object pt
// Create a new Point object to test the distance function
Point pt2(3.0, 4.0); // Initialize with two values
// Test the distance function
cout << "The distance to Origin(0,0) is: " << pt.DistanceOrigin() << endl; // Print the distance to origin
cout << "The distance to " << pt2.ToString() << " is: " << pt.Distance(pt2) << endl; // Print the distance to (3, 4)
return 0;
}
// With Copy Constructor:
// 1. Default constructor called once;
// 2. Constructor with values called once
// 3. Copy constructor wasn't called;
// 4. Destructor called twice;
//
// Now the number of calls of Default constructor = Destructor
|
//
// Created by Mpho Mbotho on 2020-10-07.
//
#include "suil/base/datetime.hpp"
namespace suil {
Datetime::Datetime(time_t t)
: m_t(t)
{
gmtime_r(&m_t, &m_tm);
}
Datetime::Datetime()
: Datetime(time(nullptr))
{}
Datetime::Datetime(const char *fmt, const char *str)
{
const char *tmp = HTTP_FMT;
if (fmt) {
tmp = fmt;
}
strptime(str, tmp, &m_tm);
}
Datetime::Datetime(const char *http_time)
: Datetime(HTTP_FMT, http_time)
{}
const char* Datetime::str(char *out, size_t sz, const char *fmt) {
if (!out || !sz || !fmt) {
return nullptr;
}
(void) strftime(out, sz, fmt, &m_tm);
return out;
}
Datetime::operator time_t() {
if (m_t == 0) {
m_t = timegm(&m_tm);
}
return m_t;
}
}
|
#include "FEAdaptor.h"
#include "FEDataStructures.h"
#include <iostream>
#include <vtkCPDataDescription.h>
#include <vtkCPInputDataDescription.h>
#include <vtkCPProcessor.h>
#include <vtkCPPythonScriptPipeline.h>
#include <vtkCPPythonScriptV2Pipeline.h>
#include <vtkCellData.h>
#include <vtkCellType.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkUnstructuredGrid.h>
#include "vtkCPMappedVectorArrayTemplate.h"
#include <vtksys/SystemTools.hxx>
namespace
{
vtkCPProcessor* Processor = NULL;
vtkUnstructuredGrid* VTKGrid;
void BuildVTKGrid(Grid& grid)
{
// create the points information
vtkCPMappedVectorArrayTemplate<double>* pointArray =
vtkCPMappedVectorArrayTemplate<double>::New();
pointArray->SetVectorArray(
grid.GetPointsArray(), static_cast<vtkIdType>(grid.GetNumberOfPoints()));
vtkNew<vtkPoints> points;
points->SetData(pointArray);
pointArray->Delete();
VTKGrid->SetPoints(points);
// create the cells
size_t numCells = grid.GetNumberOfCells();
VTKGrid->Allocate(static_cast<vtkIdType>(numCells * 9));
for (size_t cell = 0; cell < numCells; cell++)
{
unsigned int* cellPoints = grid.GetCellPoints(cell);
vtkIdType tmp[8] = { cellPoints[0], cellPoints[1], cellPoints[2], cellPoints[3], cellPoints[4],
cellPoints[5], cellPoints[6], cellPoints[7] };
VTKGrid->InsertNextCell(VTK_HEXAHEDRON, 8, tmp);
}
}
void UpdateVTKAttributes(Grid& grid, Attributes& attributes, vtkCPInputDataDescription* idd)
{
if (idd->IsFieldNeeded("velocity", vtkDataObject::POINT))
{
if (VTKGrid->GetPointData()->GetNumberOfArrays() == 0)
{
// velocity array
vtkCPMappedVectorArrayTemplate<double>* velocity =
vtkCPMappedVectorArrayTemplate<double>::New();
velocity->SetName("velocity");
VTKGrid->GetPointData()->AddArray(velocity);
velocity->Delete();
}
vtkCPMappedVectorArrayTemplate<double>* velocity =
vtkCPMappedVectorArrayTemplate<double>::SafeDownCast(
VTKGrid->GetPointData()->GetArray("velocity"));
velocity->SetVectorArray(attributes.GetVelocityArray(), VTKGrid->GetNumberOfPoints());
}
if (idd->IsFieldNeeded("pressure", vtkDataObject::CELL))
{
if (VTKGrid->GetCellData()->GetNumberOfArrays() == 0)
{
// pressure array
vtkNew<vtkFloatArray> pressure;
pressure->SetName("pressure");
pressure->SetNumberOfComponents(1);
VTKGrid->GetCellData()->AddArray(pressure);
}
vtkFloatArray* pressure =
vtkFloatArray::SafeDownCast(VTKGrid->GetCellData()->GetArray("pressure"));
// The pressure array is a scalar array so we can reuse
// memory as long as we ordered the points properly.
float* pressureData = attributes.GetPressureArray();
pressure->SetArray(pressureData, static_cast<vtkIdType>(grid.GetNumberOfCells()), 1);
}
}
void BuildVTKDataStructures(Grid& grid, Attributes& attributes, vtkCPInputDataDescription* idd)
{
if (VTKGrid == NULL)
{
// The grid structure isn't changing so we only build it
// the first time it's needed. If we needed the memory
// we could delete it and rebuild as necessary.
VTKGrid = vtkUnstructuredGrid::New();
BuildVTKGrid(grid);
}
UpdateVTKAttributes(grid, attributes, idd);
}
}
namespace FEAdaptor
{
void Initialize(int numScripts, char* scripts[])
{
if (Processor == NULL)
{
Processor = vtkCPProcessor::New();
Processor->Initialize();
}
else
{
Processor->RemoveAllPipelines();
}
for (int i = 0; i < numScripts; i++)
{
std::string ext = vtksys::SystemTools::GetFilenameLastExtension(scripts[i]);
if (ext == ".zip")
{
vtkNew<vtkCPPythonScriptV2Pipeline> pipeline;
pipeline->Initialize(scripts[i]);
Processor->AddPipeline(pipeline);
}
else
{
vtkNew<vtkCPPythonScriptPipeline> pipeline;
pipeline->Initialize(scripts[i]);
Processor->AddPipeline(pipeline);
}
}
}
void Finalize()
{
if (Processor)
{
Processor->Delete();
Processor = NULL;
}
if (VTKGrid)
{
VTKGrid->Delete();
VTKGrid = NULL;
}
}
void CoProcess(
Grid& grid, Attributes& attributes, double time, unsigned int timeStep, bool lastTimeStep)
{
vtkNew<vtkCPDataDescription> dataDescription;
dataDescription->AddInput("input");
dataDescription->SetTimeData(time, timeStep);
if (lastTimeStep == true)
{
// assume that we want to all the pipelines to execute if it
// is the last time step.
dataDescription->ForceOutputOn();
}
if (Processor->RequestDataDescription(dataDescription) != 0)
{
vtkCPInputDataDescription* idd = dataDescription->GetInputDescriptionByName("input");
BuildVTKDataStructures(grid, attributes, idd);
idd->SetGrid(VTKGrid);
Processor->CoProcess(dataDescription);
}
}
} // end of Catalyst namespace
|
# ifndef GL_WINDOW_HANDLER
# define GL_WINDOW_HANDLER 1
# include <string.h>
# include <GL/glew.h>
# include <GLFW/glfw3.h>
# include <glm/glm.hpp>
using namespace glm ;
# include "logging_handler.cpp"
GLFWwindow * mainWindow ;
short int windowWidth ;
short int windowHeight ;
class windowHandler {
private:
GLFWmonitor * primaryMonitor ;
GLuint vertexArrayIDs ;
short int errorCode ;
loggingHandler * logger ;
public:
windowHandler ( const char * windowTitle , loggingHandler * logger = new loggingHandler ) {
this -> logger = logger ;
this -> logger -> logInfo ( "windowHandler : Initializing the main window and its handler" ) ;
if ( ! glfwInit ( ) ) {
this -> logger -> logInfo ( "windowHandler : Failed to initialize GLFW. Have to exit\n" ) ;
exit ( - 1 ) ;
}
this -> logger -> logInfo ( "windowHandler : Reading game window related settings from file" ) ;
char settingType [ 20 ] , settingValue [ 100 ] ;
int isFullscreen , windowSamples ;
FILE * settingsFile = fopen ( "config/settings.cf" , "r" ) ;
while ( ! feof ( settingsFile ) ) {
fscanf ( settingsFile , "%s : %s" , settingType , settingValue ) ;
if ( ! strcmp ( "WINDOW_TYPE" , settingType ) ) {
if ( ! strcmp ( "FULLSCREEN" , settingValue ) )
isFullscreen = 1 ;
else
isFullscreen = 0 ;
}
else if ( ! strcmp ( "WINDOW_WIDTH" , settingType ) ) {
windowWidth = atoi ( settingValue ) ;
}
else if ( ! strcmp ( "WINDOW_HEIGHT" , settingType ) ) {
windowHeight = atoi ( settingValue ) ;
}
else if ( ! strcmp ( "WINDOW_SAMPLES" , settingType ) ) {
windowSamples = atoi ( settingValue ) ;
}
}
fclose ( settingsFile ) ;
this -> logger -> logInfo ( "windowHandler : Setting number of samples to be used for multi-sampling and anti-aliasing" ) ;
glfwWindowHint ( GLFW_SAMPLES , windowSamples ) ;
this -> logger -> logInfo ( "windowHandler : Setting OpenGL version to be used to 3.3" ) ;
glfwWindowHint ( GLFW_CONTEXT_VERSION_MAJOR , 3 ) ;
glfwWindowHint ( GLFW_CONTEXT_VERSION_MINOR , 3 ) ;
this -> logger -> logInfo ( "windowHandler : Enabling forward compatibility ( Required for Macs apparently )" ) ;
glfwWindowHint ( GLFW_OPENGL_FORWARD_COMPAT , GL_TRUE ) ;
this -> logger -> logInfo ( "windowHandler : Setting OpenGL to use the core/main profile" ) ;
glfwWindowHint ( GLFW_OPENGL_PROFILE , GLFW_OPENGL_CORE_PROFILE ) ;
this -> logger -> logInfo ( "windowHandler : Retrieving the primary monitor to be used to show the window in" ) ;
this -> primaryMonitor = glfwGetPrimaryMonitor ( ) ;
if ( ( this -> primaryMonitor ) == NULL ) {
this -> logger -> logInfo ( "windowHandler : Could not retrieve which is the primary monitor. Have to exit\n" ) ;
exit ( - 1 ) ;
}
this -> logger -> logInfo ( "windowHandler : Retrieve the video mode the primary monitor is using" ) ;
const GLFWvidmode * videoMode = glfwGetVideoMode ( this -> primaryMonitor ) ;
if ( videoMode == NULL ) {
this -> logger -> logInfo ( "windowHandler : Could not retrieve the video mode of the primary monitor. Have to exit\n" ) ;
exit ( - 1 ) ;
}
this -> logger -> logInfo ( "windowHandler : Setting the gamma value for the primary monitor" ) ;
glfwSetGamma ( ( this -> primaryMonitor ) , 1.0 ) ;
this -> logger -> logInfo ( "windowHandler : Creating a window to use the primary monitor in it's currently set video mode resolution" ) ;
if ( isFullscreen ) {
mainWindow = glfwCreateWindow ( ( videoMode -> width ) , ( videoMode -> height ) , windowTitle , ( this -> primaryMonitor ) , NULL ) ;
windowWidth = ( videoMode -> width ) ;
windowHeight = ( videoMode -> height ) ;
}
else
mainWindow = glfwCreateWindow ( windowWidth , windowHeight , windowTitle , NULL , NULL ) ;
if ( mainWindow == NULL ) {
this -> logger -> logInfo ( "windowHandler : Could not create a window. Have to exit\n" ) ;
exit ( - 1 ) ;
}
this -> logger -> logInfo ( "windowHandler : Set the newly created window as the one to be used in context" ) ;
glfwMakeContextCurrent ( mainWindow ) ;
glfwSwapInterval ( 0 ) ;
this -> logger -> logInfo ( "windowHandler : Setting GLEW to use the experimental profile ( required )" ) ;
glewExperimental = true ;
this -> logger -> logInfo ( "windowHandler : Initializing GLEW" ) ;
if ( glewInit ( ) != GLEW_OK ) {
this -> logger -> logInfo ( "windowHandler : Could not initialize GLEW. Have to exit\n" ) ;
exit ( - 1 ) ;
}
this -> logger -> logInfo ( "windowHandler : Saving the primary monitor's current video mode's resolution" ) ;
glGenVertexArrays ( 1 , & ( this -> vertexArrayIDs ) ) ;
glBindVertexArray ( this -> vertexArrayIDs ) ;
this -> logger -> logInfo ( "windowHandler : Initialized the main window and its handler\n" ) ;
}
~windowHandler ( ) {
glDeleteVertexArrays ( 1 , & ( this -> vertexArrayIDs ) ) ;
glfwDestroyWindow ( mainWindow ) ;
glfwTerminate ( ) ;
}
void setClearScreenColor ( vec4 color ) {
glClearColor ( color . x , color . y , color . z , color . w ) ;
}
void clearScreen ( GLbitfield mask ) {
glClear ( mask ) ;
}
void enableMSAA ( ) {
glEnable ( GL_MULTISAMPLE ) ;
}
void enableDepthTest ( ) {
glEnable ( GL_DEPTH_TEST ) ;
glDepthFunc ( GL_LESS ) ;
}
void disableDepthTest ( ) {
glDisable ( GL_DEPTH_TEST ) ;
}
void enableFaceCulling ( ) {
glEnable ( GL_CULL_FACE ) ;
}
void disableFaceCulling ( ) {
glDisable ( GL_CULL_FACE ) ;
}
int getWindowWidth ( ) {
return windowWidth ;
}
int getWindowHeight ( ) {
return windowHeight ;
}
} ;
#endif
|
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2011. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINERS_MAP_HPP
#define BOOST_CONTAINERS_MAP_HPP
#if (defined _MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif
#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
#include <boost/container/container_fwd.hpp>
#include <utility>
#include <functional>
#include <memory>
#include <stdexcept>
#include <boost/container/detail/tree.hpp>
#include <boost/container/detail/value_init.hpp>
#include <boost/type_traits/has_trivial_destructor.hpp>
#include <boost/container/detail/mpl.hpp>
#include <boost/container/detail/utilities.hpp>
#include <boost/container/detail/pair.hpp>
#include <boost/container/detail/type_traits.hpp>
#include <boost/move/move.hpp>
#include <boost/static_assert.hpp>
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
namespace boost {
namespace container {
#else
namespace boost {
namespace container {
#endif
/// @cond
// Forward declarations of operators == and <, needed for friend declarations.
template <class Key, class T, class Pred, class A>
inline bool operator==(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y);
template <class Key, class T, class Pred, class A>
inline bool operator<(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y);
/// @endcond
//! A map is a kind of associative container that supports unique keys (contains at
//! most one of each key value) and provides for fast retrieval of values of another
//! type T based on the keys. The map class supports bidirectional iterators.
//!
//! A map satisfies all of the requirements of a container and of a reversible
//! container and of an associative container. For a
//! map<Key,T> the key_type is Key and the value_type is std::pair<const Key,T>.
//!
//! Pred is the ordering function for Keys (e.g. <i>std::less<Key></i>).
//!
//! A is the allocator to allocate the value_types
//! (e.g. <i>allocator< std::pair<const Key, T> > </i>).
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
template <class Key, class T, class Pred = std::less< std::pair< const Key, T> >, class A = std::allocator<T> >
#else
template <class Key, class T, class Pred, class A>
#endif
class map
{
/// @cond
private:
BOOST_COPYABLE_AND_MOVABLE(map)
typedef containers_detail::rbtree<Key,
std::pair<const Key, T>,
containers_detail::select1st< std::pair<const Key, T> >,
Pred,
A> tree_t;
tree_t m_tree; // red-black tree representing map
/// @endcond
public:
// typedefs:
typedef typename tree_t::key_type key_type;
typedef typename tree_t::value_type value_type;
typedef typename tree_t::pointer pointer;
typedef typename tree_t::const_pointer const_pointer;
typedef typename tree_t::reference reference;
typedef typename tree_t::const_reference const_reference;
typedef T mapped_type;
typedef Pred key_compare;
typedef typename tree_t::iterator iterator;
typedef typename tree_t::const_iterator const_iterator;
typedef typename tree_t::reverse_iterator reverse_iterator;
typedef typename tree_t::const_reverse_iterator const_reverse_iterator;
typedef typename tree_t::size_type size_type;
typedef typename tree_t::difference_type difference_type;
typedef typename tree_t::allocator_type allocator_type;
typedef typename tree_t::stored_allocator_type stored_allocator_type;
typedef std::pair<key_type, mapped_type> nonconst_value_type;
typedef containers_detail::pair
<key_type, mapped_type> nonconst_impl_value_type;
/// @cond
class value_compare_impl
: public Pred,
public std::binary_function<value_type, value_type, bool>
{
friend class map<Key,T,Pred,A>;
protected :
value_compare_impl(const Pred &c) : Pred(c) {}
public:
bool operator()(const value_type& x, const value_type& y) const {
return Pred::operator()(x.first, y.first);
}
};
/// @endcond
typedef value_compare_impl value_compare;
//! <b>Effects</b>: Constructs an empty map using the specified comparison object
//! and allocator.
//!
//! <b>Complexity</b>: Constant.
explicit map(const Pred& comp = Pred(),
const allocator_type& a = allocator_type())
: m_tree(comp, a)
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Constructs an empty map using the specified comparison object and
//! allocator, and inserts elements from the range [first ,last ).
//!
//! <b>Complexity</b>: Linear in N if the range [first ,last ) is already sorted using
//! comp and otherwise N logN, where N is last - first.
template <class InputIterator>
map(InputIterator first, InputIterator last, const Pred& comp = Pred(),
const allocator_type& a = allocator_type())
: m_tree(first, last, comp, a, true)
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Constructs an empty map using the specified comparison object and
//! allocator, and inserts elements from the ordered unique range [first ,last). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate and must be
//! unique values.
//!
//! <b>Complexity</b>: Linear in N.
template <class InputIterator>
map( ordered_unique_range_t, InputIterator first, InputIterator last
, const Pred& comp = Pred(), const allocator_type& a = allocator_type())
: m_tree(ordered_range, first, last, comp, a)
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Copy constructs a map.
//!
//! <b>Complexity</b>: Linear in x.size().
map(const map<Key,T,Pred,A>& x)
: m_tree(x.m_tree)
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Move constructs a map. Constructs *this using x's resources.
//!
//! <b>Complexity</b>: Construct.
//!
//! <b>Postcondition</b>: x is emptied.
map(BOOST_RV_REF(map) x)
: m_tree(boost::move(x.m_tree))
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Makes *this a copy of x.
//!
//! <b>Complexity</b>: Linear in x.size().
map& operator=(BOOST_COPY_ASSIGN_REF(map) x)
{ m_tree = x.m_tree; return *this; }
//! <b>Effects</b>: this->swap(x.get()).
//!
//! <b>Complexity</b>: Constant.
map& operator=(BOOST_RV_REF(map) x)
{ m_tree = boost::move(x.m_tree); return *this; }
//! <b>Effects</b>: Returns the comparison object out
//! of which a was constructed.
//!
//! <b>Complexity</b>: Constant.
key_compare key_comp() const
{ return m_tree.key_comp(); }
//! <b>Effects</b>: Returns an object of value_compare constructed out
//! of the comparison object.
//!
//! <b>Complexity</b>: Constant.
value_compare value_comp() const
{ return value_compare(m_tree.key_comp()); }
//! <b>Effects</b>: Returns a copy of the Allocator that
//! was passed to the object's constructor.
//!
//! <b>Complexity</b>: Constant.
allocator_type get_allocator() const
{ return m_tree.get_allocator(); }
const stored_allocator_type &get_stored_allocator() const
{ return m_tree.get_stored_allocator(); }
stored_allocator_type &get_stored_allocator()
{ return m_tree.get_stored_allocator(); }
//! <b>Effects</b>: Returns an iterator to the first element contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
iterator begin()
{ return m_tree.begin(); }
//! <b>Effects</b>: Returns a const_iterator to the first element contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator begin() const
{ return m_tree.begin(); }
//! <b>Effects</b>: Returns an iterator to the end of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
iterator end()
{ return m_tree.end(); }
//! <b>Effects</b>: Returns a const_iterator to the end of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator end() const
{ return m_tree.end(); }
//! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
reverse_iterator rbegin()
{ return m_tree.rbegin(); }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator rbegin() const
{ return m_tree.rbegin(); }
//! <b>Effects</b>: Returns a reverse_iterator pointing to the end
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
reverse_iterator rend()
{ return m_tree.rend(); }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator rend() const
{ return m_tree.rend(); }
//! <b>Effects</b>: Returns true if the container contains no elements.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
bool empty() const
{ return m_tree.empty(); }
//! <b>Effects</b>: Returns the number of the elements contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
size_type size() const
{ return m_tree.size(); }
//! <b>Effects</b>: Returns the largest possible size of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
size_type max_size() const
{ return m_tree.max_size(); }
//! Effects: If there is no key equivalent to x in the map, inserts
//! value_type(x, T()) into the map.
//!
//! Returns: A reference to the mapped_type corresponding to x in *this.
//!
//! Complexity: Logarithmic.
T& operator[](const key_type& k)
{
//we can optimize this
iterator i = lower_bound(k);
// i->first is greater than or equivalent to k.
if (i == end() || key_comp()(k, (*i).first)){
containers_detail::value_init<T> v;
value_type val(k, boost::move(v.m_t));
i = insert(i, boost::move(val));
}
return (*i).second;
}
//! Effects: If there is no key equivalent to x in the map, inserts
//! value_type(boost::move(x), T()) into the map (the key is move-constructed)
//!
//! Returns: A reference to the mapped_type corresponding to x in *this.
//!
//! Complexity: Logarithmic.
T& operator[](BOOST_RV_REF(key_type) mk)
{
key_type &k = mk;
//we can optimize this
iterator i = lower_bound(k);
// i->first is greater than or equivalent to k.
if (i == end() || key_comp()(k, (*i).first)){
value_type val(boost::move(k), boost::move(T()));
i = insert(i, boost::move(val));
}
return (*i).second;
}
//! Returns: A reference to the element whose key is equivalent to x.
//! Throws: An exception object of type out_of_range if no such element is present.
//! Complexity: logarithmic.
T& at(const key_type& k)
{
iterator i = this->find(k);
if(i == this->end()){
throw std::out_of_range("key not found");
}
return i->second;
}
//! Returns: A reference to the element whose key is equivalent to x.
//! Throws: An exception object of type out_of_range if no such element is present.
//! Complexity: logarithmic.
const T& at(const key_type& k) const
{
const_iterator i = this->find(k);
if(i == this->end()){
throw std::out_of_range("key not found");
}
return i->second;
}
//! <b>Effects</b>: Swaps the contents of *this and x.
//! If this->allocator_type() != x.allocator_type() allocators are also swapped.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
void swap(map& x)
{ m_tree.swap(x.m_tree); }
//! <b>Effects</b>: Inserts x if and only if there is no element in the container
//! with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic.
std::pair<iterator,bool> insert(const value_type& x)
{ return m_tree.insert_unique(x); }
//! <b>Effects</b>: Inserts a new value_type created from the pair if and only if
//! there is no element in the container with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic.
std::pair<iterator,bool> insert(const nonconst_value_type& x)
{ return m_tree.insert_unique(x); }
//! <b>Effects</b>: Inserts a new value_type move constructed from the pair if and
//! only if there is no element in the container with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic.
std::pair<iterator,bool> insert(BOOST_RV_REF(nonconst_value_type) x)
{ return m_tree.insert_unique(boost::move(x)); }
//! <b>Effects</b>: Inserts a new value_type move constructed from the pair if and
//! only if there is no element in the container with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic.
std::pair<iterator,bool> insert(BOOST_RV_REF(nonconst_impl_value_type) x)
{ return m_tree.insert_unique(boost::move(x)); }
//! <b>Effects</b>: Move constructs a new value from x if and only if there is
//! no element in the container with key equivalent to the key of x.
//!
//! <b>Returns</b>: The bool component of the returned pair is true if and only
//! if the insertion takes place, and the iterator component of the pair
//! points to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic.
std::pair<iterator,bool> insert(BOOST_RV_REF(value_type) x)
{ return m_tree.insert_unique(boost::move(x)); }
//! <b>Effects</b>: Inserts a copy of x in the container if and only if there is
//! no element in the container with key equivalent to the key of x.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
iterator insert(iterator position, const value_type& x)
{ return m_tree.insert_unique(position, x); }
//! <b>Effects</b>: Move constructs a new value from x if and only if there is
//! no element in the container with key equivalent to the key of x.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
iterator insert(iterator position, BOOST_RV_REF(nonconst_value_type) x)
{ return m_tree.insert_unique(position, boost::move(x)); }
//! <b>Effects</b>: Move constructs a new value from x if and only if there is
//! no element in the container with key equivalent to the key of x.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
iterator insert(iterator position, BOOST_RV_REF(nonconst_impl_value_type) x)
{ return m_tree.insert_unique(position, boost::move(x)); }
//! <b>Effects</b>: Inserts a copy of x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic.
iterator insert(iterator position, const nonconst_value_type& x)
{ return m_tree.insert_unique(position, x); }
//! <b>Effects</b>: Inserts an element move constructed from x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent to the key of x.
//!
//! <b>Complexity</b>: Logarithmic.
iterator insert(iterator position, BOOST_RV_REF(value_type) x)
{ return m_tree.insert_unique(position, boost::move(x)); }
//! <b>Requires</b>: first, last are not iterators into *this.
//!
//! <b>Effects</b>: inserts each element from the range [first,last) if and only
//! if there is no element with key equivalent to the key of that element.
//!
//! <b>Complexity</b>: At most N log(size()+N) (N is the distance from first to last)
template <class InputIterator>
void insert(InputIterator first, InputIterator last)
{ m_tree.insert_unique(first, last); }
#if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts an object of type T constructed with
//! std::forward<Args>(args)... in the container if and only if there is
//! no element in the container with an equivalent key.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
template <class... Args>
iterator emplace(Args&&... args)
{ return m_tree.emplace_unique(boost::forward<Args>(args)...); }
//! <b>Effects</b>: Inserts an object of type T constructed with
//! std::forward<Args>(args)... in the container if and only if there is
//! no element in the container with an equivalent key.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
template <class... Args>
iterator emplace_hint(const_iterator hint, Args&&... args)
{ return m_tree.emplace_hint_unique(hint, boost::forward<Args>(args)...); }
#else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING
iterator emplace()
{ return m_tree.emplace_unique(); }
iterator emplace_hint(const_iterator hint)
{ return m_tree.emplace_hint_unique(hint); }
#define BOOST_PP_LOCAL_MACRO(n) \
template<BOOST_PP_ENUM_PARAMS(n, class P)> \
iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \
{ return m_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \
\
template<BOOST_PP_ENUM_PARAMS(n, class P)> \
iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \
{ return m_tree.emplace_hint_unique(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _));}\
//!
#define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS)
#include BOOST_PP_LOCAL_ITERATE()
#endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING
//! <b>Effects</b>: Erases the element pointed to by position.
//!
//! <b>Returns</b>: Returns an iterator pointing to the element immediately
//! following q prior to the element being erased. If no such element exists,
//! returns end().
//!
//! <b>Complexity</b>: Amortized constant time
iterator erase(const_iterator position)
{ return m_tree.erase(position); }
//! <b>Effects</b>: Erases all elements in the container with key equivalent to x.
//!
//! <b>Returns</b>: Returns the number of erased elements.
//!
//! <b>Complexity</b>: log(size()) + count(k)
size_type erase(const key_type& x)
{ return m_tree.erase(x); }
//! <b>Effects</b>: Erases all the elements in the range [first, last).
//!
//! <b>Returns</b>: Returns last.
//!
//! <b>Complexity</b>: log(size())+N where N is the distance from first to last.
iterator erase(const_iterator first, const_iterator last)
{ return m_tree.erase(first, last); }
//! <b>Effects</b>: erase(a.begin(),a.end()).
//!
//! <b>Postcondition</b>: size() == 0.
//!
//! <b>Complexity</b>: linear in size().
void clear()
{ m_tree.clear(); }
//! <b>Returns</b>: An iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
iterator find(const key_type& x)
{ return m_tree.find(x); }
//! <b>Returns</b>: A const_iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
const_iterator find(const key_type& x) const
{ return m_tree.find(x); }
//! <b>Returns</b>: The number of elements with key equivalent to x.
//!
//! <b>Complexity</b>: log(size())+count(k)
size_type count(const key_type& x) const
{ return m_tree.find(x) == m_tree.end() ? 0 : 1; }
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
iterator lower_bound(const key_type& x)
{ return m_tree.lower_bound(x); }
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
const_iterator lower_bound(const key_type& x) const
{ return m_tree.lower_bound(x); }
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
iterator upper_bound(const key_type& x)
{ return m_tree.upper_bound(x); }
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
const_iterator upper_bound(const key_type& x) const
{ return m_tree.upper_bound(x); }
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
std::pair<iterator,iterator> equal_range(const key_type& x)
{ return m_tree.equal_range(x); }
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
std::pair<const_iterator,const_iterator> equal_range(const key_type& x) const
{ return m_tree.equal_range(x); }
/// @cond
template <class K1, class T1, class C1, class A1>
friend bool operator== (const map<K1, T1, C1, A1>&,
const map<K1, T1, C1, A1>&);
template <class K1, class T1, class C1, class A1>
friend bool operator< (const map<K1, T1, C1, A1>&,
const map<K1, T1, C1, A1>&);
/// @endcond
};
template <class Key, class T, class Pred, class A>
inline bool operator==(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y)
{ return x.m_tree == y.m_tree; }
template <class Key, class T, class Pred, class A>
inline bool operator<(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y)
{ return x.m_tree < y.m_tree; }
template <class Key, class T, class Pred, class A>
inline bool operator!=(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y)
{ return !(x == y); }
template <class Key, class T, class Pred, class A>
inline bool operator>(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y)
{ return y < x; }
template <class Key, class T, class Pred, class A>
inline bool operator<=(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y)
{ return !(y < x); }
template <class Key, class T, class Pred, class A>
inline bool operator>=(const map<Key,T,Pred,A>& x,
const map<Key,T,Pred,A>& y)
{ return !(x < y); }
template <class Key, class T, class Pred, class A>
inline void swap(map<Key,T,Pred,A>& x, map<Key,T,Pred,A>& y)
{ x.swap(y); }
/// @cond
// Forward declaration of operators < and ==, needed for friend declaration.
template <class Key, class T, class Pred, class A>
inline bool operator==(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y);
template <class Key, class T, class Pred, class A>
inline bool operator<(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y);
} //namespace container {
/*
//!has_trivial_destructor_after_move<> == true_type
//!specialization for optimizations
template <class K, class T, class C, class A>
struct has_trivial_destructor_after_move<boost::container::map<K, T, C, A> >
{
static const bool value = has_trivial_destructor<A>::value && has_trivial_destructor<C>::value;
};
*/
namespace container {
/// @endcond
//! A multimap is a kind of associative container that supports equivalent keys
//! (possibly containing multiple copies of the same key value) and provides for
//! fast retrieval of values of another type T based on the keys. The multimap class
//! supports bidirectional iterators.
//!
//! A multimap satisfies all of the requirements of a container and of a reversible
//! container and of an associative container. For a
//! map<Key,T> the key_type is Key and the value_type is std::pair<const Key,T>.
//!
//! Pred is the ordering function for Keys (e.g. <i>std::less<Key></i>).
//!
//! A is the allocator to allocate the value_types
//!(e.g. <i>allocator< std::pair<<b>const</b> Key, T> ></i>).
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
template <class Key, class T, class Pred = std::less< std::pair< const Key, T> >, class A = std::allocator<T> >
#else
template <class Key, class T, class Pred, class A>
#endif
class multimap
{
/// @cond
private:
BOOST_COPYABLE_AND_MOVABLE(multimap)
typedef containers_detail::rbtree<Key,
std::pair<const Key, T>,
containers_detail::select1st< std::pair<const Key, T> >,
Pred,
A> tree_t;
tree_t m_tree; // red-black tree representing map
/// @endcond
public:
// typedefs:
typedef typename tree_t::key_type key_type;
typedef typename tree_t::value_type value_type;
typedef typename tree_t::pointer pointer;
typedef typename tree_t::const_pointer const_pointer;
typedef typename tree_t::reference reference;
typedef typename tree_t::const_reference const_reference;
typedef T mapped_type;
typedef Pred key_compare;
typedef typename tree_t::iterator iterator;
typedef typename tree_t::const_iterator const_iterator;
typedef typename tree_t::reverse_iterator reverse_iterator;
typedef typename tree_t::const_reverse_iterator const_reverse_iterator;
typedef typename tree_t::size_type size_type;
typedef typename tree_t::difference_type difference_type;
typedef typename tree_t::allocator_type allocator_type;
typedef typename tree_t::stored_allocator_type stored_allocator_type;
typedef std::pair<key_type, mapped_type> nonconst_value_type;
typedef containers_detail::pair
<key_type, mapped_type> nonconst_impl_value_type;
/// @cond
class value_compare_impl
: public Pred,
public std::binary_function<value_type, value_type, bool>
{
friend class multimap<Key,T,Pred,A>;
protected :
value_compare_impl(const Pred &c) : Pred(c) {}
public:
bool operator()(const value_type& x, const value_type& y) const {
return Pred::operator()(x.first, y.first);
}
};
/// @endcond
typedef value_compare_impl value_compare;
//! <b>Effects</b>: Constructs an empty multimap using the specified comparison
//! object and allocator.
//!
//! <b>Complexity</b>: Constant.
explicit multimap(const Pred& comp = Pred(),
const allocator_type& a = allocator_type())
: m_tree(comp, a)
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Constructs an empty multimap using the specified comparison object
//! and allocator, and inserts elements from the range [first ,last ).
//!
//! <b>Complexity</b>: Linear in N if the range [first ,last ) is already sorted using
//! comp and otherwise N logN, where N is last - first.
template <class InputIterator>
multimap(InputIterator first, InputIterator last,
const Pred& comp = Pred(),
const allocator_type& a = allocator_type())
: m_tree(first, last, comp, a, false)
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Constructs an empty multimap using the specified comparison object and
//! allocator, and inserts elements from the ordered range [first ,last). This function
//! is more efficient than the normal range creation for ordered ranges.
//!
//! <b>Requires</b>: [first ,last) must be ordered according to the predicate.
//!
//! <b>Complexity</b>: Linear in N.
template <class InputIterator>
multimap(ordered_range_t ordered_range, InputIterator first, InputIterator last, const Pred& comp = Pred(),
const allocator_type& a = allocator_type())
: m_tree(ordered_range, first, last, comp, a)
{}
//! <b>Effects</b>: Copy constructs a multimap.
//!
//! <b>Complexity</b>: Linear in x.size().
multimap(const multimap<Key,T,Pred,A>& x)
: m_tree(x.m_tree)
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Move constructs a multimap. Constructs *this using x's resources.
//!
//! <b>Complexity</b>: Construct.
//!
//! <b>Postcondition</b>: x is emptied.
multimap(BOOST_RV_REF(multimap) x)
: m_tree(boost::move(x.m_tree))
{
//Allocator type must be std::pair<CONST Key, T>
BOOST_STATIC_ASSERT((containers_detail::is_same<std::pair<const Key, T>, typename A::value_type>::value));
}
//! <b>Effects</b>: Makes *this a copy of x.
//!
//! <b>Complexity</b>: Linear in x.size().
multimap& operator=(BOOST_COPY_ASSIGN_REF(multimap) x)
{ m_tree = x.m_tree; return *this; }
//! <b>Effects</b>: this->swap(x.get()).
//!
//! <b>Complexity</b>: Constant.
multimap& operator=(BOOST_RV_REF(multimap) x)
{ m_tree = boost::move(x.m_tree); return *this; }
//! <b>Effects</b>: Returns the comparison object out
//! of which a was constructed.
//!
//! <b>Complexity</b>: Constant.
key_compare key_comp() const
{ return m_tree.key_comp(); }
//! <b>Effects</b>: Returns an object of value_compare constructed out
//! of the comparison object.
//!
//! <b>Complexity</b>: Constant.
value_compare value_comp() const
{ return value_compare(m_tree.key_comp()); }
//! <b>Effects</b>: Returns a copy of the Allocator that
//! was passed to the object's constructor.
//!
//! <b>Complexity</b>: Constant.
allocator_type get_allocator() const
{ return m_tree.get_allocator(); }
const stored_allocator_type &get_stored_allocator() const
{ return m_tree.get_stored_allocator(); }
stored_allocator_type &get_stored_allocator()
{ return m_tree.get_stored_allocator(); }
//! <b>Effects</b>: Returns an iterator to the first element contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
iterator begin()
{ return m_tree.begin(); }
//! <b>Effects</b>: Returns a const_iterator to the first element contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator begin() const
{ return m_tree.begin(); }
//! <b>Effects</b>: Returns an iterator to the end of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
iterator end()
{ return m_tree.end(); }
//! <b>Effects</b>: Returns a const_iterator to the end of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_iterator end() const
{ return m_tree.end(); }
//! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
reverse_iterator rbegin()
{ return m_tree.rbegin(); }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator rbegin() const
{ return m_tree.rbegin(); }
//! <b>Effects</b>: Returns a reverse_iterator pointing to the end
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
reverse_iterator rend()
{ return m_tree.rend(); }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end
//! of the reversed container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
const_reverse_iterator rend() const
{ return m_tree.rend(); }
//! <b>Effects</b>: Returns true if the container contains no elements.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
bool empty() const
{ return m_tree.empty(); }
//! <b>Effects</b>: Returns the number of the elements contained in the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
size_type size() const
{ return m_tree.size(); }
//! <b>Effects</b>: Returns the largest possible size of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
size_type max_size() const
{ return m_tree.max_size(); }
//! <b>Effects</b>: Swaps the contents of *this and x.
//! If this->allocator_type() != x.allocator_type() allocators are also swapped.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
void swap(multimap& x)
{ m_tree.swap(x.m_tree); }
//! <b>Effects</b>: Inserts x and returns the iterator pointing to the
//! newly inserted element.
//!
//! <b>Complexity</b>: Logarithmic.
iterator insert(const value_type& x)
{ return m_tree.insert_equal(x); }
//! <b>Effects</b>: Inserts a new value constructed from x and returns
//! the iterator pointing to the newly inserted element.
//!
//! <b>Complexity</b>: Logarithmic.
iterator insert(const nonconst_value_type& x)
{ return m_tree.insert_equal(x); }
//! <b>Effects</b>: Inserts a new value move-constructed from x and returns
//! the iterator pointing to the newly inserted element.
//!
//! <b>Complexity</b>: Logarithmic.
iterator insert(BOOST_RV_REF(nonconst_value_type) x)
{ return m_tree.insert_equal(boost::move(x)); }
//! <b>Effects</b>: Inserts a new value move-constructed from x and returns
//! the iterator pointing to the newly inserted element.
//!
//! <b>Complexity</b>: Logarithmic.
iterator insert(BOOST_RV_REF(nonconst_impl_value_type) x)
{ return m_tree.insert_equal(boost::move(x)); }
//! <b>Effects</b>: Inserts a copy of x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
iterator insert(iterator position, const value_type& x)
{ return m_tree.insert_equal(position, x); }
//! <b>Effects</b>: Inserts a new value constructed from x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
iterator insert(iterator position, const nonconst_value_type& x)
{ return m_tree.insert_equal(position, x); }
//! <b>Effects</b>: Inserts a new value move constructed from x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
iterator insert(iterator position, BOOST_RV_REF(nonconst_value_type) x)
{ return m_tree.insert_equal(position, boost::move(x)); }
//! <b>Effects</b>: Inserts a new value move constructed from x in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
iterator insert(iterator position, BOOST_RV_REF(nonconst_impl_value_type) x)
{ return m_tree.insert_equal(position, boost::move(x)); }
//! <b>Requires</b>: first, last are not iterators into *this.
//!
//! <b>Effects</b>: inserts each element from the range [first,last) .
//!
//! <b>Complexity</b>: At most N log(size()+N) (N is the distance from first to last)
template <class InputIterator>
void insert(InputIterator first, InputIterator last)
{ m_tree.insert_equal(first, last); }
#if defined(BOOST_CONTAINERS_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts an object of type T constructed with
//! std::forward<Args>(args)... in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
template <class... Args>
iterator emplace(Args&&... args)
{ return m_tree.emplace_equal(boost::forward<Args>(args)...); }
//! <b>Effects</b>: Inserts an object of type T constructed with
//! std::forward<Args>(args)... in the container.
//! p is a hint pointing to where the insert should start to search.
//!
//! <b>Returns</b>: An iterator pointing to the element with key equivalent
//! to the key of x.
//!
//! <b>Complexity</b>: Logarithmic in general, but amortized constant if t
//! is inserted right before p.
template <class... Args>
iterator emplace_hint(const_iterator hint, Args&&... args)
{ return m_tree.emplace_hint_equal(hint, boost::forward<Args>(args)...); }
#else //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING
iterator emplace()
{ return m_tree.emplace_equal(); }
iterator emplace_hint(const_iterator hint)
{ return m_tree.emplace_hint_equal(hint); }
#define BOOST_PP_LOCAL_MACRO(n) \
template<BOOST_PP_ENUM_PARAMS(n, class P)> \
iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \
{ return m_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); } \
\
template<BOOST_PP_ENUM_PARAMS(n, class P)> \
iterator emplace_hint(const_iterator hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_LIST, _)) \
{ return m_tree.emplace_hint_equal(hint, BOOST_PP_ENUM(n, BOOST_CONTAINERS_PP_PARAM_FORWARD, _)); }\
//!
#define BOOST_PP_LOCAL_LIMITS (1, BOOST_CONTAINERS_MAX_CONSTRUCTOR_PARAMETERS)
#include BOOST_PP_LOCAL_ITERATE()
#endif //#ifdef BOOST_CONTAINERS_PERFECT_FORWARDING
//! <b>Effects</b>: Erases the element pointed to by position.
//!
//! <b>Returns</b>: Returns an iterator pointing to the element immediately
//! following q prior to the element being erased. If no such element exists,
//! returns end().
//!
//! <b>Complexity</b>: Amortized constant time
iterator erase(const_iterator position)
{ return m_tree.erase(position); }
//! <b>Effects</b>: Erases all elements in the container with key equivalent to x.
//!
//! <b>Returns</b>: Returns the number of erased elements.
//!
//! <b>Complexity</b>: log(size()) + count(k)
size_type erase(const key_type& x)
{ return m_tree.erase(x); }
//! <b>Effects</b>: Erases all the elements in the range [first, last).
//!
//! <b>Returns</b>: Returns last.
//!
//! <b>Complexity</b>: log(size())+N where N is the distance from first to last.
iterator erase(const_iterator first, const_iterator last)
{ return m_tree.erase(first, last); }
//! <b>Effects</b>: erase(a.begin(),a.end()).
//!
//! <b>Postcondition</b>: size() == 0.
//!
//! <b>Complexity</b>: linear in size().
void clear()
{ m_tree.clear(); }
//! <b>Returns</b>: An iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
iterator find(const key_type& x)
{ return m_tree.find(x); }
//! <b>Returns</b>: A const iterator pointing to an element with the key
//! equivalent to x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic.
const_iterator find(const key_type& x) const
{ return m_tree.find(x); }
//! <b>Returns</b>: The number of elements with key equivalent to x.
//!
//! <b>Complexity</b>: log(size())+count(k)
size_type count(const key_type& x) const
{ return m_tree.count(x); }
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
iterator lower_bound(const key_type& x)
{return m_tree.lower_bound(x); }
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than k, or a.end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
const_iterator lower_bound(const key_type& x) const
{ return m_tree.lower_bound(x); }
//! <b>Returns</b>: An iterator pointing to the first element with key not less
//! than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
iterator upper_bound(const key_type& x)
{ return m_tree.upper_bound(x); }
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
std::pair<iterator,iterator> equal_range(const key_type& x)
{ return m_tree.equal_range(x); }
//! <b>Returns</b>: A const iterator pointing to the first element with key not
//! less than x, or end() if such an element is not found.
//!
//! <b>Complexity</b>: Logarithmic
const_iterator upper_bound(const key_type& x) const
{ return m_tree.upper_bound(x); }
//! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)).
//!
//! <b>Complexity</b>: Logarithmic
std::pair<const_iterator,const_iterator>
equal_range(const key_type& x) const
{ return m_tree.equal_range(x); }
/// @cond
template <class K1, class T1, class C1, class A1>
friend bool operator== (const multimap<K1, T1, C1, A1>& x,
const multimap<K1, T1, C1, A1>& y);
template <class K1, class T1, class C1, class A1>
friend bool operator< (const multimap<K1, T1, C1, A1>& x,
const multimap<K1, T1, C1, A1>& y);
/// @endcond
};
template <class Key, class T, class Pred, class A>
inline bool operator==(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y)
{ return x.m_tree == y.m_tree; }
template <class Key, class T, class Pred, class A>
inline bool operator<(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y)
{ return x.m_tree < y.m_tree; }
template <class Key, class T, class Pred, class A>
inline bool operator!=(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y)
{ return !(x == y); }
template <class Key, class T, class Pred, class A>
inline bool operator>(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y)
{ return y < x; }
template <class Key, class T, class Pred, class A>
inline bool operator<=(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y)
{ return !(y < x); }
template <class Key, class T, class Pred, class A>
inline bool operator>=(const multimap<Key,T,Pred,A>& x,
const multimap<Key,T,Pred,A>& y)
{ return !(x < y); }
template <class Key, class T, class Pred, class A>
inline void swap(multimap<Key,T,Pred,A>& x, multimap<Key,T,Pred,A>& y)
{ x.swap(y); }
/// @cond
} //namespace container {
/*
//!has_trivial_destructor_after_move<> == true_type
//!specialization for optimizations
template <class K, class T, class C, class A>
struct has_trivial_destructor_after_move<boost::container::multimap<K, T, C, A> >
{
static const bool value = has_trivial_destructor<A>::value && has_trivial_destructor<C>::value;
};
*/
namespace container {
/// @endcond
}}
#include <boost/container/detail/config_end.hpp>
#endif /* BOOST_CONTAINERS_MAP_HPP */
|
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "precompile.h"
namespace google_breakpad {
Base::Base(Derived* derived)
: derived_(derived) {
}
Base::~Base() {
derived_->DoSomething();
}
#pragma warning(push)
#pragma warning(disable:4355)
// Disable warning C4355: 'this' : used in base member initializer list.
Derived::Derived()
: Base(this) { // C4355
}
#pragma warning(pop)
void Derived::DoSomething() {
}
} // namespace google_breakpad
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/wallet.h>
#include <base58.h>
#include <checkpoints.h>
#include <chain.h>
#include <wallet/coincontrol.h>
#include <consensus/consensus.h>
#include <consensus/validation.h>
#include <coins.h>
#include <dbwrapper.h>
#include <fs.h>
#include <wallet/init.h>
#include <key.h>
#include <keystore.h>
#include <validation.h>
#include <net.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <scheduler.h>
#include <timedata.h>
#include <txmempool.h>
#include <util.h>
#include <utilmoneystr.h>
#include <wallet/fees.h>
#include <assert.h>
#include <future>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
#include <sidechain.h>
#include <sidechaindb.h>
std::vector<CWalletRef> vpwallets;
/** Transaction fee set by the user */
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
bool fWalletRbf = DEFAULT_WALLET_RBF;
OutputType g_address_type = OUTPUT_TYPE_NONE;
OutputType g_change_type = OUTPUT_TYPE_NONE;
const char * DEFAULT_WALLET_DAT = "wallet.dat";
const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
/**
* Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
/**
* If fee estimation does not have enough data to provide estimates, use this fee instead.
* Has no effect if not using fee estimation
* Override with -fallbackfee
*/
CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly
{
bool operator()(const CInputCoin& t1,
const CInputCoin& t2) const
{
return t1.txout.nValue < t2.txout.nValue;
}
};
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
}
class CAffectedKeysVisitor : public boost::static_visitor<void> {
private:
const CKeyStore &keystore;
std::vector<CKeyID> &vKeys;
public:
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
void Process(const CScript &script) {
txnouttype type;
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
for (const CTxDestination &dest : vDest)
boost::apply_visitor(*this, dest);
}
}
void operator()(const CKeyID &keyId) {
if (keystore.HaveKey(keyId))
vKeys.push_back(keyId);
}
void operator()(const CScriptID &scriptId) {
CScript script;
if (keystore.GetCScript(scriptId, script))
Process(script);
}
void operator()(const WitnessV0ScriptHash& scriptID)
{
CScriptID id;
CRIPEMD160().Write(scriptID.begin(), 32).Finalize(id.begin());
CScript script;
if (keystore.GetCScript(id, script)) {
Process(script);
}
}
void operator()(const WitnessV0KeyHash& keyid)
{
CKeyID id(keyid);
if (keystore.HaveKey(id)) {
vKeys.push_back(id);
}
}
template<typename X>
void operator()(const X &none) {}
};
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return nullptr;
return &(it->second);
}
CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
CKey secret;
// Create new metadata
int64_t nCreationTime = GetTime();
CKeyMetadata metadata(nCreationTime);
// use HD key derivation if HD was enabled during wallet creation
if (IsHDEnabled()) {
DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
} else {
secret.MakeNewKey(fCompressed);
}
// Compressed public keys were introduced in version 0.6.0
if (fCompressed) {
SetMinVersion(FEATURE_COMPRPUBKEY);
}
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
mapKeyMetadata[pubkey.GetID()] = metadata;
UpdateTimeFirstKey(nCreationTime);
if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
throw std::runtime_error(std::string(__func__) + ": AddKey failed");
}
return pubkey;
}
void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
{
// for now we use a fixed keypath scheme of m/0'/0'/k
CKey key; //master key seed (256bit)
CExtKey masterKey; //hd master key
CExtKey accountKey; //key at m/0'
CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
CExtKey childKey; //key at m/0'/0'/<n>'
// try to get the master key
if (!GetKey(hdChain.masterKeyID, key))
throw std::runtime_error(std::string(__func__) + ": Master key not found");
masterKey.SetMaster(key.begin(), key.size());
// derive m/0'
// use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
// derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
// derive child key at next index, skip keys already known to the wallet
do {
// always derive hardened keys
// childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
// example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
if (internal) {
chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
hdChain.nInternalChainCounter++;
}
else {
chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
hdChain.nExternalChainCounter++;
}
} while (HaveKey(childKey.key.GetPubKey().GetID()));
secret = childKey.key;
metadata.hdMasterKeyID = hdChain.masterKeyID;
// update the chain model in the database
if (!walletdb.WriteHDChain(hdChain))
throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
}
bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
// CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
// which is overridden below. To avoid flushes, the database handle is
// tunneled through to it.
bool needsDB = !pwalletdbEncryption;
if (needsDB) {
pwalletdbEncryption = &walletdb;
}
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
if (needsDB) pwalletdbEncryption = nullptr;
return false;
}
if (needsDB) pwalletdbEncryption = nullptr;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(pubkey.GetID());
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
script = GetScriptForRawPubKey(pubkey);
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
if (!IsCrypted()) {
return walletdb.WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
{
CWalletDB walletdb(*dbw);
return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
const std::vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
}
bool CWallet::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
UpdateTimeFirstKey(meta.nCreateTime);
mapKeyMetadata[keyID] = meta;
return true;
}
bool CWallet::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &meta)
{
AssertLockHeld(cs_wallet); // m_script_metadata
UpdateTimeFirstKey(meta.nCreateTime);
m_script_metadata[script_id] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
/**
* Update wallet first key creation time. This should be called whenever keys
* are added to the wallet, with the oldest key creation time.
*/
void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
{
AssertLockHeld(cs_wallet);
if (nCreateTime <= 1) {
// Cannot determine birthday information, so set the wallet birthday to
// the beginning of time.
nTimeFirstKey = 1;
} else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
nTimeFirstKey = nCreateTime;
}
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
std::string strAddr = EncodeDestination(CScriptID(redeemScript));
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
return true;
}
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::AddWatchOnly(const CScript& dest)
{
if (!CCryptoKeyStore::AddWatchOnly(dest))
return false;
const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
UpdateTimeFirstKey(meta.nCreateTime);
NotifyWatchonlyChanged(true);
return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
}
bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
{
m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
return AddWatchOnly(dest);
}
bool CWallet::RemoveWatchOnly(const CScript &dest)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::RemoveWatchOnly(dest))
return false;
if (!HaveWatchOnly())
NotifyWatchonlyChanged(false);
if (!CWalletDB(*dbw).EraseWatchOnly(dest))
return false;
return true;
}
bool CWallet::LoadWatchOnly(const CScript &dest)
{
return CCryptoKeyStore::AddWatchOnly(dest);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
CCrypter crypter;
CKeyingMaterial _vMasterKey;
{
LOCK(cs_wallet);
for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
continue; // try another master key
if (CCryptoKeyStore::Unlock(_vMasterKey))
return true;
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial _vMasterKey;
for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(_vMasterKey))
{
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(*dbw);
walletdb.WriteBestBlock(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
std::set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
for (const CTxIn& txin : wtx.tx->vin)
{
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
result.insert(_it->second);
}
return result;
}
bool CWallet::HasWalletSpend(const uint256& txid) const
{
AssertLockHeld(cs_wallet);
auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
return (iter != mapTxSpends.end() && iter->first.hash == txid);
}
void CWallet::Flush(bool shutdown)
{
dbw->Flush(shutdown);
}
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = nullptr;
for (TxSpends::iterator it = range.first; it != range.second; ++it) {
const CWalletTx* wtx = &mapWallet[it->second];
if (wtx->nOrderPos < nMinOrderPos) {
nMinOrderPos = wtx->nOrderPos;;
copyFrom = wtx;
}
}
assert(copyFrom);
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet[hash];
if (copyFrom == copyTo) continue;
assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// fTimeReceivedIsTxTime not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nReplayStatus = copyFrom->nReplayStatus;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
{
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end()) {
int depth = mit->second.GetDepthInMainChain();
if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
return true; // Spent
}
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(std::make_pair(outpoint, wtxid));
std::pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
auto it = mapWallet.find(wtxid);
assert(it != mapWallet.end());
CWalletTx& thisTx = it->second;
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
for (const CTxIn& txin : thisTx.tx->vin)
AddToSpends(txin.prevout, wtxid);
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial _vMasterKey;
_vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
assert(!pwalletdbEncryption);
pwalletdbEncryption = new CWalletDB(*dbw);
if (!pwalletdbEncryption->TxnBegin()) {
delete pwalletdbEncryption;
pwalletdbEncryption = nullptr;
return false;
}
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
if (!EncryptKeys(_vMasterKey))
{
pwalletdbEncryption->TxnAbort();
delete pwalletdbEncryption;
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (!pwalletdbEncryption->TxnCommit()) {
delete pwalletdbEncryption;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);
}
delete pwalletdbEncryption;
pwalletdbEncryption = nullptr;
Lock();
Unlock(strWalletPassphrase);
// if we are using HD, replace the HD master key (seed) with a new one
if (IsHDEnabled()) {
if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
return false;
}
}
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
dbw->Rewrite();
}
NotifyStatusChanged(this);
return true;
}
DBErrors CWallet::ReorderTransactions()
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (auto& entry : mapWallet)
{
CWalletTx* wtx = &entry.second;
txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
}
std::list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit("", acentries);
for (CAccountingEntry& entry : acentries)
{
txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
}
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
return DB_LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
for (const int64_t& nOffsetStart : nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
return DB_LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
walletdb.WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb) {
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else {
CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
{
CWalletDB walletdb(*dbw);
if (!walletdb.TxnBegin())
return false;
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
AddAccountingEntry(debit, &walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
AddAccountingEntry(credit, &walletdb);
if (!walletdb.TxnCommit())
return false;
return true;
}
bool CWallet::GetAccountDestination(CTxDestination &dest, std::string strAccount, bool bForceNew)
{
CWalletDB walletdb(*dbw);
CAccount account;
walletdb.ReadAccount(strAccount, account);
if (!bForceNew) {
if (!account.vchPubKey.IsValid())
bForceNew = true;
else {
// Check if the current key has been used (TODO: check other addresses with the same key)
CScript scriptPubKey = GetScriptForDestination(GetDestinationForKey(account.vchPubKey, g_address_type));
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
it != mapWallet.end() && account.vchPubKey.IsValid();
++it)
for (const CTxOut& txout : (*it).second.tx->vout)
if (txout.scriptPubKey == scriptPubKey) {
bForceNew = true;
break;
}
}
}
// Generate a new key
if (bForceNew) {
if (!GetKeyFromPool(account.vchPubKey, false))
return false;
LearnRelatedScripts(account.vchPubKey, g_address_type);
dest = GetDestinationForKey(account.vchPubKey, g_address_type);
SetAddressBook(dest, strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
} else {
dest = GetDestinationForKey(account.vchPubKey, g_address_type);
}
return true;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
{
LOCK(cs_wallet);
auto mi = mapWallet.find(originalHash);
// There is a bug if MarkReplaced is not called on an existing wallet transaction.
assert(mi != mapWallet.end());
CWalletTx& wtx = (*mi).second;
// Ensure for now that we're not overwriting data
assert(wtx.mapValue.count("replaced_by_txid") == 0);
wtx.mapValue["replaced_by_txid"] = newHash.ToString();
CWalletDB walletdb(*dbw, "r+");
bool success = true;
if (!walletdb.WriteTx(wtx)) {
LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
success = false;
}
NotifyTransactionChanged(this, originalHash, CT_UPDATED);
return success;
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
uint256 hash = wtxIn.GetHash();
// Inserts only if not already there, returns tx inserted or tx found
std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
{
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(&walletdb);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
// If no longer abandoned, update
if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
{
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
if (wtxIn.nReplayStatus != wtx.nReplayStatus)
{
wtx.nReplayStatus = wtxIn.nReplayStatus;
fUpdated = true;
}
// If we have a witness-stripped version of this transaction, and we
// see a new version with a witness, then we must be upgrading a pre-segwit
// wallet. Store the new version of the transaction with the witness,
// as the stripped-version must be invalid.
// TODO: Store all versions of the transaction, instead of just one.
if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
wtx.SetTx(wtxIn.tx);
fUpdated = true;
}
}
//// debug print
LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!walletdb.WriteTx(wtx))
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = gArgs.GetArg("-walletnotify", "");
if (!strCmd.empty())
{
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
{
uint256 hash = wtxIn.GetHash();
CWalletTx& wtx = mapWallet.emplace(hash, wtxIn).first->second;
wtx.BindWallet(this);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
AddToSpends(hash);
for (const CTxIn& txin : wtx.tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
CWalletTx& prevtx = it->second;
if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
MarkConflicted(prevtx.hashBlock, wtx.GetHash());
}
}
}
return true;
}
/**
* Add a transaction to the wallet, or update it. pIndex and posInBlock should
* be set when the transaction was known to be included in a block. When
* pIndex == nullptr, then wallet state is not updated in AddToWallet, but
* notifications happen and cached balances are marked dirty.
*
* If fUpdate is true, existing transactions will be updated.
* TODO: One exception to this is that the abandoned state is cleared under the
* assumption that any further notification of a transaction that was considered
* abandoned is an indication that it is not safe to be considered abandoned.
* Abandoned state should probably be more carefully tracked via different
* posInBlock signals or by checking mempool presence when necessary.
*/
bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
{
const CTransaction& tx = *ptx;
{
AssertLockHeld(cs_wallet);
if (pIndex != nullptr) {
for (const CTxIn& txin : tx.vin) {
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetHash()) {
LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
MarkConflicted(pIndex->GetBlockHash(), range.first->second);
}
range.first++;
}
}
}
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
/* Check if any keys in the wallet keypool that were supposed to be unused
* have appeared in a new transaction. If so, remove those keys from the keypool.
* This can happen when restoring an old wallet backup that does not contain
* the mostly recently created transactions from newer versions of the wallet.
*/
// loop though all outputs
for (const CTxOut& txout: tx.vout) {
// extract addresses and check if they match with an unused keypool key
std::vector<CKeyID> vAffected;
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
for (const CKeyID &keyid : vAffected) {
std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
if (mi != m_pool_key_to_index.end()) {
LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
MarkReserveKeysAsUsed(mi->second);
if (!TopUpKeyPool()) {
LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
}
}
}
}
CWalletTx wtx(this, ptx);
// Get merkle branch if transaction was found in a block
if (pIndex != nullptr)
wtx.SetMerkleBranch(pIndex, posInBlock);
return AddToWallet(wtx, false);
}
}
return false;
}
bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
{
LOCK2(cs_main, cs_wallet);
const CWalletTx* wtx = GetWalletTx(hashTx);
return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() == 0 && !wtx->InMempool();
}
bool CWallet::AbandonTransaction(const uint256& hashTx, std::string* pstrReason)
{
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(*dbw, "r+");
std::set<uint256> todo;
std::set<uint256> done;
// Can't mark abandoned if confirmed or in mempool
auto it = mapWallet.find(hashTx);
assert(it != mapWallet.end());
CWalletTx& origtx = it->second;
if (origtx.GetDepthInMainChain() != 0) {
if (pstrReason)
*pstrReason = "Already confirmed in block!";
return false;
}
if (origtx.InMempool()) {
if (pstrReason)
*pstrReason = "In mempool!";
return false;
}
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
// If the orig tx was not in block, none of its spends can be
assert(currentconfirm <= 0);
// if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
if (currentconfirm == 0 && !wtx.isAbandoned()) {
// If the orig tx was not in block/mempool, none of its spends can be in mempool
assert(!wtx.InMempool());
wtx.nIndex = -1;
wtx.setAbandoned();
wtx.MarkDirty();
walletdb.WriteTx(wtx);
NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
for (const CTxIn& txin : wtx.tx->vin)
{
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
}
return true;
}
void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
int conflictconfirms = 0;
if (mapBlockIndex.count(hashBlock)) {
CBlockIndex* pindex = mapBlockIndex[hashBlock];
if (chainActive.Contains(pindex)) {
conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
}
}
// If number of conflict confirms cannot be determined, this means
// that the block is still unknown or not yet part of the main chain,
// for example when loading the wallet during a reindex. Do nothing in that
// case.
if (conflictconfirms >= 0)
return;
// Do not flush the wallet here for performance reasons
CWalletDB walletdb(*dbw, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
if (conflictconfirms < currentconfirm) {
// Block is 'more conflicted' than current confirm; update.
// Mark transaction as conflicted with this block.
wtx.nIndex = -1;
wtx.hashBlock = hashBlock;
wtx.MarkDirty();
walletdb.WriteTx(wtx);
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
for (const CTxIn& txin : wtx.tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
}
}
void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
const CTransaction& tx = *ptx;
if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
for (const CTxIn& txin : tx.vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
LOCK2(cs_main, cs_wallet);
SyncTransaction(ptx);
auto it = mapWallet.find(ptx->GetHash());
if (it != mapWallet.end()) {
it->second.fInMempool = true;
}
}
void CWallet::TransactionRemovedFromMempool(const CTransactionRef &ptx) {
LOCK(cs_wallet);
auto it = mapWallet.find(ptx->GetHash());
if (it != mapWallet.end()) {
it->second.fInMempool = false;
}
}
void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
LOCK2(cs_main, cs_wallet);
// TODO: Temporarily ensure that mempool removals are notified before
// connected transactions. This shouldn't matter, but the abandoned
// state of transactions in our wallet is currently cleared when we
// receive another notification and there is a race condition where
// notification of a connected conflict might cause an outside process
// to abandon a transaction and then have it inadvertently cleared by
// the notification that the conflicted transaction was evicted.
for (const CTransactionRef& ptx : vtxConflicted) {
SyncTransaction(ptx);
TransactionRemovedFromMempool(ptx);
}
for (size_t i = 0; i < pblock->vtx.size(); i++) {
SyncTransaction(pblock->vtx[i], pindex, i);
TransactionRemovedFromMempool(pblock->vtx[i]);
}
m_last_block_processed = pindex;
}
void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
LOCK2(cs_main, cs_wallet);
for (const CTransactionRef& ptx : pblock->vtx) {
SyncTransaction(ptx);
}
}
void CWallet::BlockUntilSyncedToCurrentChain() {
AssertLockNotHeld(cs_main);
AssertLockNotHeld(cs_wallet);
{
// Skip the queue-draining stuff if we know we're caught up with
// chainActive.Tip()...
// We could also take cs_wallet here, and call m_last_block_processed
// protected by cs_wallet instead of cs_main, but as long as we need
// cs_main here anyway, its easier to just call it cs_main-protected.
LOCK(cs_main);
const CBlockIndex* initialChainTip = chainActive.Tip();
if (m_last_block_processed->GetAncestor(initialChainTip->nHeight) == initialChainTip) {
return;
}
}
// ...otherwise put a callback in the validation interface queue and wait
// for the queue to drain enough to execute it (indicating we are caught up
// at least with the time we entered this function).
SyncWithValidationInterfaceQueue();
}
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
return IsMine(prev.tx->vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
// Note that this function doesn't distinguish between a 0-valued input,
// and a not-"is mine" (according to the filter) input.
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
return prev.tx->vout[txin.prevout.n].nValue;
}
}
return 0;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout.scriptPubKey);
}
CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return ((IsMine(txout) & filter) ? txout.nValue : 0);
}
bool CWallet::IsChange(const CTxOut& txout) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (::IsMine(*this, txout.scriptPubKey))
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
return true;
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
CAmount CWallet::GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return (IsChange(txout) ? txout.nValue : 0);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
for (const CTxOut& txout : tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nDebit = 0;
for (const CTxIn& txin : tx.vin)
{
nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nDebit;
}
bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
{
LOCK(cs_wallet);
for (const CTxIn& txin : tx.vin)
{
auto mi = mapWallet.find(txin.prevout.hash);
if (mi == mapWallet.end())
return false; // any unknown inputs can't be from us
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n >= prev.tx->vout.size())
return false; // invalid input!
if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
return false;
}
return true;
}
CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nCredit = 0;
for (const CTxOut& txout : tx.vout)
{
nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nCredit;
}
CAmount CWallet::GetChange(const CTransaction& tx) const
{
CAmount nChange = 0;
for (const CTxOut& txout : tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nChange;
}
CPubKey CWallet::GenerateNewHDMasterKey()
{
CKey key;
key.MakeNewKey(true);
int64_t nCreationTime = GetTime();
CKeyMetadata metadata(nCreationTime);
// calculate the pubkey
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
// set the hd keypath to "m" -> Master, refers the masterkeyid to itself
metadata.hdKeypath = "m";
metadata.hdMasterKeyID = pubkey.GetID();
{
LOCK(cs_wallet);
// mem store the metadata
mapKeyMetadata[pubkey.GetID()] = metadata;
// write the key&metadata to the database
if (!AddKeyPubKey(key, pubkey))
throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
}
return pubkey;
}
bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
{
LOCK(cs_wallet);
// store the keyid (hash160) together with
// the child index counter in the database
// as a hdchain object
CHDChain newHdChain;
newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
newHdChain.masterKeyID = pubkey.GetID();
SetHDChain(newHdChain, false);
return true;
}
bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
{
LOCK(cs_wallet);
if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
throw std::runtime_error(std::string(__func__) + ": writing chain failed");
hdChain = chain;
return true;
}
bool CWallet::IsHDEnabled() const
{
return !hdChain.masterKeyID.IsNull();
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = tx->GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < tx->vout.size(); ++i)
{
const CTxOut& txout = tx->vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0)
{
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
}
else if (!(fIsMine & filter))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
{
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
COutputEntry output = {address, txout.nValue, (int)i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(output);
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter)
listReceived.push_back(output);
}
}
/**
* Scan active chain for relevant transactions after importing keys. This should
* be called whenever new keys are added to the wallet, with the oldest key
* creation time.
*
* @return Earliest timestamp that could be successfully scanned from. Timestamp
* returned will be higher than startTime if relevant blocks could not be read.
*/
int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
{
// Find starting block. May be null if nCreateTime is greater than the
// highest blockchain timestamp, in which case there is nothing that needs
// to be scanned.
CBlockIndex* startBlock = nullptr;
{
LOCK(cs_main);
startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
}
if (startBlock) {
const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, reserver, update);
if (failedBlock) {
return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
}
}
return startTime;
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*
* Returns null if scan was successful. Otherwise, if a complete rescan was not
* possible (due to pruning or corruption), returns pointer to the most recent
* block that could not be scanned.
*
* If pindexStop is not a nullptr, the scan will stop at the block-index
* defined by pindexStop
*
* Caller needs to make sure pindexStop (and the optional pindexStart) are on
* the main chain after to the addition of any new keys you want to detect
* transactions for.
*/
CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, const WalletRescanReserver &reserver, bool fUpdate)
{
int64_t nNow = GetTime();
const CChainParams& chainParams = Params();
assert(reserver.isReserved());
if (pindexStop) {
assert(pindexStop->nHeight >= pindexStart->nHeight);
}
CBlockIndex* pindex = pindexStart;
CBlockIndex* ret = nullptr;
{
fAbortRescan = false;
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
CBlockIndex* tip = nullptr;
double dProgressStart;
double dProgressTip;
{
LOCK(cs_main);
tip = chainActive.Tip();
dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
dProgressTip = GuessVerificationProgress(chainParams.TxData(), tip);
}
while (pindex && !fAbortRescan)
{
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) {
double gvp = 0;
{
LOCK(cs_main);
gvp = GuessVerificationProgress(chainParams.TxData(), pindex);
}
ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((gvp - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
}
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LOCK(cs_main);
LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
CBlock block;
if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
LOCK2(cs_main, cs_wallet);
if (pindex && !chainActive.Contains(pindex)) {
// Abort scan if current block is no longer active, to prevent
// marking transactions as coming from the wrong block.
ret = pindex;
break;
}
for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
}
} else {
ret = pindex;
}
if (pindex == pindexStop) {
break;
}
{
LOCK(cs_main);
pindex = chainActive.Next(pindex);
if (tip != chainActive.Tip()) {
tip = chainActive.Tip();
// in case the tip has changed, update progress max
dProgressTip = GuessVerificationProgress(chainParams.TxData(), tip);
}
}
}
if (pindex && fAbortRescan) {
LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
}
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
// If transactions aren't being broadcasted, don't let them into local mempool either
if (!fBroadcastTransactions)
return;
LOCK2(cs_main, cs_wallet);
std::map<int64_t, CWalletTx*> mapSorted;
// Sort pending wallet transactions based on their initial wallet insertion order
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
}
}
// Try to add wallet transactions to memory pool
for (std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
CWalletTx& wtx = *(item.second);
CValidationState state;
wtx.AcceptToMemoryPool(maxTxFee, state);
}
}
bool CWalletTx::RelayWalletTransaction(CConnman* connman)
{
assert(pwallet->GetBroadcastTransactions());
if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
{
CValidationState state;
/* GetDepthInMainChain already catches known conflicts. */
if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
LogPrintf("Relaying wtx %s\n", GetHash().ToString());
if (connman) {
CInv inv(MSG_TX, GetHash());
connman->ForEachNode([&inv](CNode* pnode)
{
pnode->PushInventory(inv);
});
return true;
}
}
}
return false;
}
std::set<uint256> CWalletTx::GetConflicts() const
{
std::set<uint256> result;
if (pwallet != nullptr)
{
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
CAmount CWalletTx::GetDebit(const isminefilter& filter) const
{
if (tx->vin.empty())
return 0;
CAmount debit = 0;
if(filter & ISMINE_SPENDABLE)
{
if (fDebitCached)
debit += nDebitCached;
else
{
nDebitCached = pwallet->GetDebit(*tx, ISMINE_SPENDABLE);
fDebitCached = true;
debit += nDebitCached;
}
}
if(filter & ISMINE_WATCH_ONLY)
{
if(fWatchDebitCached)
debit += nWatchDebitCached;
else
{
nWatchDebitCached = pwallet->GetDebit(*tx, ISMINE_WATCH_ONLY);
fWatchDebitCached = true;
debit += nWatchDebitCached;
}
}
return debit;
}
CAmount CWalletTx::GetCredit(const isminefilter& filter) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (IsCriticalData() && GetBlocksToMaturity() > 0)
return 0;
CAmount credit = 0;
if (filter & ISMINE_SPENDABLE)
{
// GetBalance can assume transactions in mapWallet won't change
if (fCreditCached)
credit += nCreditCached;
else
{
nCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
fCreditCached = true;
credit += nCreditCached;
}
}
if (filter & ISMINE_WATCH_ONLY)
{
if (fWatchCreditCached)
credit += nWatchCreditCached;
else
{
nWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
fWatchCreditCached = true;
credit += nWatchCreditCached;
}
}
return credit;
}
CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
{
if ((IsCoinBase() || IsCriticalData()) && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureCreditCached)
return nImmatureCreditCached;
nImmatureCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
fImmatureCreditCached = true;
return nImmatureCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
{
if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (IsCriticalData() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableCreditCached)
return nAvailableCreditCached;
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < tx->vout.size(); i++)
{
if (!pwallet->IsSpent(hashTx, i))
{
const CTxOut &txout = tx->vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + " : value out of range");
}
}
nAvailableCreditCached = nCredit;
fAvailableCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool fUseCache) const
{
if ((IsCoinBase() || IsCriticalData()) && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureWatchCreditCached)
return nImmatureWatchCreditCached;
nImmatureWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
fImmatureWatchCreditCached = true;
return nImmatureWatchCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool fUseCache) const
{
if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if ((IsCoinBase() || IsCriticalData()) && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableWatchCreditCached)
return nAvailableWatchCreditCached;
CAmount nCredit = 0;
for (unsigned int i = 0; i < tx->vout.size(); i++)
{
if (!pwallet->IsSpent(GetHash(), i))
{
const CTxOut &txout = tx->vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
}
nAvailableWatchCreditCached = nCredit;
fAvailableWatchCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*tx);
fChangeCached = true;
return nChangeCached;
}
bool CWalletTx::InMempool() const
{
return fInMempool;
}
bool CWalletTx::IsTrusted() const
{
// Quick answer in most cases
if (!CheckFinalTx(*tx))
return false;
int nDepth = GetDepthInMainChain();
if (nDepth >= 1)
return true;
if (nDepth < 0)
return false;
if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
return false;
// Don't trust unconfirmed transactions from us unless they are in the mempool.
if (!InMempool())
return false;
// Trusted if all inputs are from us and are in the mempool:
for (const CTxIn& txin : tx->vin)
{
// Transactions not sent by us: not trusted
const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
if (parent == nullptr)
return false;
const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
return false;
}
return true;
}
bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
{
CMutableTransaction tx1 = *this->tx;
CMutableTransaction tx2 = *_tx.tx;
for (auto& txin : tx1.vin) txin.scriptSig = CScript();
for (auto& txin : tx2.vin) txin.scriptSig = CScript();
return CTransaction(tx1) == CTransaction(tx2);
}
std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
{
std::vector<uint256> result;
LOCK(cs_wallet);
// Sort them in chronological order
std::multimap<unsigned int, CWalletTx*> mapSorted;
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime:
if (wtx.nTimeReceived > nTime)
continue;
mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
}
for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.RelayWalletTransaction(connman))
result.push_back(wtx.GetHash());
}
return result;
}
void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend || !fBroadcastTransactions)
return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
if (nBestBlockTime < nLastResend)
return;
nLastResend = GetTime();
// Rebroadcast unconfirmed txes older than 5 minutes before the last
// block was found:
std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
if (!relayed.empty())
LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
}
/** @} */ // end of mapWallet
/** @defgroup Actions
*
* @{
*/
CAmount CWallet::GetBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (const auto& entry : mapWallet)
{
const CWalletTx* pcoin = &entry.second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
}
// Also count loaded coins
for (const LoadedCoin& c : vLoadedCoinCache) {
if (!IsSpent(c.out.hash, c.out.n)) {
nTotal += c.coin.out.nValue;
}
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (const auto& entry : mapWallet)
{
const CWalletTx* pcoin = &entry.second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (const auto& entry : mapWallet)
{
const CWalletTx* pcoin = &entry.second;
nTotal += pcoin->GetImmatureCredit();
}
}
return nTotal;
}
CAmount CWallet::GetWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (const auto& entry : mapWallet)
{
const CWalletTx* pcoin = &entry.second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (const auto& entry : mapWallet)
{
const CWalletTx* pcoin = &entry.second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (const auto& entry : mapWallet)
{
const CWalletTx* pcoin = &entry.second;
nTotal += pcoin->GetImmatureWatchOnlyCredit();
}
}
return nTotal;
}
// Calculate total balance in a different way from GetBalance. The biggest
// difference is that GetBalance sums up all unspent TxOuts paying to the
// wallet, while this sums up both spent and unspent TxOuts paying to the
// wallet, and then subtracts the values of TxIns spending from the wallet. This
// also has fewer restrictions on which unconfirmed transactions are considered
// trusted.
CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
{
LOCK2(cs_main, cs_wallet);
CAmount balance = 0;
for (const auto& entry : mapWallet) {
const CWalletTx& wtx = entry.second;
const int depth = wtx.GetDepthInMainChain();
if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
continue;
}
// Loop through tx outputs and add incoming payments. For outgoing txs,
// treat change outputs specially, as part of the amount debited.
CAmount debit = wtx.GetDebit(filter);
const bool outgoing = debit > 0;
for (const CTxOut& out : wtx.tx->vout) {
if (outgoing && IsChange(out)) {
debit -= out.nValue;
} else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
balance += out.nValue;
}
}
// For outgoing txs, subtract amount debited.
if (outgoing && (!account || *account == wtx.strFromAccount)) {
balance -= debit;
}
}
if (account) {
balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
}
return balance;
}
CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
{
LOCK2(cs_main, cs_wallet);
CAmount balance = 0;
std::vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl);
for (const COutput& out : vCoins) {
if (out.fSpendable) {
balance += out.tx->tx->vout[out.i].nValue;
}
}
// Also count loaded coins
for (const LoadedCoin& c : vLoadedCoinCache) {
if (!IsSpent(c.out.hash, c.out.n))
balance += c.coin.out.nValue;
}
return balance;
}
void CWallet::AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount, const int nMinDepth, const int nMaxDepth) const
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
vCoins.clear();
CAmount nTotal = 0;
for (const auto& entry : mapWallet)
{
const uint256& wtxid = entry.first;
const CWalletTx* pcoin = &entry.second;
if (!CheckFinalTx(*pcoin->tx))
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
if (pcoin->IsCriticalData() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 0)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !pcoin->InMempool())
continue;
bool safeTx = pcoin->IsTrusted();
// We should not consider coins from transactions that are replacing
// other transactions.
//
// Example: There is a transaction A which is replaced by bumpfee
// transaction B. In this case, we want to prevent creation of
// a transaction B' which spends an output of B.
//
// Reason: If transaction A were initially confirmed, transactions B
// and B' would no longer be valid, so the user would have to create
// a new transaction C to replace B'. However, in the case of a
// one-block reorg, transactions B' and C might BOTH be accepted,
// when the user only wanted one of them. Specifically, there could
// be a 1-block reorg away from the chain where transactions A and C
// were accepted to another chain where B, B', and C were all
// accepted.
if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
safeTx = false;
}
// Similarly, we should not consider coins from transactions that
// have been replaced. In the example above, we would want to prevent
// creation of a transaction A' spending an output of A, because if
// transaction B were initially confirmed, conflicting with A and
// A', we wouldn't want to the user to create a transaction D
// intending to replace A', but potentially resulting in a scenario
// where A, A', and D could all be accepted (instead of just B and
// D, or just A and A' like the user would want).
if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
safeTx = false;
}
if (fOnlySafe && !safeTx) {
continue;
}
if (nDepth < nMinDepth || nDepth > nMaxDepth)
continue;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
continue;
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
continue;
if (IsLockedCoin(entry.first, i))
continue;
if (IsSpent(wtxid, i))
continue;
isminetype mine = IsMine(pcoin->tx->vout[i]);
if (mine == ISMINE_NO) {
continue;
}
bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
// Checks the sum amount of all UTXO's.
if (nMinimumSumAmount != MAX_MONEY) {
nTotal += pcoin->tx->vout[i].nValue;
if (nTotal >= nMinimumSumAmount) {
return;
}
}
// Checks the maximum number of UTXO's.
if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
return;
}
}
}
}
std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
{
// TODO: Add AssertLockHeld(cs_wallet) here.
//
// Because the return value from this function contains pointers to
// CWalletTx objects, callers to this function really should acquire the
// cs_wallet lock before calling it. However, the current caller doesn't
// acquire this lock yet. There was an attempt to add the missing lock in
// https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
// postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
// avoid adding some extra complexity to the Qt code.
std::map<CTxDestination, std::vector<COutput>> result;
std::vector<COutput> availableCoins;
LOCK2(cs_main, cs_wallet);
AvailableCoins(availableCoins);
for (auto& coin : availableCoins) {
CTxDestination address;
if (coin.fSpendable &&
ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
result[address].emplace_back(std::move(coin));
}
}
std::vector<COutPoint> lockedCoins;
ListLockedCoins(lockedCoins);
for (const auto& output : lockedCoins) {
auto it = mapWallet.find(output.hash);
if (it != mapWallet.end()) {
int depth = it->second.GetDepthInMainChain();
if (depth >= 0 && output.n < it->second.tx->vout.size() &&
IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
CTxDestination address;
if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
result[address].emplace_back(
&it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
}
}
}
}
return result;
}
const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
{
const CTransaction* ptx = &tx;
int n = output;
while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
const COutPoint& prevout = ptx->vin[0].prevout;
auto it = mapWallet.find(prevout.hash);
if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
!IsMine(it->second.tx->vout[prevout.n])) {
break;
}
ptx = it->second.tx.get();
n = prevout.n;
}
return ptx->vout[n];
}
static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
FastRandomContext insecure_rand;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
{
nTotal += vValue[i].txout.nValue;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].txout.nValue;
vfIncluded[i] = false;
}
}
}
}
}
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
boost::optional<CInputCoin> coinLowestLarger;
std::vector<CInputCoin> vValue;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
for (const COutput &output : vCoins)
{
if (!output.fSpendable)
continue;
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
continue;
int i = output.i;
CInputCoin coin = CInputCoin(pcoin, i);
if (coin.txout.nValue == nTargetValue)
{
setCoinsRet.insert(coin);
nValueRet += coin.txout.nValue;
return true;
}
else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
{
vValue.push_back(coin);
nTotalLower += coin.txout.nValue;
}
else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (const auto& input : vValue)
{
setCoinsRet.insert(input);
nValueRet += input.txout.nValue;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (!coinLowestLarger)
return false;
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLarger->txout.nValue;
return true;
}
// Solve subset sum by stochastic approximation
std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
std::reverse(vValue.begin(), vValue.end());
std::vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
{
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLarger->txout.nValue;
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i]);
nValueRet += vValue[i].txout.nValue;
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++) {
if (vfBest[i]) {
LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
}
}
LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
}
}
return true;
}
bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
{
std::vector<COutput> vCoins(vAvailableCoins);
std::vector<LoadedCoin> vLoadedCoin;
vLoadedCoin = GetMyLoadedCoins();
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
{
for (const COutput& out : vCoins)
{
if (!out.fSpendable)
continue;
nValueRet += out.tx->tx->vout[out.i].nValue;
setCoinsRet.insert(CInputCoin(out.tx, out.i));
}
for (const LoadedCoin& c : vLoadedCoin)
{
if (IsSpent(c.out.hash, c.out.n))
continue;
nValueRet += c.coin.out.nValue;
setCoinsRet.insert(CInputCoin(c.out, c.coin.out));
}
return (nValueRet >= nTargetValue);
}
// calculate value from preset inputs and store them
std::set<CInputCoin> setPresetCoins;
CAmount nValueFromPresetInputs = 0;
std::vector<COutPoint> vPresetInputs;
if (coinControl)
coinControl->ListSelected(vPresetInputs);
for (const COutPoint& outpoint : vPresetInputs)
{
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
{
const CWalletTx* pcoin = &it->second;
// Clearly invalid input, fail
if (pcoin->tx->vout.size() <= outpoint.n)
return false;
nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
} else
return false; // TODO: Allow non-wallet inputs
}
// remove preset inputs from vCoins
for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
{
if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
it = vCoins.erase(it);
else
++it;
}
size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
bool res = nTargetValue <= nValueFromPresetInputs ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
// because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
// add preset inputs to the total value selected
nValueRet += nValueFromPresetInputs;
return res;
}
bool CWallet::SignTransaction(CMutableTransaction &tx)
{
AssertLockHeld(cs_wallet); // mapWallet
// sign the new tx
CTransaction txNewConst(tx);
int nIn = 0;
for (const auto& input : tx.vin) {
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
return false;
}
const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
SignatureData sigdata;
if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
return false;
}
UpdateTransaction(tx, nIn, sigdata);
nIn++;
}
return true;
}
bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
{
std::vector<CRecipient> vecSend;
// Turn the txout set into a CRecipient vector.
for (size_t idx = 0; idx < tx.vout.size(); idx++) {
const CTxOut& txOut = tx.vout[idx];
CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
vecSend.push_back(recipient);
}
coinControl.fAllowOtherInputs = true;
for (const CTxIn& txin : tx.vin) {
coinControl.Select(txin.prevout);
}
// Acquire the locks to prevent races to the new locked unspents between the
// CreateTransaction call and LockCoin calls (when lockUnspents is true).
LOCK2(cs_main, cs_wallet);
CReserveKey reservekey(this);
CWalletTx wtx;
if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
return false;
}
if (nChangePosInOut != -1) {
tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
// We don't have the normal Create/Commit cycle, and don't want to risk
// reusing change, so just remove the key from the keypool here.
reservekey.KeepKey();
}
// Copy output sizes from new transaction; they may have had the fee
// subtracted from them.
for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
}
// Add new txins while keeping original txin scriptSig/order.
for (const CTxIn& txin : wtx.tx->vin) {
if (!coinControl.IsSelected(txin.prevout)) {
tx.vin.push_back(txin);
if (lockUnspents) {
LockCoin(txin.prevout);
}
}
}
return true;
}
OutputType CWallet::TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend)
{
// If -changetype is specified, always use that change type.
if (change_type != OUTPUT_TYPE_NONE) {
return change_type;
}
// if g_address_type is legacy, use legacy address as change (even
// if some of the outputs are P2WPKH or P2WSH).
if (g_address_type == OUTPUT_TYPE_LEGACY) {
return OUTPUT_TYPE_LEGACY;
}
// if any destination is P2WPKH or P2WSH, use P2WPKH for the change
// output.
for (const auto& recipient : vecSend) {
// Check if any destination contains a witness program:
int witnessversion = 0;
std::vector<unsigned char> witnessprogram;
if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
return OUTPUT_TYPE_BECH32;
}
}
// else use g_address_type for change
return g_address_type;
}
bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign, uint32_t nVersionOverride, uint32_t nLockTimeOverride, CCriticalData criticalData)
{
CAmount nValue = 0;
int nChangePosRequest = nChangePosInOut;
unsigned int nSubtractFeeFromAmount = 0;
for (const auto& recipient : vecSend)
{
if (nValue < 0 || recipient.nAmount < 0)
{
strFailReason = _("Transaction amounts must not be negative");
return false;
}
nValue += recipient.nAmount;
if (recipient.fSubtractFeeFromAmount)
nSubtractFeeFromAmount++;
}
if (vecSend.empty())
{
strFailReason = _("Transaction must have at least one recipient");
return false;
}
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
txNew.nVersion = nVersionOverride;
// Discourage fee sniping.
//
// For a large miner the value of the transactions in the best block and
// the mempool can exceed the cost of deliberately attempting to mine two
// blocks to orphan the current best block. By setting nLockTime such that
// only the next block can include the transaction, we discourage this
// practice as the height restricted and limited blocksize gives miners
// considering fee sniping fewer options for pulling off this attack.
//
// A simple way to think about this is from the wallet's point of view we
// always want the blockchain to move forward. By setting nLockTime this
// way we're basically making the statement that we only want this
// transaction to appear in the next block; we don't want to potentially
// encourage reorgs by allowing transactions to appear at lower heights
// than the next block in forks of the best chain.
//
// Of course, the subsidy is high enough, and transaction volume low
// enough, that fee sniping isn't a problem yet, but by implementing a fix
// now we ensure code won't be written that makes assumptions about
// nLockTime that preclude a fix later.
txNew.nLockTime = chainActive.Height();
if (nLockTimeOverride != 0)
txNew.nLockTime = nLockTimeOverride;
if (!criticalData.IsNull())
txNew.criticalData = criticalData;
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
FeeCalculation feeCalc;
CAmount nFeeNeeded;
unsigned int nBytes;
{
std::set<CInputCoin> setCoins;
LOCK2(cs_main, cs_wallet);
{
std::vector<COutput> vAvailableCoins;
AvailableCoins(vAvailableCoins, true, &coin_control);
// Create change script that will be used if we need change
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-bitcoin-address
CScript scriptChange;
// coin control: send change to custom address
if (!boost::get<CNoDestination>(&coin_control.destChange)) {
scriptChange = GetScriptForDestination(coin_control.destChange);
} else { // no coin control: send change to newly generated address
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey;
bool ret;
ret = reservekey.GetReservedKey(vchPubKey, true);
if (!ret)
{
strFailReason = _("Keypool ran out, please call keypoolrefill first");
return false;
}
const OutputType change_type = TransactionChangeType(coin_control.change_type, vecSend);
LearnRelatedScripts(vchPubKey, change_type);
scriptChange = GetScriptForDestination(GetDestinationForKey(vchPubKey, change_type));
}
CTxOut change_prototype_txout(0, scriptChange);
size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
nFeeRet = 0;
bool pick_new_inputs = true;
CAmount nValueIn = 0;
// Start with no fee and loop until there is enough fee
while (true)
{
nChangePosInOut = nChangePosRequest;
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
wtxNew.nReplayStatus = REPLAY_UNKNOWN; // TODO
bool fFirst = true;
CAmount nValueToSelect = nValue;
if (nSubtractFeeFromAmount == 0)
nValueToSelect += nFeeRet;
// vouts to the payees
for (const auto& recipient : vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
if (recipient.fSubtractFeeFromAmount)
{
assert(nSubtractFeeFromAmount != 0);
txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
if (fFirst) // first receiver pays the remainder not divisible by output count
{
fFirst = false;
txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
}
}
if (IsDust(txout, ::dustRelayFee))
{
if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
{
if (txout.nValue < 0)
strFailReason = _("The transaction amount is too small to pay the fee");
else
strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
}
else
strFailReason = _("Transaction amount too small");
return false;
}
txNew.vout.push_back(txout);
}
// Choose coins to use
if (pick_new_inputs) {
nValueIn = 0;
setCoins.clear();
if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
{
strFailReason = _("Insufficient funds");
return false;
}
}
const CAmount nChange = nValueIn - nValueToSelect;
if (nChange > 0)
{
// Fill a vout to ourself
CTxOut newTxOut(nChange, scriptChange);
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (IsDust(newTxOut, discard_rate))
{
nChangePosInOut = -1;
nFeeRet += nChange;
}
else
{
if (nChangePosInOut == -1)
{
// Insert change txn at random position:
nChangePosInOut = GetRandInt(txNew.vout.size()+1);
}
else if ((unsigned int)nChangePosInOut > txNew.vout.size())
{
strFailReason = _("Change index out of range");
return false;
}
std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
txNew.vout.insert(position, newTxOut);
}
} else {
nChangePosInOut = -1;
}
// Fill vin
//
// Note how the sequence number is set to non-maxint so that
// the nLockTime set above actually works.
//
// BIP125 defines opt-in RBF as any nSequence < maxint-1, so
// we use the highest possible value in that range (maxint-2)
// to avoid conflicting with other possible uses of nSequence,
// and in the spirit of "smallest possible change from prior
// behavior."
const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
for (const auto& coin : setCoins)
txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
nSequence));
// Fill in dummy signatures for fee calculation.
if (!DummySignTx(txNew, setCoins)) {
strFailReason = _("Signing transaction failed");
return false;
}
nBytes = GetVirtualTransactionSize(txNew);
// Remove scriptSigs to eliminate the fee calculation dummy signatures
for (auto& vin : txNew.vin) {
vin.scriptSig = CScript();
vin.scriptWitness.SetNull();
}
nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
{
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded) {
// Reduce fee to only the needed amount if possible. This
// prevents potential overpayment in fees if the coins
// selected to meet nFeeNeeded result in a transaction that
// requires less fee than the prior iteration.
// If we have no change and a big enough excess fee, then
// try to construct transaction again only without picking
// new inputs. We now know we only need the smaller fee
// (because of reduced tx size) and so we should add a
// change output. Only try this once.
if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
pick_new_inputs = false;
nFeeRet = fee_needed_with_change;
continue;
}
}
// If we have change output already, just increase it
if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount extraFeePaid = nFeeRet - nFeeNeeded;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
change_position->nValue += extraFeePaid;
nFeeRet -= extraFeePaid;
}
break; // Done, enough fee included.
}
else if (!pick_new_inputs) {
// This shouldn't happen, we should have had enough excess
// fee to pay for the new output and still meet nFeeNeeded
// Or we should have just subtracted fee from recipients and
// nFeeNeeded should not have changed
strFailReason = _("Transaction fee and change calculation failed");
return false;
}
// Try to reduce change to include necessary fee
if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
// Only reduce change if remaining amount is still a large enough output.
if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
change_position->nValue -= additionalFeeNeeded;
nFeeRet += additionalFeeNeeded;
break; // Done, able to increase fee from change
}
}
// If subtracting fee from recipients, we now know what fee we
// need to subtract, we have no reason to reselect inputs
if (nSubtractFeeFromAmount > 0) {
pick_new_inputs = false;
}
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
if (sign)
{
CTransaction txNewConst(txNew);
int nIn = 0;
for (const auto& coin : setCoins)
{
const CScript& scriptPubKey = coin.txout.scriptPubKey;
SignatureData sigdata;
if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
{
strFailReason = _("Signing transaction failed");
return false;
} else {
UpdateTransaction(txNew, nIn, sigdata);
}
nIn++;
}
}
// Embed the constructed transaction data in wtxNew.
wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
// Limit size
if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
{
strFailReason = _("Transaction too large");
return false;
}
}
if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
// Lastly, ensure this tx will pass the mempool's chain limits
LockPoints lp;
CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, false, false, 0, 0, lp);
CTxMemPool::setEntries setAncestors;
size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
strFailReason = _("Transaction has too long of a mempool chain");
return false;
}
}
LogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
feeCalc.est.pass.start, feeCalc.est.pass.end,
100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
feeCalc.est.fail.start, feeCalc.est.fail.end,
100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
return true;
}
bool CWallet::CreateSidechainDeposit(CTransactionRef& tx, std::string& strFail, const CScript& sidechainScriptPubKey, const uint8_t nSidechain, const CAmount& nAmount, const CAmount& nFee, const std::string& strDest)
{
strFail = "Unknown error!";
if (!scdb.IsSidechainActive(nSidechain)) {
strFail = "Invalid Sidechain number!\n";
return false;
}
if (vpwallets.empty()) {
strFail = "No active wallet!\n";
return false;
}
// User deposit data script
CScript dataScript = CScript() << OP_RETURN << ParseHex(HexStr(strDest));
if (dataScript.size() > MAX_DEPOSIT_DESTINATION_BYTES) {
strFail = "Invalid sidechain deposit script - destination too large!";
return false;
}
std::vector<unsigned char> vch(ParseHex(HexStr(sidechainScriptPubKey)));
CScript sidechainScript = CScript(vch.begin(), vch.end());
if (sidechainScript.empty()) {
strFail = "Invalid sidechain deposit script!";
return false;
}
// The deposit transaction
CMutableTransaction mtx;
BlockUntilSyncedToCurrentChain();
LOCK2(cs_main, vpwallets[0]->cs_wallet);
// Select coins to cover sidechain deposit
std::vector<COutput> vCoins;
AvailableCoins(vCoins, true /* fOnlySafe */);
std::set<CInputCoin> setCoins;
CAmount nAmountRet = CAmount(0);
if (!SelectCoins(vCoins, nAmount + nFee, setCoins, nAmountRet)) {
strFail = "Could not collect enough coins to cover deposit + fee!\n";
return false;
}
// Handle change if there is any
const CAmount nChange = nAmountRet - (nAmount + nFee);
CReserveKey reserveKey(vpwallets[0]);
if (nChange > 0) {
CScript scriptChange;
// Reserve a new key pair from key pool
CPubKey vchPubKey;
if (!reserveKey.GetReservedKey(vchPubKey))
{
strFail = "Keypool ran out, please call keypoolrefill first!\n";
return false;
}
scriptChange = GetScriptForDestination(vchPubKey.GetID());
CTxOut out(nChange, scriptChange);
if (!IsDust(out, ::dustRelayFee))
mtx.vout.push_back(out);
}
// Add deposit inputs
for (const auto& coin : setCoins) {
mtx.vin.push_back(CTxIn(coin.outpoint.hash, coin.outpoint.n, CScript()));
}
// Add data output
mtx.vout.push_back(CTxOut(CAmount(0), dataScript));
// Add deposit output
mtx.vout.push_back(CTxOut(nAmount, sidechainScript));
// Handle existing sidechain utxo. We will look at our local mempool, and
// create a deposit based on the latest CTIP for the sidechain.
// Note: It will be rejected if other nodes have seen a newer CTIP.
SidechainCTIP ctip;
CAmount returnAmount = CAmount(0);
if (::mempool.GetMemPoolCTIP(nSidechain, ctip)) {
returnAmount = ctip.amount;
// Amount returning to sidechain
mtx.vout.back().nValue += returnAmount;
// Spend the existing CTIP
mtx.vin.push_back(CTxIn(ctip.out));
}
// Dummy sign the transaction to calculate fee
std::set<CInputCoin> setCoinsTemp = setCoins;
// TODO also dummy sign the sidechain UTXO input
if (!DummySignTx(mtx, setCoinsTemp)) {
strFail = "Dummy signing transaction for required fee calculation failed!";
return false;
}
// Get transaction size with dummy signatures
unsigned int nBytes = GetVirtualTransactionSize(mtx);
// Calculate fee
CCoinControl coinControl;
FeeCalculation feeCalc;
CAmount nFeeNeeded = GetMinimumFee(nBytes, coinControl, ::mempool, ::feeEstimator, &feeCalc);
// Check that the fee is valid for relay
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) {
strFail = "Transaction too large for fee policy";
return false;
}
// Check the user set fee
if (nFee < nFeeNeeded) {
strFail = "The fee you have set is too small!";
return false;
}
// Remove dummy signatures
for (auto& vin : mtx.vin) {
vin.scriptSig = CScript();
vin.scriptWitness.SetNull();
}
Sidechain sidechain;
if (!scdb.GetSidechain(nSidechain, sidechain))
return false;
// Sign the sidechain utxo if we need to
if (returnAmount > CAmount(0)) {
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(sidechain.strPrivKey);
if (!fGood) {
strFail = "Invalid sidechain private key encoding!\n";
return false;
}
CKey privKey = vchSecret.GetKey();
if (!privKey.IsValid()) {
strFail = "Sidechain private key invalid!\n";
return false;
}
CBasicKeyStore tempKeystore;
tempKeystore.AddKey(privKey);
const CKeyStore& keystoreConst = tempKeystore;
const CTransaction& txToSign = mtx;
TransactionSignatureCreator creator(&keystoreConst, &txToSign, mtx.vin.size() - 1, returnAmount);
SignatureData sigdata;
bool sigCreated = ProduceSignature(creator, sidechainScript, sigdata);
if (!sigCreated) {
strFail = "Failed to sign sidechain inputs!\n";
return false;
}
mtx.vin.back().scriptSig = sigdata.scriptSig;
}
// Sign the non sidechain inputs
const CTransaction txToSign = mtx;
int nIn = 0;
for (const auto& coin : setCoins) {
const CScript& scriptPubKey = coin.txout.scriptPubKey;
SignatureData sigdata;
if (!ProduceSignature(TransactionSignatureCreator(this, &txToSign, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
{
strFail = "Signing non-sidechain inputs failed!\n";
return false;
} else {
UpdateTransaction(mtx, nIn, sigdata);
}
nIn++;
}
// Broadcast transaction
CWalletTx wtxNew;
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.fFromMe = true;
wtxNew.BindWallet(this);
wtxNew.SetTx(MakeTransactionRef(std::move(mtx)));
CValidationState state;
if (!CommitTransaction(wtxNew, reserveKey, g_connman.get(), state, true /* fRemoveIfFail */)) {
strFail = "Failed to commit sidechain deposit! Reject reason: " + FormatStateMessage(state) + "\n";
return false;
}
tx = wtxNew.tx;
return true;
}
/**
* Call after CreateTransaction unless you want to abort
*/
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state, bool fRemoveIfFail)
{
{
LOCK2(cs_main, cs_wallet);
LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
{
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Notify that old coins are spent
for (const CTxIn& txin : wtxNew.tx->vin)
{
// TODO handle loaded coin being spent notification (GUI)
// Skip notification if spending a loaded coin (will segfault)
// We check IsSpent every time we look up loaded coins for now.
const auto i = mapWallet.find(txin.prevout.hash);
if (i == mapWallet.end())
continue;
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
}
// Get the inserted-CWalletTx from mapWallet so that the
// fInMempool flag is cached properly
CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
if (fBroadcastTransactions)
{
// Broadcast
if (!wtx.AcceptToMemoryPool(maxTxFee, state)) {
LogPrintf("%s: Transaction cannot be broadcast immediately, %s\n", __func__, state.GetRejectReason());
const uint256 hashTx = wtx.GetHash();
if (fRemoveIfFail && mapWallet.count(hashTx)) {
if (!AbandonTransaction(hashTx)) {
LogPrintf("%s: Failed to abandon transaction!\n", __func__);
}
return false;
}
} else {
wtx.RelayWalletTransaction(connman);
}
}
}
return true;
}
void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
CWalletDB walletdb(*dbw);
return walletdb.ListAccountCreditDebit(strAccount, entries);
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
{
CWalletDB walletdb(*dbw);
return AddAccountingEntry(acentry, &walletdb);
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
{
if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
return false;
}
laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back();
wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
return true;
}
void CWallet::AddLoadedCoins(const std::vector<LoadedCoin>& vLoadedCoin)
{
AssertLockHeld(cs_wallet);
vLoadedCoinCache.clear();
for (const LoadedCoin& c : vLoadedCoin) {
vLoadedCoinCache.push_back(c);
}
}
std::vector<LoadedCoin> CWallet::GetMyLoadedCoins() const
{
return vLoadedCoinCache;
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
LOCK2(cs_main, cs_wallet);
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
// This wallet is in its first run if all of these are empty
fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
uiInterface.LoadWallet(this);
return DB_LOAD_OK;
}
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{
AssertLockHeld(cs_wallet); // mapWallet
DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
for (uint256 hash : vHashOut)
mapWallet.erase(hash);
if (nZapSelectTxRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapSelectTxRet != DB_LOAD_OK)
return nZapSelectTxRet;
MarkDirty();
return DB_LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
LOCK(cs_wallet);
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapWalletTxRet != DB_LOAD_OK)
return nZapWalletTxRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
fUpdated = mi != mapAddressBook.end();
mapAddressBook[address].name = strName;
if (!strPurpose.empty()) /* update purpose only if requested */
mapAddressBook[address].purpose = strPurpose;
}
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
return false;
return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
{
LOCK(cs_wallet); // mapAddressBook
// Delete destdata tuples associated with address
std::string strAddress = EncodeDestination(address);
for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
{
CWalletDB(*dbw).EraseDestData(strAddress, item.first);
}
mapAddressBook.erase(address);
}
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
return CWalletDB(*dbw).EraseName(EncodeDestination(address));
}
const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
{
CTxDestination address;
if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
auto mi = mapAddressBook.find(address);
if (mi != mapAddressBook.end()) {
return mi->second.name;
}
}
// A scriptPubKey that doesn't have an entry in the address book is
// associated with the default account ("").
const static std::string DEFAULT_ACCOUNT_NAME;
return DEFAULT_ACCOUNT_NAME;
}
/**
* Mark old keypool keys as used,
* and generate all new keys
*/
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
for (int64_t nIndex : setInternalKeyPool) {
walletdb.ErasePool(nIndex);
}
setInternalKeyPool.clear();
for (int64_t nIndex : setExternalKeyPool) {
walletdb.ErasePool(nIndex);
}
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
if (!TopUpKeyPool()) {
return false;
}
LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
}
return true;
}
size_t CWallet::KeypoolCountExternalKeys()
{
AssertLockHeld(cs_wallet); // setExternalKeyPool
return setExternalKeyPool.size();
}
void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
{
AssertLockHeld(cs_wallet);
if (keypool.fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (mapKeyMetadata.count(keyid) == 0)
mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
// Top up key pool
unsigned int nTargetSize;
if (kpSize > 0)
nTargetSize = kpSize;
else
nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
// count amount of available keys (internal, external)
// make sure the keypool of external and internal keys fits the user selected target (-keypool)
int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
{
// don't create extra internal keys
missingInternal = 0;
}
bool internal = false;
CWalletDB walletdb(*dbw);
for (int64_t i = missingInternal + missingExternal; i--;)
{
if (i < missingInternal) {
internal = true;
}
assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
int64_t index = ++m_max_keypool_index;
CPubKey pubkey(GenerateNewKey(walletdb, internal));
if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
}
if (internal) {
setInternalKeyPool.insert(index);
} else {
setExternalKeyPool.insert(index);
}
m_pool_key_to_index[pubkey.GetID()] = index;
}
if (missingInternal + missingExternal > 0) {
LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
// Get the oldest key
if(setKeyPool.empty())
return;
CWalletDB walletdb(*dbw);
auto it = setKeyPool.begin();
nIndex = *it;
setKeyPool.erase(it);
if (!walletdb.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read failed");
}
if (!HaveKey(keypool.vchPubKey.GetID())) {
throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
}
if (keypool.fInternal != fReturningInternal) {
throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
}
assert(keypool.vchPubKey.IsValid());
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
LogPrintf("keypool reserve %d\n", nIndex);
}
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
CWalletDB walletdb(*dbw);
walletdb.ErasePool(nIndex);
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
{
// Return to key pool
{
LOCK(cs_wallet);
if (fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
m_pool_key_to_index[pubkey.GetID()] = nIndex;
}
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
{
CKeyPool keypool;
{
LOCK(cs_wallet);
int64_t nIndex = 0;
ReserveKeyFromKeyPool(nIndex, keypool, internal);
if (nIndex == -1)
{
if (IsLocked()) return false;
CWalletDB walletdb(*dbw);
result = GenerateNewKey(walletdb, internal);
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
if (setKeyPool.empty()) {
return GetTime();
}
CKeyPool keypool;
int64_t nIndex = *(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
}
assert(keypool.vchPubKey.IsValid());
return keypool.nTime;
}
int64_t CWallet::GetOldestKeyPoolTime()
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
// load oldest key from keypool, get time and return
int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
}
return oldestKey;
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{
std::map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
for (const auto& walletEntry : mapWallet)
{
const CWalletTx *pcoin = &walletEntry.second;
if (!pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
if (pcoin->IsCriticalData() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
{
CTxDestination addr;
if (!IsMine(pcoin->tx->vout[i]))
continue;
if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
std::set< std::set<CTxDestination> > groupings;
std::set<CTxDestination> grouping;
for (const auto& walletEntry : mapWallet)
{
const CWalletTx *pcoin = &walletEntry.second;
if (pcoin->tx->vin.size() > 0)
{
bool any_mine = false;
// group all input addresses with each other
for (CTxIn txin : pcoin->tx->vin)
{
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine)
{
for (CTxOut txout : pcoin->tx->vout)
if (IsChange(txout))
{
CTxDestination txoutAddr;
if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0)
{
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (const auto& txout : pcoin->tx->vout)
if (IsMine(txout))
{
CTxDestination address;
if(!ExtractDestination(txout.scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
for (std::set<CTxDestination> _grouping : groupings)
{
// make a set of all the groups hit by this new group
std::set< std::set<CTxDestination>* > hits;
std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
for (CTxDestination address : _grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
for (std::set<CTxDestination>* hit : hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
for (CTxDestination element : *merged)
setmap[element] = merged;
}
std::set< std::set<CTxDestination> > ret;
for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
{
LOCK(cs_wallet);
std::set<CTxDestination> result;
for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
{
const CTxDestination& address = item.first;
const std::string& strName = item.second.name;
if (strName == strAccount)
result.insert(address);
}
return result;
}
bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else {
return false;
}
fInternal = keypool.fInternal;
}
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1) {
pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
}
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
{
AssertLockHeld(cs_wallet);
bool internal = setInternalKeyPool.count(keypool_id);
if (!internal) assert(setExternalKeyPool.count(keypool_id));
std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
auto it = setKeyPool->begin();
CWalletDB walletdb(*dbw);
while (it != std::end(*setKeyPool)) {
const int64_t& index = *(it);
if (index > keypool_id) break; // set*KeyPool is ordered
CKeyPool keypool;
if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
}
LearnAllRelatedScripts(keypool.vchPubKey);
walletdb.ErasePool(index);
LogPrintf("keypool index %d removed\n", index);
it = setKeyPool->erase(it);
}
}
void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
{
std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
CPubKey pubkey;
if (!rKey->GetReservedKey(pubkey))
return;
script = rKey;
script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
}
void CWallet::LockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.insert(output);
}
void CWallet::UnlockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.erase(output);
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
/** @} */ // end of Actions
void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (const auto& entry : mapKeyMetadata) {
if (entry.second.nCreateTime) {
mapKeyBirth[entry.first] = entry.second.nCreateTime;
}
}
// map in which we'll infer heights of other keys
CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
for (const CKeyID &keyid : GetKeys()) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (const auto& entry : mapWallet) {
// iterate over all wallet transactions...
const CWalletTx &wtx = entry.second;
BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
for (const CTxOut &txout : wtx.tx->vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
for (const CKeyID &keyid : vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
}
vAffected.clear();
}
}
}
// Extract block timestamps for those keys
for (const auto& entry : mapKeyFirstBlock)
mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
}
/**
* Compute smart timestamp for a transaction being added to the wallet.
*
* Logic:
* - If sending a transaction, assign its timestamp to the current time.
* - If receiving a transaction outside a block, assign its timestamp to the
* current time.
* - If receiving a block with a future timestamp, assign all its (not already
* known) transactions' timestamps to the current time.
* - If receiving a block with a past timestamp, before the most recent known
* transaction (that we care about), assign all its (not already known)
* transactions' timestamps to the same timestamp as that most-recent-known
* transaction.
* - If receiving a block with a past timestamp, but after the most recent known
* transaction, assign all its (not already known) transactions' timestamps to
* the block time.
*
* For more information see CWalletTx::nTimeSmart,
* https://bitcointalk.org/?topic=54527, or
* https://github.com/bitcoin/bitcoin/pull/1393.
*/
unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
{
unsigned int nTimeSmart = wtx.nTimeReceived;
if (!wtx.hashUnset()) {
if (mapBlockIndex.count(wtx.hashBlock)) {
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
const TxItems& txOrdered = wtxOrdered;
for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = it->second.first;
if (pwtx == &wtx) {
continue;
}
CAccountingEntry* const pacentry = it->second.second;
int64_t nSmartTime;
if (pwtx) {
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime) {
nSmartTime = pwtx->nTimeReceived;
}
} else {
nSmartTime = pacentry->nTime;
}
if (nSmartTime <= latestTolerated) {
latestEntry = nSmartTime;
if (nSmartTime > latestNow) {
latestNow = nSmartTime;
}
break;
}
}
int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else {
LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
}
}
return nTimeSmart;
}
bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
if (boost::get<CNoDestination>(&dest))
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
}
bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
}
bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return true;
}
bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
if(i != mapAddressBook.end())
{
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if(j != i->second.destdata.end())
{
if(value)
*value = j->second;
return true;
}
}
return false;
}
std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
{
LOCK(cs_wallet);
std::vector<std::string> values;
for (const auto& address : mapAddressBook) {
for (const auto& data : address.second.destdata) {
if (!data.first.compare(0, prefix.size(), prefix)) {
values.emplace_back(data.second);
}
}
}
return values;
}
CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
{
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
if (gArgs.GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(std::move(dbw));
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
if (nZapWalletRet != DB_LOAD_OK) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
}
uiInterface.InitMessage(_("Loading wallet..."));
int64_t nStart = GetTimeMillis();
bool fFirstRun = true;
std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
CWallet *walletInstance = new CWallet(std::move(dbw));
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."),
walletFile));
}
else if (nLoadWalletRet == DB_TOO_NEW) {
InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
return nullptr;
}
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
return nullptr;
}
else {
InitError(strprintf(_("Error loading %s"), walletFile));
return nullptr;
}
}
if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < walletInstance->GetVersion())
{
InitError(_("Cannot downgrade wallet"));
return nullptr;
}
walletInstance->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
if (!gArgs.GetBoolArg("-usehd", true)) {
InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
return nullptr;
}
walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
// generate a new master key
CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
if (!walletInstance->SetHDMasterKey(masterPubKey))
throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
// Top up the keypool
if (!walletInstance->TopUpKeyPool()) {
InitError(_("Unable to generate initial keys") += "\n");
return nullptr;
}
walletInstance->SetBestChain(chainActive.GetLocator());
}
else if (gArgs.IsArgSet("-usehd")) {
bool useHD = gArgs.GetBoolArg("-usehd", true);
if (walletInstance->IsHDEnabled() && !useHD) {
InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
return nullptr;
}
if (!walletInstance->IsHDEnabled() && useHD) {
InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
return nullptr;
}
}
LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
// Try to top up keypool. No-op if the wallet is locked.
walletInstance->TopUpKeyPool();
CBlockIndex *pindexRescan = chainActive.Genesis();
if (!gArgs.GetBoolArg("-rescan", false))
{
CWalletDB walletdb(*walletInstance->dbw);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = FindForkInGlobalIndex(chainActive, locator);
}
walletInstance->m_last_block_processed = chainActive.Tip();
RegisterValidationInterface(walletInstance);
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{
//We can't rescan beyond non-pruned blocks, stop and throw an error
//this might happen if a user uses an old wallet within a pruned node
// or if he ran -disablewallet for a longer time, then decided to re-enable
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
block = block->pprev;
if (pindexRescan != block) {
InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
return nullptr;
}
}
uiInterface.InitMessage(_("Rescanning..."));
LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
// No need to read and scan block if block was created before
// our wallet birthday (as adjusted for block time variability)
while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
pindexRescan = chainActive.Next(pindexRescan);
}
nStart = GetTimeMillis();
{
WalletRescanReserver reserver(walletInstance);
if (!reserver.reserve()) {
InitError(_("Failed to rescan the wallet during initialization"));
return nullptr;
}
walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, reserver, true);
}
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
walletInstance->SetBestChain(chainActive.GetLocator());
walletInstance->dbw->IncrementUpdateCounter();
// Restore wallet transaction metadata after -zapwallettxes=1
if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
{
CWalletDB walletdb(*walletInstance->dbw);
for (const CWalletTx& wtxOld : vWtx)
{
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
if (mi != walletInstance->mapWallet.end())
{
const CWalletTx* copyFrom = &wtxOld;
CWalletTx* copyTo = &mi->second;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
copyTo->nTimeReceived = copyFrom->nTimeReceived;
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nOrderPos = copyFrom->nOrderPos;
copyTo->nReplayStatus = copyFrom->nReplayStatus;
walletdb.WriteTx(*copyTo);
}
}
}
}
walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
{
LOCK(walletInstance->cs_wallet);
LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
}
return walletInstance;
}
std::atomic<bool> CWallet::fFlushScheduled(false);
void CWallet::postInitProcess(CScheduler& scheduler)
{
// Add wallet transactions that aren't already in a block to mempool
// Do this here as mempool requires genesis block to be loaded
ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
if (!CWallet::fFlushScheduled.exchange(true)) {
scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
}
}
bool CWallet::BackupWallet(const std::string& strDest)
{
return dbw->Backup(strDest);
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
fInternal = false;
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
fInternal = internalIn;
}
CWalletKey::CWalletKey(int64_t nExpires)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
{
// Update the tx's hashBlock
hashBlock = pindex->GetBlockHash();
// set the position of the transaction in the block
nIndex = posInBlock;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
{
if (hashUnset())
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
pindexRet = pindex;
return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (tx->IsCoinBase())
return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
//else
//if (!tx->criticalData.IsNull()) {
// return std::max(0, (CRITICAL_DATA_MATURITY+1) - GetDepthInMainChain());
//}
return 0;
}
bool CWalletTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
{
// Quick check to avoid re-setting fInMempool to false
if (mempool.exists(tx->GetHash())) {
return state.DoS(0, false, REJECT_INVALID, "txn-already-in-mempool");
}
// We must set fInMempool here - while it will be re-set to true by the
// entered-mempool callback, if we did not there would be a race where a
// user could call sendmoney in a loop and hit spurious out of funds errors
// because we think that the transaction they just generated's change is
// unavailable as we're not yet aware its in mempool.
bool pfMissingInputs = false;
bool ret = ::AcceptToMemoryPool(mempool, state, tx, &pfMissingInputs,
nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
fInMempool = ret;
if (pfMissingInputs == true) {
return state.DoS(0, false, REJECT_INVALID, "tx-missing-inputs");
}
return ret;
}
static const std::string OUTPUT_TYPE_STRING_LEGACY = "legacy";
static const std::string OUTPUT_TYPE_STRING_P2SH_SEGWIT = "p2sh-segwit";
static const std::string OUTPUT_TYPE_STRING_BECH32 = "bech32";
OutputType ParseOutputType(const std::string& type, OutputType default_type)
{
if (type.empty()) {
return default_type;
} else if (type == OUTPUT_TYPE_STRING_LEGACY) {
return OUTPUT_TYPE_LEGACY;
} else if (type == OUTPUT_TYPE_STRING_P2SH_SEGWIT) {
return OUTPUT_TYPE_P2SH_SEGWIT;
} else if (type == OUTPUT_TYPE_STRING_BECH32) {
return OUTPUT_TYPE_BECH32;
} else {
return OUTPUT_TYPE_NONE;
}
}
const std::string& FormatOutputType(OutputType type)
{
switch (type) {
case OUTPUT_TYPE_LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
case OUTPUT_TYPE_P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
case OUTPUT_TYPE_BECH32: return OUTPUT_TYPE_STRING_BECH32;
default: assert(false);
}
}
void CWallet::LearnRelatedScripts(const CPubKey& key, OutputType type)
{
if (key.IsCompressed() && (type == OUTPUT_TYPE_P2SH_SEGWIT || type == OUTPUT_TYPE_BECH32)) {
CTxDestination witdest = WitnessV0KeyHash(key.GetID());
CScript witprog = GetScriptForDestination(witdest);
// Make sure the resulting program is solvable.
assert(IsSolvable(*this, witprog));
AddCScript(witprog);
}
}
void CWallet::LearnAllRelatedScripts(const CPubKey& key)
{
// OUTPUT_TYPE_P2SH_SEGWIT always adds all necessary scripts for all types.
LearnRelatedScripts(key, OUTPUT_TYPE_P2SH_SEGWIT);
}
CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type)
{
switch (type) {
case OUTPUT_TYPE_LEGACY: return key.GetID();
case OUTPUT_TYPE_P2SH_SEGWIT:
case OUTPUT_TYPE_BECH32: {
if (!key.IsCompressed()) return key.GetID();
CTxDestination witdest = WitnessV0KeyHash(key.GetID());
CScript witprog = GetScriptForDestination(witdest);
if (type == OUTPUT_TYPE_P2SH_SEGWIT) {
return CScriptID(witprog);
} else {
return witdest;
}
}
default: assert(false);
}
}
std::vector<CTxDestination> GetAllDestinationsForKey(const CPubKey& key)
{
CKeyID keyid = key.GetID();
if (key.IsCompressed()) {
CTxDestination segwit = WitnessV0KeyHash(keyid);
CTxDestination p2sh = CScriptID(GetScriptForDestination(segwit));
return std::vector<CTxDestination>{std::move(keyid), std::move(p2sh), std::move(segwit)};
} else {
return std::vector<CTxDestination>{std::move(keyid)};
}
}
CTxDestination CWallet::AddAndGetDestinationForScript(const CScript& script, OutputType type)
{
// Note that scripts over 520 bytes are not yet supported.
switch (type) {
case OUTPUT_TYPE_LEGACY:
return CScriptID(script);
case OUTPUT_TYPE_P2SH_SEGWIT:
case OUTPUT_TYPE_BECH32: {
WitnessV0ScriptHash hash;
CSHA256().Write(script.data(), script.size()).Finalize(hash.begin());
CTxDestination witdest = hash;
CScript witprog = GetScriptForDestination(witdest);
// Check if the resulting program is solvable (i.e. doesn't use an uncompressed key)
if (!IsSolvable(*this, witprog)) return CScriptID(script);
// Add the redeemscript, so that P2WSH and P2SH-P2WSH outputs are recognized as ours.
AddCScript(witprog);
if (type == OUTPUT_TYPE_BECH32) {
return witdest;
} else {
return CScriptID(witprog);
}
}
default: assert(false);
}
}
int CWallet::GetReplayStatus(const uint256& txid)
{
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it != mapWallet.end()) {
if (it->second.tx->nVersion == 4)
return REPLAY_SPLIT;
else
return it->second.GetReplayStatus();
}
return REPLAY_UNKNOWN;
}
void CWallet::UpdateReplayStatus(const uint256& txid, const int nReplayStatus)
{
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return;
// Update the object
it->second.UpdateReplayStatus(nReplayStatus);
// Write to db
CWalletDB walletdb(*dbw, "r+");
if (!walletdb.WriteTx(it->second))
LogPrintf("%s: Updating walletdb tx %s failed", __func__, it->second.GetHash().ToString());
NotifyTransactionChanged(this, txid, CT_UPDATED);
}
|
#include <iostream>
int route[10][10]
void dfs(int **);
void dfs(int **Map, int need, int x, int y) {
for (int i = 0; i < 4; i++) {
switch (i)
case 0:
dfs(Map, need, x + 1, y);
break;
case 1:
dfs(Map, need, x -1, y);
break;
case 2:
dfs(Map, need, x, y + 1);
case 3:
dfs(Map, need, x, y - 1);
default:
break;
}
}
|
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "mosek_guarded.h"
IGL_INLINE MSKrescodee igl::mosek::mosek_guarded(const MSKrescodee r)
{
using namespace std;
if(r != MSK_RES_OK)
{
/* In case of an error print error code and description. */
char symname[MSK_MAX_STR_LEN];
char desc[MSK_MAX_STR_LEN];
MSK_getcodedesc(r,symname,desc);
cerr<<"MOSEK ERROR ("<<r<<"): "<<symname<<" - '"<<desc<<"'"<<endl;
}
return r;
}
|
//
// audioexport.cpp
// MDStudio
//
// Created by Daniel Cliche on 2015-08-29.
// Copyright (c) 2015-2020 Daniel Cliche. All rights reserved.
//
#include "audioexport.h"
#include "platform.h"
extern "C" {
#include <libaiff/libaiff.h>
}
using namespace MDStudio;
// ---------------------------------------------------------------------------------------------------------------------
AudioExport::AudioExport(Sequencer* sequencer) : _sequencer(sequencer) {
_audioExportDidStartFn = nullptr;
_audioExportDidSetProgressFn = nullptr;
_audioExportDidFinishFn = nullptr;
}
// ---------------------------------------------------------------------------------------------------------------------
AudioExport::~AudioExport() {
if (_exportAudioThread.joinable()) {
_isAborted = true;
_exportAudioThread.join();
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Audio export thread
void AudioExport::exportAudioThread() {
AIFF_Ref exportAudioAIFFRef = static_cast<AIFF_Ref>(_exportAudioAIFFRef);
Metronome::timePointType startTime = std::chrono::high_resolution_clock::now();
Metronome::timePointType currentTime = startTime;
Metronome::doublePrecisionDurationType period = Metronome::doublePrecisionDurationType(1.0 / 44100.0);
AIFF_SetAudioFormat(exportAudioAIFFRef, 2, 44100.0, 16);
AIFF_StartWritingSamples(exportAudioAIFFRef);
bool isDone = false;
bool isMetronomeDone = false;
int nbFramesAtEnd = 44100;
float lastProgress = 0.0f;
while (!isDone && !_isAborted) {
if (!isMetronomeDone) {
if (!_sequencer->studio()->metronome()->performTick(startTime, currentTime)) isMetronomeDone = true;
}
GraphSampleType outA, outB;
GraphSampleType* ioData[2];
ioData[0] = &outA;
ioData[1] = &outB;
// Render a single frame
_sequencer->studio()->mixer()->renderInput(1, ioData, 1);
int32_t samples[2] = {(int32_t)(outA * 2147483647.0f), (int32_t)(outB * 2147483647.0f)};
AIFF_WriteSamples32Bit(exportAudioAIFFRef, samples, 2);
currentTime += period;
if (isMetronomeDone) {
if (nbFramesAtEnd == 0) {
isDone = true;
} else {
nbFramesAtEnd--;
}
} else {
float progress =
static_cast<float>(_sequencer->studio()->metronome()->tick()) / static_cast<float>(_totalNbTicks);
if (progress - lastProgress > 0.01f) {
Platform::sharedInstance()->invoke([=] { setProgress(progress); });
lastProgress = progress;
}
}
}
AIFF_EndWritingSamples(exportAudioAIFFRef);
Platform::sharedInstance()->invoke([=] { exportAudioCompleted(); });
}
// ---------------------------------------------------------------------------------------------------------------------
bool AudioExport::exportAudio(const std::string& path) {
if (_audioExportDidStartFn) _audioExportDidStartFn(this);
// Calculate the total nb of ticks
_totalNbTicks = 0;
for (auto& track : _sequencer->sequence()->data.tracks) {
UInt32 totalNbTicksInTrack = 0;
for (auto event : track.events) totalNbTicksInTrack += event.tickCount;
if (totalNbTicksInTrack > _totalNbTicks) _totalNbTicks = totalNbTicksInTrack;
}
_sequencer->stop();
_sequencer->studio()->metronome()->moveToTick(0);
_previousMasterMixerLevel = _sequencer->studio()->masterMixerLevel();
_sequencer->studio()->setMasterMixerLevel(STUDIO_SOURCE_USER, 0.5f);
_exportAudioAIFFRef = AIFF_OpenFile(path.c_str(), F_WRONLY);
if (_exportAudioAIFFRef == nullptr) return false;
// Start the sequencer for audio export
_sequencer->playAudioExport();
// Create a new audio export thread
_isAborted = false;
_exportAudioThread = std::thread(&AudioExport::exportAudioThread, this);
return true;
}
// ---------------------------------------------------------------------------------------------------------------------
void AudioExport::exportAudioCompleted() {
_exportAudioThread.join();
AIFF_Ref exportAudioAIFFRef = static_cast<AIFF_Ref>(_exportAudioAIFFRef);
AIFF_CloseFile(exportAudioAIFFRef);
_sequencer->studio()->setMasterMixerLevel(STUDIO_SOURCE_USER, _previousMasterMixerLevel);
if (_audioExportDidFinishFn) _audioExportDidFinishFn(this);
}
// ---------------------------------------------------------------------------------------------------------------------
void AudioExport::setProgress(float progress) {
if (_audioExportDidSetProgressFn) _audioExportDidSetProgressFn(this, progress);
}
|
/*
* Copyright 2017 MapD Technologies, 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 "RelAlgOptimizer.h"
#include "RexVisitor.h"
#include "Shared/Logger.h"
#include "Visitors/RexSubQueryIdCollector.h"
#include <numeric>
#include <string>
#include <unordered_map>
namespace {
class RexProjectInputRedirector : public RexDeepCopyVisitor {
public:
RexProjectInputRedirector(const std::unordered_set<const RelProject*>& crt_inputs)
: crt_projects_(crt_inputs) {}
RetType visitInput(const RexInput* input) const override {
auto source = dynamic_cast<const RelProject*>(input->getSourceNode());
if (!source || !crt_projects_.count(source)) {
return input->deepCopy();
}
auto new_source = source->getInput(0);
auto new_input =
dynamic_cast<const RexInput*>(source->getProjectAt(input->getIndex()));
if (!new_input) {
return input->deepCopy();
}
if (auto join = dynamic_cast<const RelJoin*>(new_source)) {
CHECK(new_input->getSourceNode() == join->getInput(0) ||
new_input->getSourceNode() == join->getInput(1));
} else {
CHECK_EQ(new_input->getSourceNode(), new_source);
}
return new_input->deepCopy();
}
private:
const std::unordered_set<const RelProject*>& crt_projects_;
};
class RexRebindInputsVisitor : public RexVisitor<void*> {
public:
RexRebindInputsVisitor(const RelAlgNode* old_input, const RelAlgNode* new_input)
: old_input_(old_input), new_input_(new_input) {}
void* visitInput(const RexInput* rex_input) const override {
const auto old_source = rex_input->getSourceNode();
if (old_source == old_input_) {
rex_input->setSourceNode(new_input_);
}
return nullptr;
};
void visitNode(const RelAlgNode* node) const {
if (dynamic_cast<const RelAggregate*>(node) || dynamic_cast<const RelSort*>(node)) {
return;
}
if (auto join = dynamic_cast<const RelJoin*>(node)) {
if (auto condition = join->getCondition()) {
visit(condition);
}
return;
}
if (auto project = dynamic_cast<const RelProject*>(node)) {
for (size_t i = 0; i < project->size(); ++i) {
visit(project->getProjectAt(i));
}
return;
}
if (auto filter = dynamic_cast<const RelFilter*>(node)) {
visit(filter->getCondition());
return;
}
CHECK(false);
}
private:
const RelAlgNode* old_input_;
const RelAlgNode* new_input_;
};
size_t get_actual_source_size(
const RelProject* curr_project,
const std::unordered_set<const RelProject*>& projects_to_remove) {
auto source = curr_project->getInput(0);
while (auto filter = dynamic_cast<const RelFilter*>(source)) {
source = filter->getInput(0);
}
if (auto src_project = dynamic_cast<const RelProject*>(source)) {
if (projects_to_remove.count(src_project)) {
return get_actual_source_size(src_project, projects_to_remove);
}
}
return curr_project->getInput(0)->size();
}
bool safe_to_redirect(
const RelProject* project,
const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web) {
if (!project->isSimple()) {
return false;
}
auto usrs_it = du_web.find(project);
CHECK(usrs_it != du_web.end());
for (auto usr : usrs_it->second) {
if (!dynamic_cast<const RelProject*>(usr) && !dynamic_cast<const RelFilter*>(usr)) {
return false;
}
}
return true;
}
bool is_identical_copy(
const RelProject* project,
const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web,
const std::unordered_set<const RelProject*>& projects_to_remove,
std::unordered_set<const RelProject*>& permutating_projects) {
auto source_size = get_actual_source_size(project, projects_to_remove);
if (project->size() > source_size) {
return false;
}
if (project->size() < source_size) {
auto usrs_it = du_web.find(project);
CHECK(usrs_it != du_web.end());
bool guard_found = false;
while (usrs_it->second.size() == size_t(1)) {
auto only_usr = *usrs_it->second.begin();
if (dynamic_cast<const RelProject*>(only_usr)) {
guard_found = true;
break;
}
if (dynamic_cast<const RelAggregate*>(only_usr) ||
dynamic_cast<const RelSort*>(only_usr) ||
dynamic_cast<const RelJoin*>(only_usr) ||
dynamic_cast<const RelTableFunction*>(only_usr) ||
dynamic_cast<const RelLogicalUnion*>(only_usr)) {
return false;
}
CHECK(dynamic_cast<const RelFilter*>(only_usr))
<< "only_usr: " << only_usr->toString();
usrs_it = du_web.find(only_usr);
CHECK(usrs_it != du_web.end());
}
if (!guard_found) {
return false;
}
}
bool identical = true;
for (size_t i = 0; i < project->size(); ++i) {
auto target = dynamic_cast<const RexInput*>(project->getProjectAt(i));
CHECK(target);
if (i != target->getIndex()) {
identical = false;
break;
}
}
if (identical) {
return true;
}
if (safe_to_redirect(project, du_web)) {
permutating_projects.insert(project);
return true;
}
return false;
}
void propagate_rex_input_renumber(
const RelFilter* excluded_root,
const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web) {
CHECK(excluded_root);
auto src_project = dynamic_cast<const RelProject*>(excluded_root->getInput(0));
CHECK(src_project && src_project->isSimple());
const auto indirect_join_src = dynamic_cast<const RelJoin*>(src_project->getInput(0));
std::unordered_map<size_t, size_t> old_to_new_idx;
for (size_t i = 0; i < src_project->size(); ++i) {
auto rex_in = dynamic_cast<const RexInput*>(src_project->getProjectAt(i));
CHECK(rex_in);
size_t src_base = 0;
if (indirect_join_src != nullptr &&
indirect_join_src->getInput(1) == rex_in->getSourceNode()) {
src_base = indirect_join_src->getInput(0)->size();
}
old_to_new_idx.insert(std::make_pair(i, src_base + rex_in->getIndex()));
old_to_new_idx.insert(std::make_pair(i, rex_in->getIndex()));
}
CHECK(old_to_new_idx.size());
RexInputRenumber<false> renumber(old_to_new_idx);
auto usrs_it = du_web.find(excluded_root);
CHECK(usrs_it != du_web.end());
std::vector<const RelAlgNode*> work_set(usrs_it->second.begin(), usrs_it->second.end());
while (!work_set.empty()) {
auto node = work_set.back();
work_set.pop_back();
auto modified_node = const_cast<RelAlgNode*>(node);
if (auto filter = dynamic_cast<RelFilter*>(modified_node)) {
auto new_condition = renumber.visit(filter->getCondition());
filter->setCondition(new_condition);
auto usrs_it = du_web.find(filter);
CHECK(usrs_it != du_web.end() && usrs_it->second.size() == 1);
work_set.push_back(*usrs_it->second.begin());
continue;
}
if (auto project = dynamic_cast<RelProject*>(modified_node)) {
std::vector<std::unique_ptr<const RexScalar>> new_exprs;
for (size_t i = 0; i < project->size(); ++i) {
new_exprs.push_back(renumber.visit(project->getProjectAt(i)));
}
project->setExpressions(new_exprs);
continue;
}
CHECK(false);
}
}
// This function appears to redirect/remove redundant Projection input nodes(?)
void redirect_inputs_of(
std::shared_ptr<RelAlgNode> node,
const std::unordered_set<const RelProject*>& projects,
const std::unordered_set<const RelProject*>& permutating_projects,
const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web) {
if (dynamic_cast<RelLogicalUnion*>(node.get())) {
return; // UNION keeps all Projection inputs.
}
std::shared_ptr<const RelProject> src_project = nullptr;
for (size_t i = 0; i < node->inputCount(); ++i) {
if (auto project =
std::dynamic_pointer_cast<const RelProject>(node->getAndOwnInput(i))) {
if (projects.count(project.get())) {
src_project = project;
break;
}
}
}
if (!src_project) {
return;
}
if (auto join = std::dynamic_pointer_cast<RelJoin>(node)) {
auto other_project =
src_project == node->getAndOwnInput(0)
? std::dynamic_pointer_cast<const RelProject>(node->getAndOwnInput(1))
: std::dynamic_pointer_cast<const RelProject>(node->getAndOwnInput(0));
join->replaceInput(src_project, src_project->getAndOwnInput(0));
RexRebindInputsVisitor rebinder(src_project.get(), src_project->getInput(0));
auto usrs_it = du_web.find(join.get());
CHECK(usrs_it != du_web.end());
for (auto usr : usrs_it->second) {
rebinder.visitNode(usr);
}
if (other_project && projects.count(other_project.get())) {
join->replaceInput(other_project, other_project->getAndOwnInput(0));
RexRebindInputsVisitor other_rebinder(other_project.get(),
other_project->getInput(0));
for (auto usr : usrs_it->second) {
other_rebinder.visitNode(usr);
}
}
return;
}
if (auto project = std::dynamic_pointer_cast<RelProject>(node)) {
project->RelAlgNode::replaceInput(src_project, src_project->getAndOwnInput(0));
RexProjectInputRedirector redirector(projects);
std::vector<std::unique_ptr<const RexScalar>> new_exprs;
for (size_t i = 0; i < project->size(); ++i) {
new_exprs.push_back(redirector.visit(project->getProjectAt(i)));
}
project->setExpressions(new_exprs);
return;
}
if (auto filter = std::dynamic_pointer_cast<RelFilter>(node)) {
const bool is_permutating_proj = permutating_projects.count(src_project.get());
if (is_permutating_proj || dynamic_cast<const RelJoin*>(src_project->getInput(0))) {
if (is_permutating_proj) {
propagate_rex_input_renumber(filter.get(), du_web);
}
filter->RelAlgNode::replaceInput(src_project, src_project->getAndOwnInput(0));
RexProjectInputRedirector redirector(projects);
auto new_condition = redirector.visit(filter->getCondition());
filter->setCondition(new_condition);
} else {
filter->replaceInput(src_project, src_project->getAndOwnInput(0));
}
return;
}
if (std::dynamic_pointer_cast<RelSort>(node)) {
auto const src_project_input = src_project->getInput(0);
if (dynamic_cast<const RelScan*>(src_project_input) ||
dynamic_cast<const RelLogicalValues*>(src_project_input) ||
dynamic_cast<const RelLogicalUnion*>(src_project_input)) {
return;
}
}
if (std::dynamic_pointer_cast<RelModify>(node)) {
return; // NOTE: Review this. Not sure about this.
}
CHECK(std::dynamic_pointer_cast<RelAggregate>(node) ||
std::dynamic_pointer_cast<RelSort>(node));
node->replaceInput(src_project, src_project->getAndOwnInput(0));
}
void cleanup_dead_nodes(std::vector<std::shared_ptr<RelAlgNode>>& nodes) {
for (auto nodeIt = nodes.rbegin(); nodeIt != nodes.rend(); ++nodeIt) {
if (nodeIt->unique()) {
LOG(INFO) << "ID=" << (*nodeIt)->getId() << " " << (*nodeIt)->toString()
<< " deleted!";
nodeIt->reset();
}
}
std::vector<std::shared_ptr<RelAlgNode>> new_nodes;
for (auto node : nodes) {
if (!node) {
continue;
}
new_nodes.push_back(node);
}
nodes.swap(new_nodes);
}
std::unordered_set<const RelProject*> get_visible_projects(const RelAlgNode* root) {
if (auto project = dynamic_cast<const RelProject*>(root)) {
return {project};
}
if (dynamic_cast<const RelAggregate*>(root) || dynamic_cast<const RelScan*>(root) ||
dynamic_cast<const RelLogicalValues*>(root) ||
dynamic_cast<const RelModify*>(root)) {
return std::unordered_set<const RelProject*>{};
}
if (auto join = dynamic_cast<const RelJoin*>(root)) {
auto lhs_projs = get_visible_projects(join->getInput(0));
auto rhs_projs = get_visible_projects(join->getInput(1));
lhs_projs.insert(rhs_projs.begin(), rhs_projs.end());
return lhs_projs;
}
if (auto logical_union = dynamic_cast<const RelLogicalUnion*>(root)) {
auto projections = get_visible_projects(logical_union->getInput(0));
for (size_t i = 1; i < logical_union->inputCount(); ++i) {
auto next = get_visible_projects(logical_union->getInput(i));
projections.insert(next.begin(), next.end());
}
return projections;
}
CHECK(dynamic_cast<const RelFilter*>(root) || dynamic_cast<const RelSort*>(root))
<< "root = " << root->toString();
return get_visible_projects(root->getInput(0));
}
// TODO(miyu): checking this at runtime is more accurate
bool is_distinct(const size_t input_idx, const RelAlgNode* node) {
if (dynamic_cast<const RelFilter*>(node) || dynamic_cast<const RelSort*>(node)) {
CHECK_EQ(size_t(1), node->inputCount());
return is_distinct(input_idx, node->getInput(0));
}
if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
CHECK_EQ(size_t(1), node->inputCount());
if (aggregate->getGroupByCount() == 1 && !input_idx) {
return true;
}
if (input_idx < aggregate->getGroupByCount()) {
return is_distinct(input_idx, node->getInput(0));
}
return false;
}
if (auto project = dynamic_cast<const RelProject*>(node)) {
CHECK_LT(input_idx, project->size());
if (auto input = dynamic_cast<const RexInput*>(project->getProjectAt(input_idx))) {
CHECK_EQ(size_t(1), node->inputCount());
return is_distinct(input->getIndex(), project->getInput(0));
}
return false;
}
CHECK(dynamic_cast<const RelJoin*>(node) || dynamic_cast<const RelScan*>(node));
return false;
}
} // namespace
std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>> build_du_web(
const std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>> web;
std::unordered_set<const RelAlgNode*> visited;
std::vector<const RelAlgNode*> work_set;
for (auto node : nodes) {
if (std::dynamic_pointer_cast<RelScan>(node) ||
std::dynamic_pointer_cast<RelModify>(node) || visited.count(node.get())) {
continue;
}
work_set.push_back(node.get());
while (!work_set.empty()) {
auto walker = work_set.back();
work_set.pop_back();
if (visited.count(walker)) {
continue;
}
CHECK(!web.count(walker));
auto it_ok =
web.insert(std::make_pair(walker, std::unordered_set<const RelAlgNode*>{}));
CHECK(it_ok.second);
visited.insert(walker);
CHECK(dynamic_cast<const RelJoin*>(walker) ||
dynamic_cast<const RelProject*>(walker) ||
dynamic_cast<const RelAggregate*>(walker) ||
dynamic_cast<const RelFilter*>(walker) ||
dynamic_cast<const RelSort*>(walker) ||
dynamic_cast<const RelLeftDeepInnerJoin*>(walker) ||
dynamic_cast<const RelLogicalValues*>(walker) ||
dynamic_cast<const RelTableFunction*>(walker) ||
dynamic_cast<const RelLogicalUnion*>(walker));
for (size_t i = 0; i < walker->inputCount(); ++i) {
auto src = walker->getInput(i);
if (dynamic_cast<const RelScan*>(src) || dynamic_cast<const RelModify*>(src)) {
continue;
}
if (web.empty() || !web.count(src)) {
web.insert(std::make_pair(src, std::unordered_set<const RelAlgNode*>{}));
}
web[src].insert(walker);
work_set.push_back(src);
}
}
}
return web;
}
/**
* Return true if the input project separates two sort nodes, i.e. Sort -> Project ->
* Sort. This pattern often occurs in machine generated SQL, e.g. SELECT * FROM (SELECT *
* FROM t LIMIT 10) t0 LIMIT 1;
* Use this function to prevent optimizing out the intermediate project, as the project is
* required to ensure the first sort runs to completion prior to the second sort. Back to
* back sort nodes are not executable and will throw an error.
*/
bool project_separates_sort(const RelProject* project, const RelAlgNode* next_node) {
CHECK(project);
if (!next_node) {
return false;
}
auto sort = dynamic_cast<const RelSort*>(next_node);
if (!sort) {
return false;
}
if (!(project->inputCount() == 1)) {
return false;
}
if (dynamic_cast<const RelSort*>(project->getInput(0))) {
return true;
}
return false;
}
// For now, the only target to eliminate is restricted to project-aggregate pair between
// scan/sort and join
// TODO(miyu): allow more chance if proved safe
void eliminate_identical_copy(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
std::unordered_set<std::shared_ptr<const RelAlgNode>> copies;
auto sink = nodes.back();
for (auto node : nodes) {
auto aggregate = std::dynamic_pointer_cast<const RelAggregate>(node);
if (!aggregate || aggregate == sink ||
!(aggregate->getGroupByCount() == 1 && aggregate->getAggExprsCount() == 0)) {
continue;
}
auto project =
std::dynamic_pointer_cast<const RelProject>(aggregate->getAndOwnInput(0));
if (project && project->size() == aggregate->size() &&
project->getFields() == aggregate->getFields()) {
CHECK_EQ(size_t(0), copies.count(aggregate));
copies.insert(aggregate);
}
}
for (auto node : nodes) {
if (!node->inputCount()) {
continue;
}
auto last_source = node->getAndOwnInput(node->inputCount() - 1);
if (!copies.count(last_source)) {
continue;
}
auto aggregate = std::dynamic_pointer_cast<const RelAggregate>(last_source);
CHECK(aggregate);
if (!std::dynamic_pointer_cast<const RelJoin>(node) || aggregate->size() != 1) {
continue;
}
auto project =
std::dynamic_pointer_cast<const RelProject>(aggregate->getAndOwnInput(0));
CHECK(project);
CHECK_EQ(size_t(1), project->size());
if (!is_distinct(size_t(0), project.get())) {
continue;
}
auto new_source = project->getAndOwnInput(0);
if (std::dynamic_pointer_cast<const RelSort>(new_source) ||
std::dynamic_pointer_cast<const RelScan>(new_source)) {
node->replaceInput(last_source, new_source);
}
}
decltype(copies)().swap(copies);
auto web = build_du_web(nodes);
std::unordered_set<const RelProject*> projects;
std::unordered_set<const RelProject*> permutating_projects;
auto const visible_projs = get_visible_projects(nodes.back().get());
for (auto node_it = nodes.begin(); node_it != nodes.end(); node_it++) {
auto node = *node_it;
auto project = std::dynamic_pointer_cast<RelProject>(node);
auto next_node_it = std::next(node_it);
if (project && project->isSimple() &&
(!visible_projs.count(project.get()) || !project->isRenaming()) &&
is_identical_copy(project.get(), web, projects, permutating_projects) &&
!project_separates_sort(
project.get(), next_node_it == nodes.end() ? nullptr : next_node_it->get())) {
projects.insert(project.get());
}
}
for (auto node : nodes) {
redirect_inputs_of(node, projects, permutating_projects, web);
}
cleanup_dead_nodes(nodes);
}
namespace {
class RexInputCollector : public RexVisitor<std::unordered_set<RexInput>> {
private:
const RelAlgNode* node_;
protected:
using RetType = std::unordered_set<RexInput>;
RetType aggregateResult(const RetType& aggregate,
const RetType& next_result) const override {
RetType result(aggregate.begin(), aggregate.end());
result.insert(next_result.begin(), next_result.end());
return result;
}
public:
RexInputCollector(const RelAlgNode* node) : node_(node) {}
RetType visitInput(const RexInput* input) const override {
RetType result;
if (node_->inputCount() == 1) {
auto src = node_->getInput(0);
if (auto join = dynamic_cast<const RelJoin*>(src)) {
CHECK_EQ(join->inputCount(), size_t(2));
const auto src2_in_offset = join->getInput(0)->size();
if (input->getSourceNode() == join->getInput(1)) {
result.emplace(src, input->getIndex() + src2_in_offset);
} else {
result.emplace(src, input->getIndex());
}
return result;
}
}
result.insert(*input);
return result;
}
};
size_t pick_always_live_col_idx(const RelAlgNode* node) {
CHECK(node->size());
RexInputCollector collector(node);
if (auto filter = dynamic_cast<const RelFilter*>(node)) {
auto rex_ins = collector.visit(filter->getCondition());
if (!rex_ins.empty()) {
return static_cast<size_t>(rex_ins.begin()->getIndex());
}
return pick_always_live_col_idx(filter->getInput(0));
} else if (auto join = dynamic_cast<const RelJoin*>(node)) {
auto rex_ins = collector.visit(join->getCondition());
if (!rex_ins.empty()) {
return static_cast<size_t>(rex_ins.begin()->getIndex());
}
if (auto lhs_idx = pick_always_live_col_idx(join->getInput(0))) {
return lhs_idx;
}
if (auto rhs_idx = pick_always_live_col_idx(join->getInput(0))) {
return rhs_idx + join->getInput(0)->size();
}
} else if (auto sort = dynamic_cast<const RelSort*>(node)) {
if (sort->collationCount()) {
return sort->getCollation(0).getField();
}
return pick_always_live_col_idx(sort->getInput(0));
}
return size_t(0);
}
std::vector<std::unordered_set<size_t>> get_live_ins(
const RelAlgNode* node,
const std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& live_outs) {
if (!node || dynamic_cast<const RelScan*>(node)) {
return {};
}
RexInputCollector collector(node);
auto it = live_outs.find(node);
CHECK(it != live_outs.end());
auto live_out = it->second;
if (auto project = dynamic_cast<const RelProject*>(node)) {
CHECK_EQ(size_t(1), project->inputCount());
std::unordered_set<size_t> live_in;
for (const auto& idx : live_out) {
CHECK_LT(idx, project->size());
auto partial_in = collector.visit(project->getProjectAt(idx));
for (auto rex_in : partial_in) {
live_in.insert(rex_in.getIndex());
}
}
if (project->size() == 1 &&
dynamic_cast<const RexLiteral*>(project->getProjectAt(0))) {
CHECK(live_in.empty());
live_in.insert(pick_always_live_col_idx(project->getInput(0)));
}
return {live_in};
}
if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
CHECK_EQ(size_t(1), aggregate->inputCount());
const auto group_key_count = static_cast<size_t>(aggregate->getGroupByCount());
const auto agg_expr_count = static_cast<size_t>(aggregate->getAggExprsCount());
std::unordered_set<size_t> live_in;
for (size_t i = 0; i < group_key_count; ++i) {
live_in.insert(i);
}
bool has_count_star_only{false};
for (const auto& idx : live_out) {
if (idx < group_key_count) {
continue;
}
const auto agg_idx = idx - group_key_count;
CHECK_LT(agg_idx, agg_expr_count);
const auto& cur_agg_expr = aggregate->getAggExprs()[agg_idx];
const auto n_operands = cur_agg_expr->size();
for (size_t i = 0; i < n_operands; ++i) {
live_in.insert(static_cast<size_t>(cur_agg_expr->getOperand(i)));
}
if (n_operands == 0) {
has_count_star_only = true;
}
}
if (has_count_star_only && !group_key_count) {
live_in.insert(size_t(0));
}
return {live_in};
}
if (auto join = dynamic_cast<const RelJoin*>(node)) {
std::unordered_set<size_t> lhs_live_ins;
std::unordered_set<size_t> rhs_live_ins;
CHECK_EQ(size_t(2), join->inputCount());
auto lhs = join->getInput(0);
auto rhs = join->getInput(1);
const auto rhs_idx_base = lhs->size();
for (const auto idx : live_out) {
if (idx < rhs_idx_base) {
lhs_live_ins.insert(idx);
} else {
rhs_live_ins.insert(idx - rhs_idx_base);
}
}
auto rex_ins = collector.visit(join->getCondition());
for (const auto& rex_in : rex_ins) {
const auto in_idx = static_cast<size_t>(rex_in.getIndex());
if (rex_in.getSourceNode() == lhs) {
lhs_live_ins.insert(in_idx);
continue;
}
if (rex_in.getSourceNode() == rhs) {
rhs_live_ins.insert(in_idx);
continue;
}
CHECK(false);
}
return {lhs_live_ins, rhs_live_ins};
}
if (auto sort = dynamic_cast<const RelSort*>(node)) {
CHECK_EQ(size_t(1), sort->inputCount());
std::unordered_set<size_t> live_in(live_out.begin(), live_out.end());
for (size_t i = 0; i < sort->collationCount(); ++i) {
live_in.insert(sort->getCollation(i).getField());
}
return {live_in};
}
if (auto filter = dynamic_cast<const RelFilter*>(node)) {
CHECK_EQ(size_t(1), filter->inputCount());
std::unordered_set<size_t> live_in(live_out.begin(), live_out.end());
auto rex_ins = collector.visit(filter->getCondition());
for (const auto& rex_in : rex_ins) {
live_in.insert(static_cast<size_t>(rex_in.getIndex()));
}
return {live_in};
}
if (auto table_func = dynamic_cast<const RelTableFunction*>(node)) {
const auto input_count = table_func->size();
std::unordered_set<size_t> live_in;
for (size_t i = 0; i < input_count; i++) {
live_in.insert(i);
}
std::vector<std::unordered_set<size_t>> result;
// Is the computed result correct in general?
for (size_t i = table_func->inputCount(); i > 0; i--) {
result.push_back(live_in);
}
return result;
}
if (auto logical_union = dynamic_cast<const RelLogicalUnion*>(node)) {
return std::vector<std::unordered_set<size_t>>(logical_union->inputCount(), live_out);
}
return {};
}
bool any_dead_col_in(const RelAlgNode* node,
const std::unordered_set<size_t>& live_outs) {
CHECK(!dynamic_cast<const RelScan*>(node));
if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
for (size_t i = aggregate->getGroupByCount(); i < aggregate->size(); ++i) {
if (!live_outs.count(i)) {
return true;
}
}
return false;
}
return node->size() > live_outs.size();
}
bool does_redef_cols(const RelAlgNode* node) {
return dynamic_cast<const RelAggregate*>(node) || dynamic_cast<const RelProject*>(node);
}
class AvailabilityChecker {
public:
AvailabilityChecker(
const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
liveouts,
const std::unordered_set<const RelAlgNode*>& intact_nodes)
: liveouts_(liveouts), intact_nodes_(intact_nodes) {}
bool hasAllSrcReady(const RelAlgNode* node) const {
for (size_t i = 0; i < node->inputCount(); ++i) {
auto src = node->getInput(i);
if (!dynamic_cast<const RelScan*>(src) && liveouts_.find(src) == liveouts_.end() &&
!intact_nodes_.count(src)) {
return false;
}
}
return true;
}
private:
const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
liveouts_;
const std::unordered_set<const RelAlgNode*>& intact_nodes_;
};
void add_new_indices_for(
const RelAlgNode* node,
std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
new_liveouts,
const std::unordered_set<size_t>& old_liveouts,
const std::unordered_set<const RelAlgNode*>& intact_nodes,
const std::unordered_map<const RelAlgNode*, size_t>& orig_node_sizes) {
auto live_fields = old_liveouts;
if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
for (size_t i = 0; i < aggregate->getGroupByCount(); ++i) {
live_fields.insert(i);
}
}
auto it_ok =
new_liveouts.insert(std::make_pair(node, std::unordered_map<size_t, size_t>{}));
CHECK(it_ok.second);
auto& new_indices = it_ok.first->second;
if (intact_nodes.count(node)) {
for (size_t i = 0, e = node->size(); i < e; ++i) {
new_indices.insert(std::make_pair(i, i));
}
return;
}
if (does_redef_cols(node)) {
auto node_sz_it = orig_node_sizes.find(node);
CHECK(node_sz_it != orig_node_sizes.end());
const auto node_size = node_sz_it->second;
CHECK_GT(node_size, live_fields.size());
LOG(INFO) << node->toString() << " eliminated " << node_size - live_fields.size()
<< " columns.";
std::vector<size_t> ordered_indices(live_fields.begin(), live_fields.end());
std::sort(ordered_indices.begin(), ordered_indices.end());
for (size_t i = 0; i < ordered_indices.size(); ++i) {
new_indices.insert(std::make_pair(ordered_indices[i], i));
}
return;
}
std::vector<size_t> ordered_indices;
for (size_t i = 0, old_base = 0, new_base = 0; i < node->inputCount(); ++i) {
auto src = node->getInput(i);
auto src_renum_it = new_liveouts.find(src);
if (src_renum_it != new_liveouts.end()) {
for (auto m : src_renum_it->second) {
new_indices.insert(std::make_pair(old_base + m.first, new_base + m.second));
}
new_base += src_renum_it->second.size();
} else if (dynamic_cast<const RelScan*>(src) || intact_nodes.count(src)) {
for (size_t i = 0; i < src->size(); ++i) {
new_indices.insert(std::make_pair(old_base + i, new_base + i));
}
new_base += src->size();
} else {
CHECK(false);
}
auto src_sz_it = orig_node_sizes.find(src);
CHECK(src_sz_it != orig_node_sizes.end());
old_base += src_sz_it->second;
}
}
class RexInputRenumberVisitor : public RexDeepCopyVisitor {
public:
RexInputRenumberVisitor(
const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
new_numbering)
: node_to_input_renum_(new_numbering) {}
RetType visitInput(const RexInput* input) const override {
auto source = input->getSourceNode();
auto node_it = node_to_input_renum_.find(source);
if (node_it != node_to_input_renum_.end()) {
auto old_to_new_num = node_it->second;
auto renum_it = old_to_new_num.find(input->getIndex());
CHECK(renum_it != old_to_new_num.end());
return boost::make_unique<RexInput>(source, renum_it->second);
}
return input->deepCopy();
}
private:
const std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
node_to_input_renum_;
};
std::vector<std::unique_ptr<const RexAgg>> renumber_rex_aggs(
std::vector<std::unique_ptr<const RexAgg>>& agg_exprs,
const std::unordered_map<size_t, size_t>& new_numbering) {
std::vector<std::unique_ptr<const RexAgg>> new_exprs;
for (auto& expr : agg_exprs) {
if (expr->size() >= 1) {
auto old_idx = expr->getOperand(0);
auto idx_it = new_numbering.find(old_idx);
if (idx_it != new_numbering.end()) {
std::vector<size_t> operands;
operands.push_back(idx_it->second);
if (expr->size() == 2) {
operands.push_back(expr->getOperand(1));
}
new_exprs.push_back(boost::make_unique<RexAgg>(
expr->getKind(), expr->isDistinct(), expr->getType(), operands));
continue;
}
}
new_exprs.push_back(std::move(expr));
}
return new_exprs;
}
SortField renumber_sort_field(const SortField& old_field,
const std::unordered_map<size_t, size_t>& new_numbering) {
auto field_idx = old_field.getField();
auto idx_it = new_numbering.find(field_idx);
if (idx_it != new_numbering.end()) {
field_idx = idx_it->second;
}
return SortField(field_idx, old_field.getSortDir(), old_field.getNullsPosition());
}
std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>> mark_live_columns(
std::vector<std::shared_ptr<RelAlgNode>>& nodes) {
std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>> live_outs;
std::vector<const RelAlgNode*> work_set;
for (auto node_it = nodes.rbegin(); node_it != nodes.rend(); ++node_it) {
auto node = node_it->get();
if (dynamic_cast<const RelScan*>(node) || live_outs.count(node) ||
dynamic_cast<const RelModify*>(node)) {
continue;
}
std::vector<size_t> all_live(node->size());
std::iota(all_live.begin(), all_live.end(), size_t(0));
live_outs.insert(std::make_pair(
node, std::unordered_set<size_t>(all_live.begin(), all_live.end())));
work_set.push_back(node);
while (!work_set.empty()) {
auto walker = work_set.back();
work_set.pop_back();
CHECK(!dynamic_cast<const RelScan*>(walker));
CHECK(live_outs.count(walker));
auto live_ins = get_live_ins(walker, live_outs);
CHECK_EQ(live_ins.size(), walker->inputCount());
for (size_t i = 0; i < walker->inputCount(); ++i) {
auto src = walker->getInput(i);
if (dynamic_cast<const RelScan*>(src) || live_ins[i].empty()) {
continue;
}
if (!live_outs.count(src)) {
live_outs.insert(std::make_pair(src, std::unordered_set<size_t>{}));
}
auto src_it = live_outs.find(src);
CHECK(src_it != live_outs.end());
auto& live_out = src_it->second;
bool changed = false;
if (!live_out.empty()) {
live_out.insert(live_ins[i].begin(), live_ins[i].end());
changed = true;
} else {
for (int idx : live_ins[i]) {
changed |= live_out.insert(idx).second;
}
}
if (changed) {
work_set.push_back(src);
}
}
}
}
return live_outs;
}
std::string get_field_name(const RelAlgNode* node, size_t index) {
CHECK_LT(index, node->size());
if (auto scan = dynamic_cast<const RelScan*>(node)) {
return scan->getFieldName(index);
}
if (auto aggregate = dynamic_cast<const RelAggregate*>(node)) {
CHECK_EQ(aggregate->size(), aggregate->getFields().size());
return aggregate->getFieldName(index);
}
if (auto join = dynamic_cast<const RelJoin*>(node)) {
const auto lhs_size = join->getInput(0)->size();
if (index < lhs_size) {
return get_field_name(join->getInput(0), index);
}
return get_field_name(join->getInput(1), index - lhs_size);
}
if (auto project = dynamic_cast<const RelProject*>(node)) {
return project->getFieldName(index);
}
CHECK(dynamic_cast<const RelSort*>(node) || dynamic_cast<const RelFilter*>(node));
return get_field_name(node->getInput(0), index);
}
void try_insert_coalesceable_proj(
std::vector<std::shared_ptr<RelAlgNode>>& nodes,
std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& liveouts,
std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web) {
std::vector<std::shared_ptr<RelAlgNode>> new_nodes;
for (auto node : nodes) {
new_nodes.push_back(node);
if (!std::dynamic_pointer_cast<RelFilter>(node)) {
continue;
}
const auto filter = node.get();
auto liveout_it = liveouts.find(filter);
CHECK(liveout_it != liveouts.end());
auto& outs = liveout_it->second;
if (!any_dead_col_in(filter, outs)) {
continue;
}
auto usrs_it = du_web.find(filter);
CHECK(usrs_it != du_web.end());
auto& usrs = usrs_it->second;
if (usrs.size() != 1 || does_redef_cols(*usrs.begin())) {
continue;
}
auto only_usr = const_cast<RelAlgNode*>(*usrs.begin());
std::vector<std::unique_ptr<const RexScalar>> exprs;
std::vector<std::string> fields;
for (size_t i = 0; i < filter->size(); ++i) {
exprs.push_back(boost::make_unique<RexInput>(filter, i));
fields.push_back(get_field_name(filter, i));
}
auto project_owner = std::make_shared<RelProject>(exprs, fields, node);
auto project = project_owner.get();
only_usr->replaceInput(node, project_owner);
if (dynamic_cast<const RelJoin*>(only_usr)) {
RexRebindInputsVisitor visitor(filter, project);
for (auto usr : du_web[only_usr]) {
visitor.visitNode(usr);
}
}
liveouts.insert(std::make_pair(project, outs));
usrs.clear();
usrs.insert(project);
du_web.insert(
std::make_pair(project, std::unordered_set<const RelAlgNode*>{only_usr}));
new_nodes.push_back(project_owner);
}
if (new_nodes.size() > nodes.size()) {
nodes.swap(new_nodes);
}
}
std::pair<std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>,
std::vector<const RelAlgNode*>>
sweep_dead_columns(
const std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& live_outs,
const std::vector<std::shared_ptr<RelAlgNode>>& nodes,
const std::unordered_set<const RelAlgNode*>& intact_nodes,
const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web,
const std::unordered_map<const RelAlgNode*, size_t>& orig_node_sizes) {
std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>
liveouts_renumbering;
std::vector<const RelAlgNode*> ready_nodes;
AvailabilityChecker checker(liveouts_renumbering, intact_nodes);
for (auto node : nodes) {
// Ignore empty live_out due to some invalid node
if (!does_redef_cols(node.get()) || intact_nodes.count(node.get())) {
continue;
}
auto live_pair = live_outs.find(node.get());
CHECK(live_pair != live_outs.end());
auto old_live_outs = live_pair->second;
add_new_indices_for(
node.get(), liveouts_renumbering, old_live_outs, intact_nodes, orig_node_sizes);
if (auto aggregate = std::dynamic_pointer_cast<RelAggregate>(node)) {
auto old_exprs = aggregate->getAggExprsAndRelease();
std::vector<std::unique_ptr<const RexAgg>> new_exprs;
auto key_name_it = aggregate->getFields().begin();
std::vector<std::string> new_fields(key_name_it,
key_name_it + aggregate->getGroupByCount());
for (size_t i = aggregate->getGroupByCount(), j = 0;
i < aggregate->getFields().size() && j < old_exprs.size();
++i, ++j) {
if (old_live_outs.count(i)) {
new_exprs.push_back(std::move(old_exprs[j]));
new_fields.push_back(aggregate->getFieldName(i));
}
}
aggregate->setAggExprs(new_exprs);
aggregate->setFields(new_fields);
} else if (auto project = std::dynamic_pointer_cast<RelProject>(node)) {
auto old_exprs = project->getExpressionsAndRelease();
std::vector<std::unique_ptr<const RexScalar>> new_exprs;
std::vector<std::string> new_fields;
for (size_t i = 0; i < old_exprs.size(); ++i) {
if (old_live_outs.count(i)) {
new_exprs.push_back(std::move(old_exprs[i]));
new_fields.push_back(project->getFieldName(i));
}
}
project->setExpressions(new_exprs);
project->setFields(new_fields);
} else {
CHECK(false);
}
auto usrs_it = du_web.find(node.get());
CHECK(usrs_it != du_web.end());
for (auto usr : usrs_it->second) {
if (checker.hasAllSrcReady(usr)) {
ready_nodes.push_back(usr);
}
}
}
return {liveouts_renumbering, ready_nodes};
}
void propagate_input_renumbering(
std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>&
liveout_renumbering,
const std::vector<const RelAlgNode*>& ready_nodes,
const std::unordered_map<const RelAlgNode*, std::unordered_set<size_t>>& old_liveouts,
const std::unordered_set<const RelAlgNode*>& intact_nodes,
const std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web,
const std::unordered_map<const RelAlgNode*, size_t>& orig_node_sizes) {
RexInputRenumberVisitor renumberer(liveout_renumbering);
AvailabilityChecker checker(liveout_renumbering, intact_nodes);
std::deque<const RelAlgNode*> work_set(ready_nodes.begin(), ready_nodes.end());
while (!work_set.empty()) {
auto walker = work_set.front();
work_set.pop_front();
CHECK(!dynamic_cast<const RelScan*>(walker));
auto node = const_cast<RelAlgNode*>(walker);
if (auto project = dynamic_cast<RelProject*>(node)) {
auto old_exprs = project->getExpressionsAndRelease();
std::vector<std::unique_ptr<const RexScalar>> new_exprs;
for (auto& expr : old_exprs) {
new_exprs.push_back(renumberer.visit(expr.get()));
}
project->setExpressions(new_exprs);
} else if (auto aggregate = dynamic_cast<RelAggregate*>(node)) {
auto src_it = liveout_renumbering.find(node->getInput(0));
CHECK(src_it != liveout_renumbering.end());
auto old_exprs = aggregate->getAggExprsAndRelease();
auto new_exprs = renumber_rex_aggs(old_exprs, src_it->second);
aggregate->setAggExprs(new_exprs);
} else if (auto join = dynamic_cast<RelJoin*>(node)) {
auto new_condition = renumberer.visit(join->getCondition());
join->setCondition(new_condition);
} else if (auto filter = dynamic_cast<RelFilter*>(node)) {
auto new_condition = renumberer.visit(filter->getCondition());
filter->setCondition(new_condition);
} else if (auto sort = dynamic_cast<RelSort*>(node)) {
auto src_it = liveout_renumbering.find(node->getInput(0));
CHECK(src_it != liveout_renumbering.end());
std::vector<SortField> new_collations;
for (size_t i = 0; i < sort->collationCount(); ++i) {
new_collations.push_back(
renumber_sort_field(sort->getCollation(i), src_it->second));
}
sort->setCollation(std::move(new_collations));
} else if (!dynamic_cast<RelLogicalUnion*>(node)) {
LOG(FATAL) << "Unhandled node type: " << node->toString();
}
// Ignore empty live_out due to some invalid node
if (does_redef_cols(node) || intact_nodes.count(node)) {
continue;
}
auto live_pair = old_liveouts.find(node);
CHECK(live_pair != old_liveouts.end());
auto live_out = live_pair->second;
add_new_indices_for(
node, liveout_renumbering, live_out, intact_nodes, orig_node_sizes);
auto usrs_it = du_web.find(walker);
CHECK(usrs_it != du_web.end());
for (auto usr : usrs_it->second) {
if (checker.hasAllSrcReady(usr)) {
work_set.push_back(usr);
}
}
}
}
} // namespace
void eliminate_dead_columns(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
if (nodes.empty()) {
return;
}
auto root = nodes.back().get();
if (!root) {
return;
}
CHECK(!dynamic_cast<const RelScan*>(root) && !dynamic_cast<const RelJoin*>(root));
// Mark
auto old_liveouts = mark_live_columns(nodes);
std::unordered_set<const RelAlgNode*> intact_nodes;
bool has_dead_cols = false;
for (auto live_pair : old_liveouts) {
auto node = live_pair.first;
const auto& outs = live_pair.second;
if (outs.empty()) {
LOG(WARNING) << "RA node with no used column: " << node->toString();
// Ignore empty live_out due to some invalid node
intact_nodes.insert(node);
}
if (any_dead_col_in(node, outs)) {
has_dead_cols = true;
} else {
intact_nodes.insert(node);
}
}
if (!has_dead_cols) {
return;
}
auto web = build_du_web(nodes);
try_insert_coalesceable_proj(nodes, old_liveouts, web);
for (auto node : nodes) {
if (intact_nodes.count(node.get()) || does_redef_cols(node.get())) {
continue;
}
bool intact = true;
for (size_t i = 0; i < node->inputCount(); ++i) {
auto source = node->getInput(i);
if (!dynamic_cast<const RelScan*>(source) && !intact_nodes.count(source)) {
intact = false;
break;
}
}
if (intact) {
intact_nodes.insert(node.get());
}
}
std::unordered_map<const RelAlgNode*, size_t> orig_node_sizes;
for (auto node : nodes) {
orig_node_sizes.insert(std::make_pair(node.get(), node->size()));
}
// Sweep
std::unordered_map<const RelAlgNode*, std::unordered_map<size_t, size_t>>
liveout_renumbering;
std::vector<const RelAlgNode*> ready_nodes;
std::tie(liveout_renumbering, ready_nodes) =
sweep_dead_columns(old_liveouts, nodes, intact_nodes, web, orig_node_sizes);
// Propagate
propagate_input_renumbering(
liveout_renumbering, ready_nodes, old_liveouts, intact_nodes, web, orig_node_sizes);
}
void eliminate_dead_subqueries(std::vector<std::shared_ptr<RexSubQuery>>& subqueries,
RelAlgNode const* root) {
if (!subqueries.empty()) {
auto live_ids = RexSubQueryIdCollector::getLiveRexSubQueryIds(root);
auto sort_live_ids_first = [&live_ids](auto& a, auto& b) {
return live_ids.count(a->getId()) && !live_ids.count(b->getId());
};
std::stable_sort(subqueries.begin(), subqueries.end(), sort_live_ids_first);
size_t n_dead_subqueries;
if (live_ids.count(subqueries.front()->getId())) {
auto first_dead_itr = std::upper_bound(subqueries.cbegin(),
subqueries.cend(),
subqueries.front(),
sort_live_ids_first);
n_dead_subqueries = subqueries.cend() - first_dead_itr;
} else {
n_dead_subqueries = subqueries.size();
}
if (n_dead_subqueries) {
VLOG(1) << "Eliminating " << n_dead_subqueries
<< (n_dead_subqueries == 1 ? " subquery." : " subqueries.");
subqueries.resize(subqueries.size() - n_dead_subqueries);
subqueries.shrink_to_fit();
}
}
}
namespace {
class RexInputSinker : public RexDeepCopyVisitor {
public:
RexInputSinker(const std::unordered_map<size_t, size_t>& old_to_new_idx,
const RelAlgNode* new_src)
: old_to_new_in_idx_(old_to_new_idx), target_(new_src) {}
RetType visitInput(const RexInput* input) const override {
CHECK_EQ(target_->inputCount(), size_t(1));
CHECK_EQ(target_->getInput(0), input->getSourceNode());
auto idx_it = old_to_new_in_idx_.find(input->getIndex());
CHECK(idx_it != old_to_new_in_idx_.end());
return boost::make_unique<RexInput>(target_, idx_it->second);
}
private:
const std::unordered_map<size_t, size_t>& old_to_new_in_idx_;
const RelAlgNode* target_;
};
class SubConditionReplacer : public RexDeepCopyVisitor {
public:
SubConditionReplacer(const std::unordered_map<size_t, std::unique_ptr<const RexScalar>>&
idx_to_sub_condition)
: idx_to_subcond_(idx_to_sub_condition) {}
RetType visitInput(const RexInput* input) const override {
auto subcond_it = idx_to_subcond_.find(input->getIndex());
if (subcond_it != idx_to_subcond_.end()) {
return RexDeepCopyVisitor::visit(subcond_it->second.get());
}
return RexDeepCopyVisitor::visitInput(input);
}
private:
const std::unordered_map<size_t, std::unique_ptr<const RexScalar>>& idx_to_subcond_;
};
} // namespace
void sink_projected_boolean_expr_to_join(
std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
auto web = build_du_web(nodes);
auto liveouts = mark_live_columns(nodes);
for (auto node : nodes) {
auto project = std::dynamic_pointer_cast<RelProject>(node);
// TODO(miyu): relax RelScan limitation
if (!project || project->isSimple() ||
!dynamic_cast<const RelScan*>(project->getInput(0))) {
continue;
}
auto usrs_it = web.find(project.get());
CHECK(usrs_it != web.end());
auto& usrs = usrs_it->second;
if (usrs.size() != 1) {
continue;
}
auto join = dynamic_cast<RelJoin*>(const_cast<RelAlgNode*>(*usrs.begin()));
if (!join) {
continue;
}
auto outs_it = liveouts.find(join);
CHECK(outs_it != liveouts.end());
std::unordered_map<size_t, size_t> in_to_out_index;
std::unordered_set<size_t> boolean_expr_indicies;
bool discarded = false;
for (size_t i = 0; i < project->size(); ++i) {
auto oper = dynamic_cast<const RexOperator*>(project->getProjectAt(i));
if (oper && oper->getType().get_type() == kBOOLEAN) {
boolean_expr_indicies.insert(i);
} else {
// TODO(miyu): relax?
if (auto input = dynamic_cast<const RexInput*>(project->getProjectAt(i))) {
in_to_out_index.insert(std::make_pair(input->getIndex(), i));
} else {
discarded = true;
}
}
}
if (discarded || boolean_expr_indicies.empty()) {
continue;
}
const size_t index_base =
join->getInput(0) == project.get() ? 0 : join->getInput(0)->size();
for (auto i : boolean_expr_indicies) {
auto join_idx = index_base + i;
if (outs_it->second.count(join_idx)) {
discarded = true;
break;
}
}
if (discarded) {
continue;
}
RexInputCollector collector(project.get());
std::vector<size_t> unloaded_input_indices;
std::unordered_map<size_t, std::unique_ptr<const RexScalar>> in_idx_to_new_subcond;
// Given all are dead right after join, safe to sink
for (auto i : boolean_expr_indicies) {
auto rex_ins = collector.visit(project->getProjectAt(i));
for (auto& in : rex_ins) {
CHECK_EQ(in.getSourceNode(), project->getInput(0));
if (!in_to_out_index.count(in.getIndex())) {
auto curr_out_index = project->size() + unloaded_input_indices.size();
in_to_out_index.insert(std::make_pair(in.getIndex(), curr_out_index));
unloaded_input_indices.push_back(in.getIndex());
}
RexInputSinker sinker(in_to_out_index, project.get());
in_idx_to_new_subcond.insert(
std::make_pair(i, sinker.visit(project->getProjectAt(i))));
}
}
if (in_idx_to_new_subcond.empty()) {
continue;
}
std::vector<std::unique_ptr<const RexScalar>> new_projections;
for (size_t i = 0; i < project->size(); ++i) {
if (boolean_expr_indicies.count(i)) {
new_projections.push_back(boost::make_unique<RexInput>(project->getInput(0), 0));
} else {
auto rex_input = dynamic_cast<const RexInput*>(project->getProjectAt(i));
CHECK(rex_input != nullptr);
new_projections.push_back(rex_input->deepCopy());
}
}
for (auto i : unloaded_input_indices) {
new_projections.push_back(boost::make_unique<RexInput>(project->getInput(0), i));
}
project->setExpressions(new_projections);
SubConditionReplacer replacer(in_idx_to_new_subcond);
auto new_condition = replacer.visit(join->getCondition());
join->setCondition(new_condition);
}
}
namespace {
class RexInputRedirector : public RexDeepCopyVisitor {
public:
RexInputRedirector(const RelAlgNode* old_src, const RelAlgNode* new_src)
: old_src_(old_src), new_src_(new_src) {}
RetType visitInput(const RexInput* input) const override {
CHECK_EQ(old_src_, input->getSourceNode());
CHECK_NE(old_src_, new_src_);
auto actual_new_src = new_src_;
if (auto join = dynamic_cast<const RelJoin*>(new_src_)) {
actual_new_src = join->getInput(0);
CHECK_EQ(join->inputCount(), size_t(2));
auto src2_input_base = actual_new_src->size();
if (input->getIndex() >= src2_input_base) {
actual_new_src = join->getInput(1);
return boost::make_unique<RexInput>(actual_new_src,
input->getIndex() - src2_input_base);
}
}
return boost::make_unique<RexInput>(actual_new_src, input->getIndex());
}
private:
const RelAlgNode* old_src_;
const RelAlgNode* new_src_;
};
void replace_all_usages(
std::shared_ptr<const RelAlgNode> old_def_node,
std::shared_ptr<const RelAlgNode> new_def_node,
std::unordered_map<const RelAlgNode*, std::shared_ptr<RelAlgNode>>& deconst_mapping,
std::unordered_map<const RelAlgNode*, std::unordered_set<const RelAlgNode*>>&
du_web) {
auto usrs_it = du_web.find(old_def_node.get());
RexInputRedirector redirector(new_def_node.get(), old_def_node.get());
CHECK(usrs_it != du_web.end());
for (auto usr : usrs_it->second) {
auto usr_it = deconst_mapping.find(usr);
CHECK(usr_it != deconst_mapping.end());
usr_it->second->replaceInput(old_def_node, new_def_node);
}
auto new_usrs_it = du_web.find(new_def_node.get());
CHECK(new_usrs_it != du_web.end());
new_usrs_it->second.insert(usrs_it->second.begin(), usrs_it->second.end());
usrs_it->second.clear();
}
} // namespace
void fold_filters(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
std::unordered_map<const RelAlgNode*, std::shared_ptr<RelAlgNode>> deconst_mapping;
for (auto node : nodes) {
deconst_mapping.insert(std::make_pair(node.get(), node));
}
auto web = build_du_web(nodes);
for (auto node_it = nodes.rbegin(); node_it != nodes.rend(); ++node_it) {
auto& node = *node_it;
if (auto filter = std::dynamic_pointer_cast<RelFilter>(node)) {
CHECK_EQ(filter->inputCount(), size_t(1));
auto src_filter = dynamic_cast<const RelFilter*>(filter->getInput(0));
if (!src_filter) {
continue;
}
auto siblings_it = web.find(src_filter);
if (siblings_it == web.end() || siblings_it->second.size() != size_t(1)) {
continue;
}
auto src_it = deconst_mapping.find(src_filter);
CHECK(src_it != deconst_mapping.end());
auto folded_filter = std::dynamic_pointer_cast<RelFilter>(src_it->second);
CHECK(folded_filter);
// TODO(miyu) : drop filter w/ only expression valued constant TRUE?
if (auto rex_operator = dynamic_cast<const RexOperator*>(filter->getCondition())) {
LOG(INFO) << "ID=" << filter->getId() << " " << filter->toString()
<< " folded into "
<< "ID=" << folded_filter->getId() << " " << folded_filter->toString()
<< std::endl;
std::vector<std::unique_ptr<const RexScalar>> operands;
operands.emplace_back(folded_filter->getAndReleaseCondition());
auto old_condition = dynamic_cast<const RexOperator*>(operands.back().get());
CHECK(old_condition && old_condition->getType().get_type() == kBOOLEAN);
RexInputRedirector redirector(folded_filter.get(), folded_filter->getInput(0));
operands.push_back(redirector.visit(rex_operator));
auto other_condition = dynamic_cast<const RexOperator*>(operands.back().get());
CHECK(other_condition && other_condition->getType().get_type() == kBOOLEAN);
const bool notnull = old_condition->getType().get_notnull() &&
other_condition->getType().get_notnull();
auto new_condition = std::unique_ptr<const RexScalar>(
new RexOperator(kAND, operands, SQLTypeInfo(kBOOLEAN, notnull)));
folded_filter->setCondition(new_condition);
replace_all_usages(filter, folded_filter, deconst_mapping, web);
deconst_mapping.erase(filter.get());
web.erase(filter.get());
web[filter->getInput(0)].erase(filter.get());
node.reset();
}
}
}
if (!nodes.empty()) {
auto sink = nodes.back();
for (auto node_it = std::next(nodes.rend()); !sink && node_it != nodes.rbegin();
++node_it) {
sink = *node_it;
}
CHECK(sink);
cleanup_dead_nodes(nodes);
}
}
std::vector<const RexScalar*> find_hoistable_conditions(const RexScalar* condition,
const RelAlgNode* source,
const size_t first_col_idx,
const size_t last_col_idx) {
if (auto rex_op = dynamic_cast<const RexOperator*>(condition)) {
switch (rex_op->getOperator()) {
case kAND: {
std::vector<const RexScalar*> subconditions;
size_t complete_subcond_count = 0;
for (size_t i = 0; i < rex_op->size(); ++i) {
auto conds = find_hoistable_conditions(
rex_op->getOperand(i), source, first_col_idx, last_col_idx);
if (conds.size() == size_t(1)) {
++complete_subcond_count;
}
subconditions.insert(subconditions.end(), conds.begin(), conds.end());
}
if (complete_subcond_count == rex_op->size()) {
return {rex_op};
} else {
return {subconditions};
}
break;
}
case kEQ: {
const auto lhs_conds = find_hoistable_conditions(
rex_op->getOperand(0), source, first_col_idx, last_col_idx);
const auto rhs_conds = find_hoistable_conditions(
rex_op->getOperand(1), source, first_col_idx, last_col_idx);
const auto lhs_in = lhs_conds.size() == 1
? dynamic_cast<const RexInput*>(*lhs_conds.begin())
: nullptr;
const auto rhs_in = rhs_conds.size() == 1
? dynamic_cast<const RexInput*>(*rhs_conds.begin())
: nullptr;
if (lhs_in && rhs_in) {
return {rex_op};
}
return {};
break;
}
default:
break;
}
return {};
}
if (auto rex_in = dynamic_cast<const RexInput*>(condition)) {
if (rex_in->getSourceNode() == source) {
const auto col_idx = rex_in->getIndex();
return {col_idx >= first_col_idx && col_idx <= last_col_idx ? condition : nullptr};
}
return {};
}
return {};
}
class JoinTargetRebaser : public RexDeepCopyVisitor {
public:
JoinTargetRebaser(const RelJoin* join, const unsigned old_base)
: join_(join)
, old_base_(old_base)
, src1_base_(join->getInput(0)->size())
, target_count_(join->size()) {}
RetType visitInput(const RexInput* input) const override {
auto curr_idx = input->getIndex();
CHECK_GE(curr_idx, old_base_);
CHECK_LT(static_cast<size_t>(curr_idx), target_count_);
curr_idx -= old_base_;
if (curr_idx >= src1_base_) {
return boost::make_unique<RexInput>(join_->getInput(1), curr_idx - src1_base_);
} else {
return boost::make_unique<RexInput>(join_->getInput(0), curr_idx);
}
}
private:
const RelJoin* join_;
const unsigned old_base_;
const size_t src1_base_;
const size_t target_count_;
};
class SubConditionRemover : public RexDeepCopyVisitor {
public:
SubConditionRemover(const std::vector<const RexScalar*> sub_conds)
: sub_conditions_(sub_conds.begin(), sub_conds.end()) {}
RetType visitOperator(const RexOperator* rex_operator) const override {
if (sub_conditions_.count(rex_operator)) {
return boost::make_unique<RexLiteral>(
true, kBOOLEAN, kBOOLEAN, unsigned(-2147483648), 1, unsigned(-2147483648), 1);
}
return RexDeepCopyVisitor::visitOperator(rex_operator);
}
private:
std::unordered_set<const RexScalar*> sub_conditions_;
};
void hoist_filter_cond_to_cross_join(
std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
std::unordered_set<const RelAlgNode*> visited;
auto web = build_du_web(nodes);
for (auto node : nodes) {
if (visited.count(node.get())) {
continue;
}
visited.insert(node.get());
auto join = dynamic_cast<RelJoin*>(node.get());
if (join && join->getJoinType() == JoinType::INNER) {
// Only allow cross join for now.
if (auto literal = dynamic_cast<const RexLiteral*>(join->getCondition())) {
// Assume Calcite always generates an inner join on constant boolean true for
// cross join.
CHECK(literal->getType() == kBOOLEAN && literal->getVal<bool>());
size_t first_col_idx = 0;
const RelFilter* filter = nullptr;
std::vector<const RelJoin*> join_seq{join};
for (const RelJoin* curr_join = join; !filter;) {
auto usrs_it = web.find(curr_join);
CHECK(usrs_it != web.end());
if (usrs_it->second.size() != size_t(1)) {
break;
}
auto only_usr = *usrs_it->second.begin();
if (auto usr_join = dynamic_cast<const RelJoin*>(only_usr)) {
if (join == usr_join->getInput(1)) {
const auto src1_offset = usr_join->getInput(0)->size();
first_col_idx += src1_offset;
}
join_seq.push_back(usr_join);
curr_join = usr_join;
continue;
}
filter = dynamic_cast<const RelFilter*>(only_usr);
break;
}
if (!filter) {
visited.insert(join_seq.begin(), join_seq.end());
continue;
}
const auto src_join = dynamic_cast<const RelJoin*>(filter->getInput(0));
CHECK(src_join);
auto modified_filter = const_cast<RelFilter*>(filter);
if (src_join == join) {
std::unique_ptr<const RexScalar> filter_condition(
modified_filter->getAndReleaseCondition());
std::unique_ptr<const RexScalar> true_condition =
boost::make_unique<RexLiteral>(true,
kBOOLEAN,
kBOOLEAN,
unsigned(-2147483648),
1,
unsigned(-2147483648),
1);
modified_filter->setCondition(true_condition);
join->setCondition(filter_condition);
continue;
}
const auto src1_base = src_join->getInput(0)->size();
auto source =
first_col_idx < src1_base ? src_join->getInput(0) : src_join->getInput(1);
first_col_idx =
first_col_idx < src1_base ? first_col_idx : first_col_idx - src1_base;
auto join_conditions =
find_hoistable_conditions(filter->getCondition(),
source,
first_col_idx,
first_col_idx + join->size() - 1);
if (join_conditions.empty()) {
continue;
}
JoinTargetRebaser rebaser(join, first_col_idx);
if (join_conditions.size() == 1) {
auto new_join_condition = rebaser.visit(*join_conditions.begin());
join->setCondition(new_join_condition);
} else {
std::vector<std::unique_ptr<const RexScalar>> operands;
bool notnull = true;
for (size_t i = 0; i < join_conditions.size(); ++i) {
operands.emplace_back(rebaser.visit(join_conditions[i]));
auto old_subcond = dynamic_cast<const RexOperator*>(join_conditions[i]);
CHECK(old_subcond && old_subcond->getType().get_type() == kBOOLEAN);
notnull = notnull && old_subcond->getType().get_notnull();
}
auto new_join_condition = std::unique_ptr<const RexScalar>(
new RexOperator(kAND, operands, SQLTypeInfo(kBOOLEAN, notnull)));
join->setCondition(new_join_condition);
}
SubConditionRemover remover(join_conditions);
auto new_filter_condition = remover.visit(filter->getCondition());
modified_filter->setCondition(new_filter_condition);
}
}
}
}
// For some reason, Calcite generates Sort, Project, Sort sequences where the
// two Sort nodes are identical and the Project is identity. Simplify this
// pattern by re-binding the input of the second sort to the input of the first.
void simplify_sort(std::vector<std::shared_ptr<RelAlgNode>>& nodes) noexcept {
if (nodes.size() < 3) {
return;
}
for (size_t i = 0; i <= nodes.size() - 3;) {
auto first_sort = std::dynamic_pointer_cast<RelSort>(nodes[i]);
const auto project = std::dynamic_pointer_cast<const RelProject>(nodes[i + 1]);
auto second_sort = std::dynamic_pointer_cast<RelSort>(nodes[i + 2]);
if (first_sort && second_sort && project && project->isIdentity() &&
*first_sort == *second_sort) {
second_sort->replaceInput(second_sort->getAndOwnInput(0),
first_sort->getAndOwnInput(0));
nodes[i].reset();
nodes[i + 1].reset();
i += 3;
} else {
++i;
}
}
std::vector<std::shared_ptr<RelAlgNode>> new_nodes;
for (auto node : nodes) {
if (!node) {
continue;
}
new_nodes.push_back(node);
}
nodes.swap(new_nodes);
}
|
#include <iostream>
using namespace std; // Using Directives
//using std::cout; //only making the particular function available
int main()
{
int slices;
cout<<"How many slices:";
cin>>slices; // cin instance of istream. Takes input from console
cout<<"You have "<<slices<<" slices"<<endl;
return 0;
}
|
/**
* @file circletest.h
* @author Petr Vana
* @brief Test of the optimal solution for the Generalized Dubins Interval Problem (GDIP)
*/
#include "gtest/gtest.h"
#include "opendubins/dubins.h"
using namespace opendubins;
using namespace std;
namespace gdiptest {
const int COUNT = 2000;
int typeCount[200] = {};
void check2(AngleInterval &interval1, AngleInterval &interval2, Dubins &d1, Dubins &d2) {
EXPECT_TRUE(d1.check()) << "incorrect original maneuver";
EXPECT_TRUE(d2.check()) << "incorrect newly created maneuver form intervals " << endl << d2;
if(!d2.check()){
cout << "Debug point here" << endl;
}
bool in1 = interval1.inIntervalWithTollerance(d2.start.ang, TOLERANCE);
bool in2 = interval2.inIntervalWithTollerance(d2.end.ang, TOLERANCE);
EXPECT_TRUE(in1) << "out of first interval";
EXPECT_TRUE(in2) << "out of second interval";
EXPECT_GE(d1.length + 10 * TOLERANCE, d2.length) << "DubinsInterval " << d2.getType() << " is longer than original maneuver " << d1.getType();
if (!in1) {
cout << "IN1 " << d2.start.ang << " is not in <" << interval1.getRight() << ", " << interval1.getLeft() <<
endl;
}
if (!in2) {
cout << "IN2 " << d2.end.ang << " is not in <" << interval2.getRight() << ", " << interval2.getLeft() <<
endl;
}
if (d1.length + TOLERANCE < d2.length) {
std::cout << "First dubins 111111111111 " << std::endl << d1 << std::endl;
std::cout << "Second dubins 222222222222 " << std::endl << d2 << std::endl;
}
typeCount[(int) d2.getType()]++;
}
bool checkGDIP(AngleInterval &interval1, AngleInterval &interval2, Dubins &d1, Dubins &d2, double diff2) {
bool ret = true;
EXPECT_TRUE(d1.check()) << "incorrect original maneuver";
EXPECT_TRUE(d2.check()) << "incorrect newly created maneuver form intervals";
bool in1 = interval1.inIntervalWithTollerance(d2.start.ang, TOLERANCE);
bool in2 = interval2.inIntervalWithTollerance(d2.end.ang, TOLERANCE);
EXPECT_TRUE(in1) << "out of first interval";
EXPECT_TRUE(in2) << "out of second interval";
EXPECT_GE(d1.length + 1 * TOLERANCE, d2.length) << "DubinsInterval is longer than original maneuver";
if (!in1) {
cout << "IN1 " << d2.start.ang << " is not in <" << interval1.getRight() << ", " << interval1.getLeft() <<
endl;
}
if (!in2) {
cout << "IN2 " << d2.end.ang << " is not in <" << interval2.getRight() << ", " << interval2.getLeft() <<
endl;
}
if (d1.length + TOLERANCE < d2.length) {
std::cout << "First dubins 111111111111 " << std::endl << d1 << std::endl;
std::cout << "Second dubins 222222222222 " << std::endl << d2 << std::endl;
ret = false;
}
EXPECT_GE(TOLERANCE, interval1.point.distance(d2.start.point)) << "Wrong start " << interval1.point << endl << d2;
EXPECT_GE(diff2 + TOLERANCE, interval2.point.distance(d2.end.point)) << "Wrong end " << interval2.point << endl << d2;
typeCount[(int) d2.getType()]++;
return ret;
}
Dubins checkUsingIntervals2(Dubins &d1, double a1, double b1, double a2, double b2) {
double a = myRandom() * a1;
double b = myRandom() * b1;
AngleInterval interval1 = AngleInterval(d1.start.point, d1.start.getAngle() - a, b + a);
a = myRandom() * a2;
b = myRandom() * b2;
AngleInterval interval2 = AngleInterval(d1.end.point, d1.end.getAngle() - a, b + a);
Dubins d2(interval1, interval2, d1.radius, 0, 0);
check2(interval1, interval2, d1, d2);
return d2;
}
double getRadius2() {
return 0.1 + 3 * myRandom();
}
// OLD TESTS FROM DIP ///////////////////////////////////////////////////////////////////
TEST (GDIP, ZeroInterval) {
State p1 = State(Point(0, 0), 0);
State p2 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT; ++i) {
p1.random(100);
p2.random(100);
Dubins d1(p1, p2, getRadius2());
AngleInterval interval1 = AngleInterval(p1.point, p1.ang, 0);
AngleInterval interval2 = AngleInterval(p2.point, p2.ang, 0);
Dubins d2(interval1, interval2, d1.radius, 0, 0);
check2(interval1, interval2, d1, d2);
Dubins d3(interval1, interval2, d1.radius, 0, 0);
}
}
TEST (GDIP, S) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
Dubins d1(p1, false, 0, myRandom() * 10, 0, getRadius2());
Dubins d2 = checkUsingIntervals2(d1, 1, 1, 1, 1);
EXPECT_LE(fabs(d1.length - d2.length), TOLERANCE) << "Different length of a straight line."
<< endl << d1 << endl << d2;
}
}
TEST (GDIP, RS) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
Dubins d1(p1, false, -myRandom() * 7, myRandom() * 10, 0, getRadius2());
checkUsingIntervals2(d1, 0, 1, 1, 1);
}
}
TEST (GDIP, LS) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
Dubins d1(p1, false, myRandom() * 7, myRandom() * 10, 0, getRadius2());
checkUsingIntervals2(d1, 1, 0, 1, 1);
}
}
TEST (GDIP, SR) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
Dubins d1(p1, false, 0, myRandom() * 10, -myRandom() * 7, getRadius2());
checkUsingIntervals2(d1, 1, 1, 1, 0);
}
}
TEST (GDIP, SL) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
Dubins d1(p1, false, 0, myRandom() * 10, myRandom() * 7, getRadius2());
checkUsingIntervals2(d1, 1, 1, 0, 1);
}
}
TEST (GDIP, Lp) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
Dubins d1(p1, false, M_PI + myRandom() * M_PI, 0, 0, getRadius2());
checkUsingIntervals2(d1, 0.1, 0.1, 0.1, 0.1);
}
}
TEST (GDIP, Rp) {
State p1 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT; ++i) {
p1.random(100);
Dubins d1(p1, false, -M_PI - myRandom() * M_PI, 0, 0, getRadius2());
checkUsingIntervals2(d1, 0.1, 0.1, 0.1, 0.1);
}
}
TEST (GDIP, LRp) {
State p1 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT; ++i) {
p1.random(100);
const double TOL_ANG = 0.05;
double turn1 = myRandom() * M_PI * (1 - TOL_ANG);
double turn2 = -M_PI * (1 + TOL_ANG) - myRandom() * M_PI * (1 - 2 * TOL_ANG);
Dubins d1(p1, false, turn1, 0, turn2, getRadius2());
checkUsingIntervals2(d1, 0.1, 0, 0.1, 0.1);
}
}
TEST (GDIP, RLp) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
const double TOL_ANG = 0.05;
double turn1 = -myRandom() * M_PI * (1 - TOL_ANG);
double turn2 = +M_PI * (1 + TOL_ANG) + myRandom() * M_PI * (1 - 2 * TOL_ANG);
Dubins d1(p1, false, turn1, 0, turn2, getRadius2());
checkUsingIntervals2(d1, 0, 0.1, 0.1, 0.1);
}
}
TEST (GDIP, LpR) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
const double TOL_ANG = 0.05;
double turn1 = M_PI * (1 + TOL_ANG) + myRandom() * M_PI * (1 - 2 * TOL_ANG);
double turn2 = -myRandom() * M_PI * (1 - TOL_ANG);
Dubins d1(p1, false, turn1, 0, turn2, getRadius2());
checkUsingIntervals2(d1, 0.1, 0.1, 0.1, 0);
}
}
TEST (GDIP, RpL) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(100);
const double TOL_ANG = 0.05;
double turn1 = -M_PI * (1 + TOL_ANG) - myRandom() * M_PI * (1 - 2 * TOL_ANG);
double turn2 = myRandom() * M_PI * (1 - TOL_ANG);
Dubins d1(p1, false, turn1, 0, turn2, getRadius2());
checkUsingIntervals2(d1, 0.1, 0.1, 0, 0.1);
}
}
TEST (GDIP, Small) {
State p1 = State(Point(0, 0), 0);
State p2 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(5);
p2.random(5);
Dubins d1(p1, p2, getRadius2());
checkUsingIntervals2(d1, 0.1, 0.1, 0.1, 0.1);
}
}
TEST (GDIP, Big) {
State p1 = State(Point(0, 0), 0);
State p2 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(5);
p2.random(5);
Dubins d1(p1, p2, getRadius2());
checkUsingIntervals2(d1, 1, 1, 1, 1);
}
}
TEST (GDIP, Random) {
State p1 = State(Point(0, 0), 0);
for (
int i = 0;
i < COUNT;
++i) {
p1.random(5);
Dubins d1;
double radius = getRadius2();
double turn1 = 0;
double turn2 = 0;
if ( myRandom() < 0.5) {
double center = myRandom() * radius;
d1 = Dubins(p1, false, turn1, center, turn2, radius);
} else {
double centerTurn = (1 + myRandom()) * M_PI;
d1 = Dubins(p1, true, turn1, centerTurn, turn2, radius);
}
checkUsingIntervals2(d1, 0.1, 0.1, 0.1, 0.1);
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// NEW TESTS SPECIALLY FOR GDIP /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
Dubins checkUsingIntervals_GDIP(Dubins &d1, double a1, double b1, double a2, double b2, bool random = false, double diff2 = 0.1) {
diff2 *= myRandom();
auto dir2 = Vector(myRandom() * 2 * M_PI) * diff2 * (1 - TOLERANCE);
if(random){
dir2 *= myRandom();
}
double a = myRandom() * a1;
double b = myRandom() * b1;
AngleInterval interval1 = AngleInterval(d1.start.point, d1.start.getAngle() - a, b + a);
a = myRandom() * a2;
b = myRandom() * b2;
AngleInterval interval2 = AngleInterval(d1.end.point + dir2, d1.end.getAngle() - a, b + a);
Dubins d2(interval1, interval2, d1.radius, diff2);
bool ok = checkGDIP(interval1, interval2, d1, d2, diff2);
if(!ok){
cout << "Test is not ok " << endl << "( " << a1 << " " << a2 << " " << b1 << " " << b2 << " " << diff2 << " )" << endl;
}
return d2;
}
TEST (GDIP, S_GDIP) {
State p1 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT; ++i) {
p1.random(100);
Dubins d1(p1, false, 0, myRandom() * 10, 0, getRadius2());
checkUsingIntervals_GDIP(d1, 1, 1, 1, 1);
}
}
void testCpC(bool isLeft, bool basic, bool reverse = false) {
int sgn = isLeft ? 1 : -1;
State p1 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT; ++i) {
p1.random(100);
const double TOL_ANG = 0.05;
double turn1 = myRandom() * M_PI * (1 - TOL_ANG);
double turn2 = -M_PI * (1 + TOL_ANG) - myRandom() * M_PI * (1 - 2 * TOL_ANG);
if(reverse){
std::swap(turn1, turn2);
sgn = -1;
}
Dubins d1(p1, false, sgn*turn1, 0, sgn*turn2, getRadius2());
double D = 0.1;
checkUsingIntervals_GDIP(d1, 0, D, D, D, true);
checkUsingIntervals_GDIP(d1, D, 0, D, D, true);
checkUsingIntervals_GDIP(d1, D, D, 0, D, true);
checkUsingIntervals_GDIP(d1, D, D, D, 0, true);
}
}
#define TEST_CpC(name, isLeft, reverse) \
TEST (GDIP, name) { \
testCpC(isLeft, false, reverse); \
}
TEST_CpC(LpP_GDIP, true, true);
TEST_CpC(RpR_GDIP, false, true);
TEST_CpC(LRp_GDIP, true, false);
TEST_CpC(RLp_GDIP, false, false);
void testCS(bool isLeft, bool basic, bool straight = false, bool longer = false) {
int sgn = isLeft ? 1 : -1;
double s = straight ? myRandom() * 0.01 : 0;
State p1 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT; ++i) {
p1.random(100);
Dubins d1(p1, false, sgn * myRandom() * 3, s, 0, getRadius2());
if(basic) {
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0);
} else {
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0, true);
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0, true);
}
}
}
#define TEST_C(name, isLeft) \
TEST (GDIP, name) { \
testCS(isLeft, false); \
}
#define TEST_C_BASIC(name, isLeft) \
TEST (GDIP, name) { \
testCS(isLeft, true); \
}
#define TEST_CS(name, isLeft, straight, longer) \
TEST (GDIP, name) { \
testCS(isLeft, false, straight, longer); \
}
#define TEST_CS_BASIC(name, isLeft, straight, longer) \
TEST (GDIP, name) { \
testCS(isLeft, true, straight, longer); \
}
TEST_C(L_GDIP_Random, true);
TEST_C(R_GDIP_Random, false);
TEST_C_BASIC(L_GDIP_Basic, true);
TEST_C_BASIC(R_GDIP_Basic, false);
TEST_CS(LS_GDIP_Random, true, true, false);
TEST_CS(RS_GDIP_Random, false, true, false);
TEST_CS_BASIC(LS_GDIP_Basic, true, true, false);
TEST_CS_BASIC(RS_GDIP_Basic, false, true, false);
TEST_CS(LS_GDIP_Long, true, true, true);
TEST_CS(RS_GDIP_Long, false, true, true);
TEST_CS_BASIC(LS_GDIP_Basic_Long, true, true, true);
TEST_CS_BASIC(RS_GDIP_Basic_Long, false, true, true);
void testSC(bool isLeft, bool basic, bool straight = false, bool longer = false) {
int sgn = isLeft ? 1 : -1;
double s = straight ? myRandom() * 0.01 : 0;
State p1 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT; ++i) {
p1.random(100);
Dubins d1(p1, false, 0, s, sgn * myRandom() * 3, getRadius2());
if(basic) {
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0);
} else {
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0, true);
}
}
}
#define TEST_CB(name, isLeft) \
TEST (GDIP, name) { \
testSC(isLeft, false); \
}
#define TEST_CB_BASIC(name, isLeft) \
TEST (GDIP, name) { \
testSC(isLeft, true); \
}
#define TEST_SC(name, isLeft, straight, longer) \
TEST (GDIP, name) { \
testSC(isLeft, false, straight, longer); \
}
#define TEST_SC_BASIC(name, isLeft, straight, longer) \
TEST (GDIP, name) { \
testSC(isLeft, true, straight, longer); \
}
TEST_CB(LB_GDIP_Random, true);
TEST_CB(RB_GDIP_Random, false);
TEST_CB_BASIC(LB_GDIP_Basic, true);
TEST_CB_BASIC(RB_GDIP_Basic, false);
TEST_SC(SL_GDIP_Random, true, true, false);
TEST_SC(SR_GDIP_Random, false, true, false);
TEST_SC_BASIC(SL_GDIP_Basic, true, true, false);
TEST_SC_BASIC(SR_GDIP_Basic, false, true, false);
TEST_SC(SL_GDIP_Long, true, true, true);
TEST_SC(SR_GDIP_Long, false, true, true);
TEST_SC_BASIC(SL_GDIP_Basic_Long, true, true, true);
TEST_SC_BASIC(SR_GDIP_Basic_Long, false, true, true);
void testCSC(bool isLeft, bool basic, bool same, double straight = 0, int type = 0) {
int sgn1 = isLeft ? 1 : -1;
int sgn2 = (isLeft==same) ? 1 : -1;
double s = myRandom() * straight;
State p1 = State(Point(0, 0), 0);
for (int i = 0; i < COUNT*1; ++i) {
p1.random(100);
double r1, r2;
if(type == 1){
r1 = sgn1 * myRandom() * 1;
r2 = fabs(myRandom() * r1) * sgn2;
}else if (type == 2){
r2 = sgn2 * myRandom() * 1;
r1 = fabs(myRandom() * r2) * sgn1;
} else{
r1 = sgn1 * myRandom() * 1;
r2 = sgn2 * myRandom() * 1;
}
Dubins d1(p1, false, r1, s, r2, getRadius2());
if(basic) {
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0);
} else {
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0, true, 0.01);
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0, true, 0.1);
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0, true, 1);
checkUsingIntervals_GDIP(d1, 0, 0, 0, 0, true, 3);
}
}
}
#define TEST_CC(name, isLeft, same) \
TEST (GDIP, name) { \
testCSC(isLeft, false, same); \
}
#define TEST_CC_BASIC(name, isLeft, same) \
TEST (GDIP, name) { \
testCSC(isLeft, true, same); \
}
#define TEST_CSC_ALL(name, isLeft, false, same, straight) \
TEST (GDIP, name) { \
testCSC(isLeft, false, same, straight, 0); \
}\
TEST (GDIP, name##_Xx) { \
testCSC(isLeft, false, same, straight, 1); \
}\
TEST (GDIP, name##_xX) { \
testCSC(isLeft, false, same, straight, 2); \
}
#define TEST_CSC(name, isLeft, same, straight) \
TEST_CSC_ALL(name, isLeft, false, same, straight)
#define TEST_CSC_BASIC(name, isLeft, same, straight) \
TEST_CSC_ALL(name, isLeft, true, same, straight)
#define BOOL_L true
#define BOOL_R false
#define TEST_CSC_BATCH(first, second) \
TEST_CC_BASIC(first##second##_GDIP_Basic, BOOL_##first, BOOL_##second) \
TEST_CC(first##second##_GDIP_Random, BOOL_##first, BOOL_##second) \
TEST_CSC_BASIC(first##S##second##_GDIP_Basic, BOOL_##first, BOOL_##second, 1) \
TEST_CSC(first##S##second##_GDIP_Random, BOOL_##first, BOOL_##second, 1)
// SAME SIDE
TEST_CSC_BATCH(L, L);
TEST_CSC_BATCH(R, R);
// DIFF SIDE
TEST_CSC_BATCH(R, L);
TEST_CSC_BATCH(L, R);
TEST (GDIP, AllUsed) {
for (int t = (int)DType::GDIP_NO; t <= (int)DType::GDIP_RpL; t++) {
DType typ = static_cast<DType>(t);
const int value = typeCount[t];
std::cout << typ << "\t-\t" << value << endl;
EXPECT_GT(value, 0) << "There is no maneuver with type " << typ;
}
}
}
|
/**
* @file sigmoid_internal.cpp
* @author Daniel Nichols
* @version 0.1
* @date 2019-02-23
*
* @copyright Copyright (c) 2019
*/
#include "compute/sigmoid/sigmoid_internal.h"
namespace magmadnn {
namespace internal {
template <typename T>
void sigmoid_full(Tensor<T> *x, Tensor<T> *out, bool fast) {
if (x->get_memory_type() == HOST) {
T *x_ptr = x->get_ptr();
T *out_ptr = out->get_ptr();
unsigned int size = out->get_size();
if (fast) {
// fast sigmoid -- fast_sigmoid(x) = x / (1 + |x|)
for (unsigned int i = 0; i < size; i++) out_ptr[i] = x_ptr[i] / (1 + abs(x_ptr[i]));
} else {
// normal sigmoid -- sigmoid(x) = 1 / (1 + exp(-x))
for (unsigned int i = 0; i < size; i++) out_ptr[i] = 1 / (1 + exp(-x_ptr[i]));
}
}
#if defined(_HAS_CUDA_)
else {
sigmoid_full_device(x, out, fast);
}
#endif
}
template void sigmoid_full(Tensor<int> *x, Tensor<int> *out, bool fast);
template void sigmoid_full(Tensor<float> *x, Tensor<float> *out, bool fast);
template void sigmoid_full(Tensor<double> *x, Tensor<double> *out, bool fast);
template <typename T>
void sigmoid_grad(Tensor<T> *output, Tensor<T> *grad, Tensor<T> *out) {
/* d s(x) = G * s(x) * (1-s(x)) */
if (out->get_memory_type() == HOST) {
T *output_ptr = output->get_ptr();
T *grad_ptr = grad->get_ptr();
T *out_ptr = out->get_ptr();
unsigned int size = out->get_size();
if (grad->get_size() == 1) {
for (unsigned int i = 0; i < size; i++) {
out_ptr[i] = grad_ptr[0] * output_ptr[i] * (((T) 1) - output_ptr[i]);
}
} else {
for (unsigned int i = 0; i < size; i++) {
out_ptr[i] = grad_ptr[i] * output_ptr[i] * (((T) 1) - output_ptr[i]);
}
}
}
#if defined(_HAS_CUDA_)
else {
sigmoid_grad_device(output, grad, out);
}
#endif
}
template void sigmoid_grad(Tensor<int> *output, Tensor<int> *grad, Tensor<int> *out);
template void sigmoid_grad(Tensor<float> *output, Tensor<float> *grad, Tensor<float> *out);
template void sigmoid_grad(Tensor<double> *output, Tensor<double> *grad, Tensor<double> *out);
} // namespace internal
} // namespace magmadnn
|
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoDeathHarvestingComponent_Small_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function DinoDeathHarvestingComponent_Small.DinoDeathHarvestingComponent_Small_C.ExecuteUbergraph_DinoDeathHarvestingComponent_Small
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UDinoDeathHarvestingComponent_Small_C::ExecuteUbergraph_DinoDeathHarvestingComponent_Small(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function DinoDeathHarvestingComponent_Small.DinoDeathHarvestingComponent_Small_C.ExecuteUbergraph_DinoDeathHarvestingComponent_Small");
UDinoDeathHarvestingComponent_Small_C_ExecuteUbergraph_DinoDeathHarvestingComponent_Small_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <shared_test_classes/single_layer/proposal.hpp>
#include "shared_test_classes/base/layer_test_utils.hpp"
#include "shared_test_classes/single_layer/psroi_pooling.hpp"
#include "shared_test_classes/single_layer/roi_pooling.hpp"
#include "shared_test_classes/single_layer/roi_align.hpp"
namespace LayerTestsDefinitions {
class ReadIRTest : public testing::WithParamInterface<std::tuple<std::string, std::string>>,
public LayerTestsUtils::LayerTestsCommon {
public:
static std::string getTestCaseName(const testing::TestParamInfo<std::tuple<std::string, std::string>> &obj);
protected:
void SetUp() override;
void GenerateInputs() override;
void Compare(const std::vector<std::vector<std::uint8_t>> &expected,
const std::vector<InferenceEngine::Blob::Ptr> &actual) override;
std::vector<InferenceEngine::Blob::Ptr> GetOutputs() override;
private:
std::string pathToModel;
};
} // namespace LayerTestsDefinitions
|
/**
* @file unit_test_fnd_static_string.cpp
*
* @brief bksge::static_string のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/static_string/static_string.hpp>
#include <bksge/fnd/string_view/string_view.hpp>
#include <bksge/fnd/compare/is_eq.hpp>
#include <bksge/fnd/compare/is_gt.hpp>
#include <bksge/fnd/compare/is_lt.hpp>
#include <bksge/fnd/concepts/swap.hpp>
#include <gtest/gtest.h>
#include <sstream>
#include <cstddef>
#include <utility>
#include "constexpr_test.hpp"
namespace bksge_static_string_test
{
#define VERIFY(...) if (!(__VA_ARGS__)) { return false; }
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool
c_str_test(bksge::static_string<N> const& s, char const* str)
{
using traits_type = typename bksge::static_string<N>::traits_type;
auto const str2 = s.c_str();
VERIFY(traits_type::length(str2) == traits_type::length(str));
VERIFY(traits_type::length(str2) == s.length());
VERIFY(traits_type::compare(str2, str, s.length()) == 0);
VERIFY(s.compare(str) == 0);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CtorDefaultTest()
{
{
bksge::static_string<N> s;
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
}
{
bksge::static_string<N> s{};
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
}
{
bksge::static_string<N> s={};
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CtorCountCharTest()
{
{
bksge::static_string<N> s(0, 'a');
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
}
{
bksge::static_string<N> s(1, 'a');
VERIFY(!s.empty());
VERIFY(s.size() == 1);
VERIFY(s.length() == 1);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "a"));
}
{
bksge::static_string<N> s(4, 'c');
VERIFY(!s.empty());
VERIFY(s.size() == 4);
VERIFY(s.length() == 4);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "cccc"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool CtorOtherPosTest()
{
{
bksge::static_string<N1> const s1("hello");
bksge::static_string<N2> const s2(s1, 1);
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "hello"));
VERIFY(!s2.empty());
VERIFY(s2.size() == 4);
VERIFY(s2.length() == 4);
VERIFY(s2.max_size() == N2);
VERIFY(s2.capacity() == N2);
VERIFY(c_str_test(s2, "ello"));
}
{
bksge::static_string<N1> const s1("hello");
bksge::static_string<N2> const s2{s1, 2};
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "hello"));
VERIFY(!s2.empty());
VERIFY(s2.size() == 3);
VERIFY(s2.length() == 3);
VERIFY(s2.max_size() == N2);
VERIFY(s2.capacity() == N2);
VERIFY(c_str_test(s2, "llo"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool CtorOtherPosCountTest()
{
{
bksge::static_string<N1> const s1("hello");
bksge::static_string<N2> const s2(s1, 1, 3);
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "hello"));
VERIFY(!s2.empty());
VERIFY(s2.size() == 3);
VERIFY(s2.length() == 3);
VERIFY(s2.max_size() == N2);
VERIFY(s2.capacity() == N2);
VERIFY(c_str_test(s2, "ell"));
}
{
bksge::static_string<N1> const s1("hello");
bksge::static_string<N2> const s2{s1, 2, 2};
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "hello"));
VERIFY(!s2.empty());
VERIFY(s2.size() == 2);
VERIFY(s2.length() == 2);
VERIFY(s2.max_size() == N2);
VERIFY(s2.capacity() == N2);
VERIFY(c_str_test(s2, "ll"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CtorCharPtrCountTest()
{
{
bksge::static_string<N> s("abcde", 4);
VERIFY(!s.empty());
VERIFY(s.size() == 4);
VERIFY(s.length() == 4);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abcd"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CtorCharPtrTest()
{
{
bksge::static_string<N> s("abcde");
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abcde"));
}
{
bksge::static_string<N> s{"hello world!"};
VERIFY(!s.empty());
VERIFY(s.size() == 12);
VERIFY(s.length() == 12);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "hello world!"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CtorIteratorTest()
{
#if !(defined(__GNUC__) && (__GNUC__ == 10)) // avoid internal compiler error
{
char const buf[] = "abcde";
bksge::static_string<N> const s(buf, buf + 3);
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abc"));
}
#endif
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool CtorCopyTest()
{
{
bksge::static_string<N1> const s1("hello world");
bksge::static_string<N2> const s2(s1);
VERIFY(!s1.empty());
VERIFY(s1.size() == 11);
VERIFY(s1.length() == 11);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "hello world"));
VERIFY(!s2.empty());
VERIFY(s2.size() == 11);
VERIFY(s2.length() == 11);
VERIFY(s2.max_size() == N2);
VERIFY(s2.capacity() == N2);
VERIFY(c_str_test(s2, "hello world"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool CtorMoveTest()
{
{
bksge::static_string<N1> s1("hello world");
bksge::static_string<N2> const s2(std::move(s1));
VERIFY(!s2.empty());
VERIFY(s2.size() == 11);
VERIFY(s2.length() == 11);
VERIFY(s2.max_size() == N2);
VERIFY(s2.capacity() == N2);
VERIFY(c_str_test(s2, "hello world"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CtorInitializerListTest()
{
{
bksge::static_string<N> s{'h', 'e', 'l', 'l', 'o'};
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "hello"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CtorStringViewTest()
{
{
bksge::static_string<N> s(bksge::string_view{"Hello World"});
VERIFY(!s.empty());
VERIFY(s.size() == 11);
VERIFY(s.length() == 11);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "Hello World"));
}
{
bksge::static_string<N> s("Hello World");
VERIFY(!s.empty());
VERIFY(s.size() == 11);
VERIFY(s.length() == 11);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "Hello World"));
}
{
bksge::static_string<N> s(bksge::string_view{"Hello World"}, 2, 5);
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "llo W"));
}
{
bksge::static_string<N> s("Hello World", 2, 5);
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "llo W"));
}
{
bksge::static_string<N> s(bksge::string_view{"Hello World"}, 2, 100);
VERIFY(!s.empty());
VERIFY(s.size() == 9);
VERIFY(s.length() == 9);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "llo World"));
}
return true;
}
GTEST_TEST(StaticStringTest, CtorTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorDefaultTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorDefaultTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorDefaultTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCountCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCountCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCountCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosCountTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosCountTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosCountTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosCountTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosCountTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorOtherPosCountTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCharPtrCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCharPtrCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCharPtrCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorIteratorTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorIteratorTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorIteratorTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorCopyTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorCopyTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorCopyTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorCopyTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorCopyTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorCopyTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorMoveTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorMoveTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorMoveTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorMoveTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorMoveTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CtorMoveTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorInitializerListTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorInitializerListTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorInitializerListTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CtorStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool AssignStringTest()
{
{
bksge::static_string<N1> s1;
VERIFY(s1.empty());
bksge::static_string<N2> const s2("hello world");
s1 = s2;
VERIFY(!s1.empty());
VERIFY(s1.size() == 11);
VERIFY(s1.length() == 11);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "hello world"));
bksge::static_string<N2> const s3("abc");
s1.assign(s3);
VERIFY(!s1.empty());
VERIFY(s1.size() == 3);
VERIFY(s1.length() == 3);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "abc"));
bksge::static_string<N2> const s4("Hello World");
s1.assign(s4, 3, 4);
VERIFY(!s1.empty());
VERIFY(s1.size() == 4);
VERIFY(s1.length() == 4);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "lo W"));
s1.assign(s4, 3, 100);
VERIFY(!s1.empty());
VERIFY(s1.size() == 8);
VERIFY(s1.length() == 8);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "lo World"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool AssignStringMoveTest()
{
{
bksge::static_string<N1> s1;
VERIFY(s1.empty());
bksge::static_string<N2> s2("hello world");
s1 = std::move(s2);
VERIFY(!s1.empty());
VERIFY(s1.size() == 11);
VERIFY(s1.length() == 11);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "hello world"));
bksge::static_string<N2> s3("abc");
s1.assign(std::move(s3));
VERIFY(!s1.empty());
VERIFY(s1.size() == 3);
VERIFY(s1.length() == 3);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "abc"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AssignCharPtrTest()
{
{
bksge::static_string<N> s;
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
s = "hoge";
VERIFY(!s.empty());
VERIFY(s.size() == 4);
VERIFY(s.length() == 4);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "hoge"));
s.assign("a");
VERIFY(!s.empty());
VERIFY(s.size() == 1);
VERIFY(s.length() == 1);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "a"));
s.assign("world", 3);
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "wor"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AssignCharTest()
{
{
bksge::static_string<N> s;
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
s = 'A';
VERIFY(!s.empty());
VERIFY(s.size() == 1);
VERIFY(s.length() == 1);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "A"));
s.assign(2, 'B');
VERIFY(!s.empty());
VERIFY(s.size() == 2);
VERIFY(s.length() == 2);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "BB"));
s = 'C';
VERIFY(!s.empty());
VERIFY(s.size() == 1);
VERIFY(s.length() == 1);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "C"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AssignIteratorTest()
{
{
bksge::static_string<N> s;
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
char buf[] = "hello";
s.assign(buf, buf+5);
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "hello"));
s.assign(buf, buf+3);
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "hel"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AssignInitializerListTest()
{
{
bksge::static_string<N> s;
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
s = {'h', 'e', 'l', 'l', 'o'};
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "hello"));
s.assign({'a', 'b', 'c', 'd'});
VERIFY(!s.empty());
VERIFY(s.size() == 4);
VERIFY(s.length() == 4);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abcd"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AssignStringViewTest()
{
{
bksge::static_string<N> s;
VERIFY(s.empty());
VERIFY(s.size() == 0);
VERIFY(s.length() == 0);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, ""));
s = bksge::string_view{"Hello World"};
VERIFY(!s.empty());
VERIFY(s.size() == 11);
VERIFY(s.length() == 11);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "Hello World"));
s.assign(bksge::string_view{"abc"});
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abc"));
s.assign(bksge::string_view{"Hello World"}, 1, 5);
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "ello "));
s.assign("Hello World", 2, 6);
VERIFY(!s.empty());
VERIFY(s.size() == 6);
VERIFY(s.length() == 6);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "llo Wo"));
s.assign(bksge::string_view{"Hello World"}, 2, 100);
VERIFY(!s.empty());
VERIFY(s.size() == 9);
VERIFY(s.length() == 9);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "llo World"));
}
return true;
}
GTEST_TEST(StaticStringTest, AssignTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringMoveTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringMoveTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringMoveTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringMoveTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringMoveTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AssignStringMoveTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignIteratorTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignIteratorTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignIteratorTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignInitializerListTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignInitializerListTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignInitializerListTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AssignStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool AppendStringTest()
{
{
bksge::static_string<N1> s1;
VERIFY(s1.empty());
bksge::static_string<N2> const s2 = "abc";
s1 += s2;
VERIFY(!s1.empty());
VERIFY(s1.size() == 3);
VERIFY(s1.length() == 3);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "abc"));
bksge::static_string<N2> const s3 = "hello";
s1.append(s3);
VERIFY(!s1.empty());
VERIFY(s1.size() == 8);
VERIFY(s1.length() == 8);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "abchello"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool AppendStringPosTest()
{
{
bksge::static_string<N1> s1;
VERIFY(s1.empty());
bksge::static_string<N2> const s2 = "abc";
s1.append(s2, 1);
VERIFY(!s1.empty());
VERIFY(s1.size() == 2);
VERIFY(s1.length() == 2);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "bc"));
bksge::static_string<N2> const s3 = "hello";
s1.append(s3, 2, 3);
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "bcllo"));
bksge::static_string<N2> const s4 = "world";
s1.append(s4, 1, 10);
VERIFY(!s1.empty());
VERIFY(s1.size() == 9);
VERIFY(s1.length() == 9);
VERIFY(s1.max_size() == N1);
VERIFY(s1.capacity() == N1);
VERIFY(c_str_test(s1, "bclloorld"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AppendCharPtrTest()
{
{
bksge::static_string<N> s1;
VERIFY(s1.empty());
s1 += "hello";
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "hello"));
s1.append(" world");
VERIFY(!s1.empty());
VERIFY(s1.size() == 11);
VERIFY(s1.length() == 11);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "hello world"));
s1.append("ABCDE", 2);
VERIFY(!s1.empty());
VERIFY(s1.size() == 13);
VERIFY(s1.length() == 13);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "hello worldAB"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AppendCharTest()
{
{
bksge::static_string<N> s1;
VERIFY(s1.empty());
s1 += 'A';
VERIFY(!s1.empty());
VERIFY(s1.size() == 1);
VERIFY(s1.length() == 1);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "A"));
s1.append(3, 'B');
VERIFY(!s1.empty());
VERIFY(s1.size() == 4);
VERIFY(s1.length() == 4);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "ABBB"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AppendInitializerListTest()
{
{
bksge::static_string<N> s1;
VERIFY(s1.empty());
s1 += { 'A', 'B', 'C' };
VERIFY(!s1.empty());
VERIFY(s1.size() == 3);
VERIFY(s1.length() == 3);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "ABC"));
s1.append({ 'h', 'e', 'l', 'l', 'o' });
VERIFY(!s1.empty());
VERIFY(s1.size() == 8);
VERIFY(s1.length() == 8);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "ABChello"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AppendIteratorTest()
{
{
bksge::static_string<N> s1;
VERIFY(s1.empty());
char buf[] = "hello";
s1.append(buf, buf+5);
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "hello"));
s1.append(buf+1, buf+3);
VERIFY(!s1.empty());
VERIFY(s1.size() == 7);
VERIFY(s1.length() == 7);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "helloel"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AppendStringViewTest()
{
{
bksge::static_string<N> s1;
VERIFY(s1.empty());
s1 += bksge::string_view{"Hel"};
VERIFY(!s1.empty());
VERIFY(s1.size() == 3);
VERIFY(s1.length() == 3);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "Hel"));
s1.append(bksge::string_view{"lo"});
VERIFY(!s1.empty());
VERIFY(s1.size() == 5);
VERIFY(s1.length() == 5);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "Hello"));
s1.append(bksge::string_view{"abcde"}, 2);
VERIFY(!s1.empty());
VERIFY(s1.size() == 8);
VERIFY(s1.length() == 8);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "Hellocde"));
s1.append(bksge::string_view{"ABCDE"}, 1, 3);
VERIFY(!s1.empty());
VERIFY(s1.size() == 11);
VERIFY(s1.length() == 11);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "HellocdeBCD"));
s1.append("ABCDE", 2, 2);
VERIFY(!s1.empty());
VERIFY(s1.size() == 13);
VERIFY(s1.length() == 13);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "HellocdeBCDCD"));
}
return true;
}
GTEST_TEST(StaticStringTest, AppendTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringPosTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringPosTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringPosTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringPosTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringPosTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AppendStringPosTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendInitializerListTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendInitializerListTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendInitializerListTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendIteratorTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendIteratorTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendIteratorTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AppendStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool InsertStringTest()
{
{
bksge::static_string<N1> s1 = "aaa";
bksge::static_string<N2> s2 = "bbb";
s1.insert(2, s2);
VERIFY(c_str_test(s1, "aabbba"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool InsertStringPosTest()
{
{
bksge::static_string<N1> s1 = "aaa";
bksge::static_string<N2> s2 = "12345";
s1.insert(2, s2, 2, 3);
VERIFY(c_str_test(s1, "aa345a"));
}
{
bksge::static_string<N1> s1 = "aaa";
bksge::static_string<N2> s2 = "12345";
s1.insert(3, s2, 1);
VERIFY(c_str_test(s1, "aaa2345"));
}
{
bksge::static_string<N1> s1 = "aaa";
bksge::static_string<N2> s2 = "12345";
s1.insert(1, s2, 1, 100);
VERIFY(c_str_test(s1, "a2345aa"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool InsertCharPtrCountTest()
{
{
bksge::static_string<N> s1 = "aaa";
s1.insert(2, "12345", 2);
VERIFY(c_str_test(s1, "aa12a"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(2, "12345", 0);
VERIFY(c_str_test(s1, "aaa"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool InsertCharPtrTest()
{
{
bksge::static_string<N> s1 = "aaa";
s1.insert(1, "12345");
VERIFY(c_str_test(s1, "a12345aa"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool InsertCharTest()
{
{
bksge::static_string<N> s1 = "aaa";
s1.insert(2, 3, 'b');
VERIFY(c_str_test(s1, "aabbba"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(2, 0, 'b');
VERIFY(c_str_test(s1, "aaa"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(s1.begin(), 'b');
VERIFY(c_str_test(s1, "baaa"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(s1.end(), 'c');
VERIFY(c_str_test(s1, "aaac"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(s1.begin(), 2, 'b');
VERIFY(c_str_test(s1, "bbaaa"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(s1.end(), 3, 'c');
VERIFY(c_str_test(s1, "aaaccc"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(s1.end(), 0, 'c');
VERIFY(c_str_test(s1, "aaa"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool InsertIteratorTest()
{
{
bksge::static_string<N> s1 = "aaa";
char buf[] = "xyz";
s1.insert(s1.begin(), buf, buf+3);
VERIFY(c_str_test(s1, "xyzaaa"));
}
{
bksge::static_string<N> s1 = "aaa";
char buf[] = "xyz";
s1.insert(s1.end(), buf, buf+3);
VERIFY(c_str_test(s1, "aaaxyz"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool InsertInitializerListTest()
{
{
bksge::static_string<N> s1 = "aaa";
s1.insert(s1.begin()+1, {'1', '2', '3', '4', '5'});
VERIFY(c_str_test(s1, "a12345aa"));
}
{
bksge::static_string<N> s1 = "aaa";
s1.insert(s1.end(), {'b', 'c'});
VERIFY(c_str_test(s1, "aaabc"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool InsertStringViewTest()
{
{
bksge::static_string<N> s1 = "abcde";
s1.insert(0, bksge::string_view{"xyz"});
VERIFY(c_str_test(s1, "xyzabcde"));
}
{
bksge::static_string<N> s1 = "abcde";
s1.insert(1, bksge::string_view{"12345"}, 1);
VERIFY(c_str_test(s1, "a2345bcde"));
}
{
bksge::static_string<N> s1 = "abcde";
s1.insert(2, bksge::string_view{"12345"}, 2, 3);
VERIFY(c_str_test(s1, "ab345cde"));
}
{
bksge::static_string<N> s1 = "abcde";
s1.insert(2, bksge::string_view{"12345"}, 2, 4);
VERIFY(c_str_test(s1, "ab345cde"));
}
return true;
}
GTEST_TEST(StaticStringTest, InsertTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringPosTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringPosTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringPosTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringPosTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringPosTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((InsertStringPosTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharPtrCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharPtrCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharPtrCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertIteratorTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertIteratorTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertIteratorTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertInitializerListTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertInitializerListTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertInitializerListTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(InsertStringViewTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ErasePosCountTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.erase(1, 2);
VERIFY(c_str_test(s1, "145"));
}
{
bksge::static_string<N> s1 = "12345";
s1.erase(2);
VERIFY(c_str_test(s1, "12"));
}
{
bksge::static_string<N> s1 = "12345";
s1.erase();
VERIFY(c_str_test(s1, ""));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool EraseIteratorTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.erase(s1.begin());
VERIFY(c_str_test(s1, "2345"));
}
{
bksge::static_string<N> s1 = "12345";
s1.erase(s1.begin()+1);
VERIFY(c_str_test(s1, "1345"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool EraseFirstLastTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.erase(s1.begin(), s1.begin()+2);
VERIFY(c_str_test(s1, "345"));
}
{
bksge::static_string<N> s1 = "12345";
s1.erase(s1.begin()+2, s1.end());
VERIFY(c_str_test(s1, "12"));
}
return true;
}
GTEST_TEST(StaticStringTest, EraseTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ErasePosCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ErasePosCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ErasePosCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EraseIteratorTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EraseIteratorTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EraseIteratorTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EraseFirstLastTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EraseFirstLastTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EraseFirstLastTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool ReplacePosCountStringTest()
{
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "abcde";
s1.replace(1, 2, s2);
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "abcde";
s1.replace(2, 100, s2);
VERIFY(c_str_test(s1, "12abcde"));
}
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "a";
s1.replace(1, 2, s2);
VERIFY(c_str_test(s1, "1a45"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool ReplacePosCountStringPosCountTest()
{
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "abcde";
s1.replace(1, 2, s2, 2, 3);
VERIFY(c_str_test(s1, "1cde45"));
}
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "abcde";
s1.replace(2, 1, s2, 1);
VERIFY(c_str_test(s1, "12bcde45"));
}
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "abcde";
s1.replace(1, 2, s2, 2, 1);
VERIFY(c_str_test(s1, "1c45"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplacePosCountCharPtrCountTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 2, "abcde", 3);
VERIFY(c_str_test(s1, "1abc45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(2, 100, "abcde", 2);
VERIFY(c_str_test(s1, "12ab"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplacePosCountCharPtrTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 2, "abcde");
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(2, 100, "abcde");
VERIFY(c_str_test(s1, "12abcde"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 3, "z");
VERIFY(c_str_test(s1, "1z5"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplacePosCountCountCharTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 2, 3, 'x');
VERIFY(c_str_test(s1, "1xxx45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(2, 100, 4, 'y');
VERIFY(c_str_test(s1, "12yyyy"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 3, 1, 'z');
VERIFY(c_str_test(s1, "1z5"));
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool ReplaceIteratorStringTest()
{
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "abcde";
s1.replace(s1.begin() + 1, s1.begin() + 3, s2);
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "abcde";
s1.replace(s1.begin(), s1.end(), s2);
VERIFY(c_str_test(s1, "abcde"));
}
{
bksge::static_string<N1> s1 = "12345";
bksge::static_string<N2> s2 = "xy";
s1.replace(s1.begin() + 1, s1.begin() + 4, s2);
VERIFY(c_str_test(s1, "1xy5"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplaceIteratorCharPtrCountTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin() + 1, s1.begin() + 3, "abcde", 3);
VERIFY(c_str_test(s1, "1abc45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin(), s1.end(), "abcde", 2);
VERIFY(c_str_test(s1, "ab"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplaceIteratorCharPtrTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin() + 1, s1.begin() + 3, "abcde");
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin(), s1.end(), "abcde");
VERIFY(c_str_test(s1, "abcde"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin() + 1, s1.begin() + 4, "xy");
VERIFY(c_str_test(s1, "1xy5"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplaceIteratorCountCharTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin() + 1, s1.begin() + 3, 3, 'x');
VERIFY(c_str_test(s1, "1xxx45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin(), s1.end(), 2, 'y');
VERIFY(c_str_test(s1, "yy"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplaceIteratorIteratorTest()
{
{
bksge::static_string<N> s1 = "12345";
bksge::static_string<N> s2 = "abcde";
s1.replace(s1.begin() + 1, s1.begin() + 3, s2.begin(), s2.end());
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N> s1 = "12345";
bksge::static_string<N> s2 = "abcde";
s1.replace(s1.begin(), s1.end(), s2.begin(), s2.end());
VERIFY(c_str_test(s1, "abcde"));
}
{
bksge::static_string<N> s1 = "12345";
bksge::static_string<N> s2 = "abcde";
s1.replace(s1.begin() + 1, s1.begin() + 3, s2.begin(), s2.begin()+1);
VERIFY(c_str_test(s1, "1a45"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplaceIteratorInitializerListTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin() + 1, s1.begin() + 3, {'a', 'b', 'c', 'd', 'e'});
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin(), s1.end(), {'a', 'b', 'c', 'd'});
VERIFY(c_str_test(s1, "abcd"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplacePosCountStringViewTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 2, bksge::string_view{"abcde"});
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 100, bksge::string_view{"abcde"});
VERIFY(c_str_test(s1, "1abcde"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 3, bksge::string_view{"A"});
VERIFY(c_str_test(s1, "1A5"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplacePosCountStringViewPosCountTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 2, bksge::string_view{"XXXabcdeYYY"}, 3, 5);
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(2, 2, bksge::string_view{"XXXabcdeYYY"}, 3);
VERIFY(c_str_test(s1, "12abcdeYYY5"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(2, 1, "abcde", 2, 3);
VERIFY(c_str_test(s1, "12cde45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(1, 3, "abcde", 2, 1);
VERIFY(c_str_test(s1, "1c5"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReplaceIteratorStringViewTest()
{
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin() + 1, s1.begin() + 3, bksge::string_view{"abcde"});
VERIFY(c_str_test(s1, "1abcde45"));
}
{
bksge::static_string<N> s1 = "12345";
s1.replace(s1.begin(), s1.end(), bksge::string_view{"abc"});
VERIFY(c_str_test(s1, "abc"));
}
return true;
}
GTEST_TEST(StaticStringTest, ReplaceTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringPosCountTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringPosCountTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringPosCountTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringPosCountTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringPosCountTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplacePosCountStringPosCountTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCharPtrCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCharPtrCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCharPtrCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCountCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCountCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountCountCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplaceIteratorStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplaceIteratorStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplaceIteratorStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplaceIteratorStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplaceIteratorStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ReplaceIteratorStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCharPtrCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCharPtrCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCharPtrCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCountCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCountCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorCountCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorIteratorTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorIteratorTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorIteratorTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorInitializerListTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorInitializerListTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorInitializerListTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountStringViewTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountStringViewPosCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountStringViewPosCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplacePosCountStringViewPosCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReplaceIteratorStringViewTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CopyTest()
{
bksge::static_string<N> const s = "hello";
using traits_type = typename bksge::static_string<N>::traits_type;
{
char result[5 + 1] ={};
auto ret = s.copy(result, 5);
VERIFY(traits_type::compare(result, "hello", 5) == 0);
VERIFY(ret == 5);
}
{
char result[3 + 1] ={};
auto ret = s.copy(result, 3);
VERIFY(traits_type::compare(result, "hel", 3) == 0);
VERIFY(ret == 3);
}
{
char result[3 + 1] ={};
auto ret = s.copy(result, 3, 2);
VERIFY(traits_type::compare(result, "llo", 3) == 0);
VERIFY(ret == 3);
}
{
char result[5 + 1] ={};
auto ret = s.copy(result, 100, 1);
VERIFY(traits_type::compare(result, "ello", 4) == 0);
VERIFY(ret == 4);
}
return true;
}
GTEST_TEST(StaticStringTest, CopyTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CopyTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CopyTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CopyTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool PushBackTest()
{
{
bksge::static_string<N> s1;
VERIFY(s1.empty());
s1.push_back('a');
VERIFY(!s1.empty());
VERIFY(s1.size() == 1);
VERIFY(s1.length() == 1);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "a"));
s1.push_back('b');
VERIFY(!s1.empty());
VERIFY(s1.size() == 2);
VERIFY(s1.length() == 2);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "ab"));
}
return true;
}
GTEST_TEST(StaticStringTest, PushBackTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(PushBackTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(PushBackTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(PushBackTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool PopBackTest()
{
{
bksge::static_string<N> s1 = "abc";
VERIFY(!s1.empty());
VERIFY(s1.size() == 3);
VERIFY(s1.length() == 3);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "abc"));
s1.pop_back();
VERIFY(!s1.empty());
VERIFY(s1.size() == 2);
VERIFY(s1.length() == 2);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "ab"));
s1.pop_back();
VERIFY(!s1.empty());
VERIFY(s1.size() == 1);
VERIFY(s1.length() == 1);
VERIFY(s1.max_size() == N);
VERIFY(s1.capacity() == N);
VERIFY(c_str_test(s1, "a"));
}
return true;
}
GTEST_TEST(StaticStringTest, PopBackTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(PopBackTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(PopBackTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(PopBackTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool BeginEndTest()
{
{
bksge::static_string<N> s = "abc";
auto it = s.begin();
VERIFY(*it == 'a');
*it++ = 'X';
VERIFY(*it == 'b');
++it;
VERIFY(*it == 'c');
VERIFY(it != s.end());
++it;
VERIFY(it == s.end());
VERIFY(c_str_test(s, "Xbc"));
}
{
bksge::static_string<N> const s = "abc";
auto it = s.begin();
VERIFY(*it++ == 'a');
VERIFY(*it == 'b');
++it;
VERIFY(*it == 'c');
VERIFY(it != s.end());
++it;
VERIFY(it == s.end());
VERIFY(c_str_test(s, "abc"));
}
{
bksge::static_string<N> s = "abc";
auto it = s.cbegin();
VERIFY(*it++ == 'a');
VERIFY(*it == 'b');
++it;
VERIFY(*it == 'c');
VERIFY(it != s.cend());
++it;
VERIFY(it == s.cend());
VERIFY(c_str_test(s, "abc"));
}
return true;
}
GTEST_TEST(StaticStringTest, BeginEndTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(BeginEndTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(BeginEndTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(BeginEndTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool RBeginREndTest()
{
{
bksge::static_string<N> s = "abc";
auto it = s.rbegin();
VERIFY(*it == 'c');
*it++ = 'X';
VERIFY(*it == 'b');
++it;
VERIFY(*it == 'a');
VERIFY(it != s.rend());
++it;
VERIFY(it == s.rend());
VERIFY(c_str_test(s, "abX"));
}
{
bksge::static_string<N> const s = "abc";
auto it = s.rbegin();
VERIFY(*it++ == 'c');
VERIFY(*it == 'b');
++it;
VERIFY(*it == 'a');
VERIFY(it != s.rend());
++it;
VERIFY(it == s.rend());
VERIFY(c_str_test(s, "abc"));
}
{
bksge::static_string<N> s = "abc";
auto it = s.crbegin();
VERIFY(*it++ == 'c');
VERIFY(*it == 'b');
++it;
VERIFY(*it == 'a');
VERIFY(it != s.crend());
++it;
VERIFY(it == s.crend());
VERIFY(c_str_test(s, "abc"));
}
return true;
}
GTEST_TEST(StaticStringTest, RBeginREndTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RBeginREndTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RBeginREndTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RBeginREndTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ResizeTest()
{
{
bksge::static_string<N> s = "abc";
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abc"));
s.resize(5, 'X');
VERIFY(!s.empty());
VERIFY(s.size() == 5);
VERIFY(s.length() == 5);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abcXX"));
s.resize(4, 'Y');
VERIFY(!s.empty());
VERIFY(s.size() == 4);
VERIFY(s.length() == 4);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "abcX"));
s.resize(6);
VERIFY(!s.empty());
VERIFY(s.size() == 6);
VERIFY(s.length() == 6);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
//VERIFY(s.compare("abcX") == 0);
s.resize(2);
VERIFY(!s.empty());
VERIFY(s.size() == 2);
VERIFY(s.length() == 2);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
VERIFY(c_str_test(s, "ab"));
}
return true;
}
GTEST_TEST(StaticStringTest, ResizeTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ResizeTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ResizeTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ResizeTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ReserveTest()
{
{
bksge::static_string<N> s = "abc";
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
s.reserve(10);
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
s.reserve();
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
s.shrink_to_fit();
VERIFY(!s.empty());
VERIFY(s.size() == 3);
VERIFY(s.length() == 3);
VERIFY(s.max_size() == N);
VERIFY(s.capacity() == N);
}
return true;
}
GTEST_TEST(StaticStringTest, ReserveTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReserveTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReserveTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ReserveTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ClearTest()
{
{
bksge::static_string<N> s = "abc";
VERIFY(!s.empty());
VERIFY(c_str_test(s, "abc"));
s.clear();
VERIFY(s.empty());
VERIFY(c_str_test(s, ""));
}
return true;
}
GTEST_TEST(StaticStringTest, ClearTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ClearTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ClearTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ClearTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool BraceTest()
{
{
bksge::static_string<N> const s = "abc";
VERIFY(s[0] == 'a');
VERIFY(s[1] == 'b');
VERIFY(s[2] == 'c');
}
{
bksge::static_string<N> s = "abc";
s[1] = 'Z';
VERIFY(c_str_test(s, "aZc"));
}
return true;
}
GTEST_TEST(StaticStringTest, BraceTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(BraceTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(BraceTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(BraceTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AtTest()
{
{
bksge::static_string<N> const s = "abc";
VERIFY(s.at(0) == 'a');
VERIFY(s.at(1) == 'b');
VERIFY(s.at(2) == 'c');
}
{
bksge::static_string<N> s = "abc";
s.at(1) = 'Z';
VERIFY(c_str_test(s, "aZc"));
}
return true;
}
GTEST_TEST(StaticStringTest, AtTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AtTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AtTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AtTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FrontBackTest()
{
{
bksge::static_string<N> const s = "abc";
VERIFY(s.front() == 'a');
VERIFY(s.back() == 'c');
}
{
bksge::static_string<N> s = "abc";
s.front() = 'X';
s.back() = 'Y';
VERIFY(c_str_test(s, "XbY"));
}
return true;
}
GTEST_TEST(StaticStringTest, FrontBackTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FrontBackTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FrontBackTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FrontBackTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool CompareStringTest()
{
{
bksge::static_string<N1> const s1 = "12345";
bksge::static_string<N2> const s2 = "12345";
bksge::static_string<N2> const s3 = "123456";
bksge::static_string<N2> const s4 = "1234";
bksge::static_string<N2> const s5 = "12346";
bksge::static_string<N2> const s6 = "12344";
VERIFY(s1.compare(s1) == 0);
VERIFY(s1.compare(s2) == 0);
VERIFY(s1.compare(s3) < 0);
VERIFY(s1.compare(s4) > 0);
VERIFY(s1.compare(s5) < 0);
VERIFY(s1.compare(s6) > 0);
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool ComparePosCountStringTest()
{
{
bksge::static_string<N1> const s1 = "123456";
bksge::static_string<N2> const s2 = "12345";
VERIFY(s1.compare(0, 5, s2) == 0); // "12345", "12345"
VERIFY(s1.compare(0, 9, s2) > 0); // "123456", "12345"
VERIFY(s1.compare(1, 5, s2) > 0); // "23456", "12345"
VERIFY(s1.compare(0, 4, s2) < 0); // "1234", "12345"
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool ComparePosCountStringPosCountTest()
{
{
bksge::static_string<N1> const s1 = "12345";
bksge::static_string<N2> const s2 = "123456";
VERIFY(s1.compare(0, 5, s2, 0, 5) == 0); // "12345", "12345"
VERIFY(s1.compare(0, 6, s2, 0) < 0); // "12345", "123456"
VERIFY(s1.compare(0, 4, s2, 0, 5) < 0); // "1234", "12345"
VERIFY(s1.compare(0, 4, s2, 0, 3) > 0); // "1234", "123"
VERIFY(s1.compare(1, 3, s2, 1, 3) == 0); // "234", "234"
VERIFY(s1.compare(1, 3, s2, 0, 3) > 0); // "234", "123"
VERIFY(s1.compare(1, 4, s2, 2, 3) < 0); // "2345", "345"
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CompareCharPtrTest()
{
{
bksge::static_string<N> const s1 = "12345";
char const* s2 = "12345";
char const* s3 = "123456";
char const* s4 = "1234";
char const* s5 = "12346";
char const* s6 = "12344";
VERIFY(s1.compare(s1) == 0);
VERIFY(s1.compare(s2) == 0);
VERIFY(s1.compare(s3) < 0);
VERIFY(s1.compare(s4) > 0);
VERIFY(s1.compare(s5) < 0);
VERIFY(s1.compare(s6) > 0);
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ComparePosCountCharPtrTest()
{
{
bksge::static_string<N> const s1 = "123456";
char const* s2 = "12345";
VERIFY(s1.compare(0, 5, s2) == 0); // "12345", "12345"
VERIFY(s1.compare(0, 9, s2) > 0); // "123456", "12345"
VERIFY(s1.compare(1, 5, s2) > 0); // "23456", "12345"
VERIFY(s1.compare(0, 4, s2) < 0); // "1234", "12345"
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ComparePosCountCharPtrCountTest()
{
{
bksge::static_string<N> const s1 = "12345";
char const* s2 = "123456";
VERIFY(s1.compare(0, 5, s2, 5) == 0); // "12345", "12345"
VERIFY(s1.compare(0, 5, s2, 9) < 0); // "12345", "123456"
VERIFY(s1.compare(1, 4, s2, 9) > 0); // "2345", "123456"
VERIFY(s1.compare(0, 4, s2, 5) < 0); // "1234", "12345"
VERIFY(s1.compare(0, 4, s2, 3) > 0); // "1234", "123"
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CompareStringViewTest()
{
{
bksge::static_string<N> const s1 = "12345";
bksge::string_view const s2 = "12345";
bksge::string_view const s3 = "123456";
bksge::string_view const s4 = "1234";
bksge::string_view const s5 = "12346";
bksge::string_view const s6 = "12344";
VERIFY(s1.compare(s1) == 0);
VERIFY(s1.compare(s2) == 0);
VERIFY(s1.compare(s3) < 0);
VERIFY(s1.compare(s4) > 0);
VERIFY(s1.compare(s5) < 0);
VERIFY(s1.compare(s6) > 0);
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ComparePosCountStringViewTest()
{
{
bksge::static_string<N> const s1 = "123456";
bksge::string_view const s2 = "12345";
VERIFY(s1.compare(0, 5, s2) == 0); // "12345", "12345"
VERIFY(s1.compare(0, 9, s2) > 0); // "123456", "12345"
VERIFY(s1.compare(1, 5, s2) > 0); // "23456", "12345"
VERIFY(s1.compare(0, 4, s2) < 0); // "1234", "12345"
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool ComparePosCountStringViewPosCountTest()
{
{
bksge::static_string<N> const s1 = "12345";
bksge::string_view const s2 = "123456";
VERIFY(s1.compare(0, 5, s2, 0, 5) == 0); // "12345", "12345"
VERIFY(s1.compare(0, 6, s2, 0) < 0); // "12345", "123456"
VERIFY(s1.compare(0, 4, s2, 0, 5) < 0); // "1234", "12345"
VERIFY(s1.compare(0, 4, s2, 0, 3) > 0); // "1234", "123"
VERIFY(s1.compare(1, 3, s2, 1, 3) == 0); // "234", "234"
VERIFY(s1.compare(1, 3, s2, 0, 3) > 0); // "234", "123"
VERIFY(s1.compare(1, 4, s2, 2, 3) < 0); // "2345", "345"
}
return true;
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool CompareOperatorStringTest()
{
{
bksge::static_string<N1> const s1 = "abc";
bksge::static_string<N2> const s2 = "abc";
bksge::static_string<N2> const s3 = "abcd";
bksge::static_string<N2> const s4 = "ab";
bksge::static_string<N2> const s5 = "abe";
bksge::static_string<N2> const s6 = "aba";
VERIFY((s1 == s1) == true);
VERIFY((s1 == s2) == true);
VERIFY((s1 == s3) == false);
VERIFY((s1 == s4) == false);
VERIFY((s1 == s5) == false);
VERIFY((s1 == s6) == false);
VERIFY((s1 != s1) == false);
VERIFY((s1 != s2) == false);
VERIFY((s1 != s3) == true);
VERIFY((s1 != s4) == true);
VERIFY((s1 != s5) == true);
VERIFY((s1 != s6) == true);
VERIFY((s1 < s1) == false);
VERIFY((s1 < s2) == false);
VERIFY((s1 < s3) == true);
VERIFY((s1 < s4) == false);
VERIFY((s1 < s5) == true);
VERIFY((s1 < s6) == false);
VERIFY((s1 > s1) == false);
VERIFY((s1 > s2) == false);
VERIFY((s1 > s3) == false);
VERIFY((s1 > s4) == true);
VERIFY((s1 > s5) == false);
VERIFY((s1 > s6) == true);
VERIFY((s1 <= s1) == true);
VERIFY((s1 <= s2) == true);
VERIFY((s1 <= s3) == true);
VERIFY((s1 <= s4) == false);
VERIFY((s1 <= s5) == true);
VERIFY((s1 <= s6) == false);
VERIFY((s1 >= s1) == true);
VERIFY((s1 >= s2) == true);
VERIFY((s1 >= s3) == false);
VERIFY((s1 >= s4) == true);
VERIFY((s1 >= s5) == false);
VERIFY((s1 >= s6) == true);
#if defined(BKSGE_HAS_CXX20_THREE_WAY_COMPARISON) && defined(BKSGE_HAS_STD_COMPARE)
VERIFY(bksge::is_eq(s1 <=> s1));
VERIFY(bksge::is_eq(s1 <=> s2));
VERIFY(bksge::is_lt(s1 <=> s3));
VERIFY(bksge::is_gt(s1 <=> s4));
VERIFY(bksge::is_lt(s1 <=> s5));
VERIFY(bksge::is_gt(s1 <=> s6));
#endif
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool CompareOperatorCharPtrTest()
{
{
bksge::static_string<N> const s1 = "abc";
char const* s2 = "abc";
char const* s3 = "abcd";
char const* s4 = "ab";
char const* s5 = "abe";
char const* s6 = "aba";
VERIFY((s1 == s2) == true);
VERIFY((s1 == s3) == false);
VERIFY((s1 == s4) == false);
VERIFY((s1 == s5) == false);
VERIFY((s1 == s6) == false);
VERIFY((s1 != s2) == false);
VERIFY((s1 != s3) == true);
VERIFY((s1 != s4) == true);
VERIFY((s1 != s5) == true);
VERIFY((s1 != s6) == true);
VERIFY((s1 < s2) == false);
VERIFY((s1 < s3) == true);
VERIFY((s1 < s4) == false);
VERIFY((s1 < s5) == true);
VERIFY((s1 < s6) == false);
VERIFY((s1 > s2) == false);
VERIFY((s1 > s3) == false);
VERIFY((s1 > s4) == true);
VERIFY((s1 > s5) == false);
VERIFY((s1 > s6) == true);
VERIFY((s1 <= s2) == true);
VERIFY((s1 <= s3) == true);
VERIFY((s1 <= s4) == false);
VERIFY((s1 <= s5) == true);
VERIFY((s1 <= s6) == false);
VERIFY((s1 >= s2) == true);
VERIFY((s1 >= s3) == false);
VERIFY((s1 >= s4) == true);
VERIFY((s1 >= s5) == false);
VERIFY((s1 >= s6) == true);
VERIFY((s2 == s1) == true);
VERIFY((s3 == s1) == false);
VERIFY((s4 == s1) == false);
VERIFY((s5 == s1) == false);
VERIFY((s6 == s1) == false);
VERIFY((s2 != s1) == false);
VERIFY((s3 != s1) == true);
VERIFY((s4 != s1) == true);
VERIFY((s5 != s1) == true);
VERIFY((s6 != s1) == true);
VERIFY((s2 < s1) == false);
VERIFY((s3 < s1) == false);
VERIFY((s4 < s1) == true);
VERIFY((s5 < s1) == false);
VERIFY((s6 < s1) == true);
VERIFY((s2 > s1) == false);
VERIFY((s3 > s1) == true);
VERIFY((s4 > s1) == false);
VERIFY((s5 > s1) == true);
VERIFY((s6 > s1) == false);
VERIFY((s2 <= s1) == true);
VERIFY((s3 <= s1) == false);
VERIFY((s4 <= s1) == true);
VERIFY((s5 <= s1) == false);
VERIFY((s6 <= s1) == true);
VERIFY((s2 >= s1) == true);
VERIFY((s3 >= s1) == true);
VERIFY((s4 >= s1) == false);
VERIFY((s5 >= s1) == true);
VERIFY((s6 >= s1) == false);
#if defined(BKSGE_HAS_CXX20_THREE_WAY_COMPARISON) && defined(BKSGE_HAS_STD_COMPARE)
VERIFY(bksge::is_eq(s1 <=> s1));
VERIFY(bksge::is_eq(s1 <=> s2));
VERIFY(bksge::is_lt(s1 <=> s3));
VERIFY(bksge::is_gt(s1 <=> s4));
VERIFY(bksge::is_lt(s1 <=> s5));
VERIFY(bksge::is_gt(s1 <=> s6));
#endif
}
return true;
}
GTEST_TEST(StaticStringTest, CompareTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringPosCountTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringPosCountTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringPosCountTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringPosCountTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringPosCountTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((ComparePosCountStringPosCountTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountCharPtrCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountCharPtrCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountCharPtrCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareStringViewTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountStringViewTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountStringViewPosCountTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountStringViewPosCountTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(ComparePosCountStringViewPosCountTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareOperatorStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareOperatorStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareOperatorStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareOperatorStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareOperatorStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((CompareOperatorStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareOperatorCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareOperatorCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(CompareOperatorCharPtrTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool FindStringTest()
{
bksge::static_string<N1> const s1 = "ab abc abcd";
VERIFY(s1.find(bksge::static_string<N2>{"a"}) == 0);
VERIFY(s1.find(bksge::static_string<N2>{"ab"}) == 0);
VERIFY(s1.find(bksge::static_string<N2>{"abc"}) == 3);
VERIFY(s1.find(bksge::static_string<N2>{"abcd"}) == 7);
VERIFY(s1.find(bksge::static_string<N2>{"abcde"}) == bksge::static_string<N1>::npos);
VERIFY(s1.find(bksge::static_string<N2>{"a"}, 1) == 3);
VERIFY(s1.find(bksge::static_string<N2>{"ab"}, 1) == 3);
VERIFY(s1.find(bksge::static_string<N2>{"abc"}, 1) == 3);
VERIFY(s1.find(bksge::static_string<N2>{"abcd"}, 1) == 7);
VERIFY(s1.find(bksge::static_string<N2>{"abcde"}, 1) == bksge::static_string<N1>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindCharPtrTest()
{
bksge::static_string<N> const s1 = "ab abc abcd";
VERIFY(s1.find("a") == 0);
VERIFY(s1.find("ab") == 0);
VERIFY(s1.find("abc") == 3);
VERIFY(s1.find("abcd") == 7);
VERIFY(s1.find("abcde") == bksge::static_string<N>::npos);
VERIFY(s1.find("a", 1) == 3);
VERIFY(s1.find("ab", 1) == 3);
VERIFY(s1.find("abc", 1) == 3);
VERIFY(s1.find("abcd", 1) == 7);
VERIFY(s1.find("abcde", 1) == bksge::static_string<N>::npos);
VERIFY(s1.find("abcde", 1, 1) == 3);
VERIFY(s1.find("abcde", 1, 2) == 3);
VERIFY(s1.find("abcde", 1, 3) == 3);
VERIFY(s1.find("abcde", 1, 4) == 7);
VERIFY(s1.find("abcde", 1, 5) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindCharTest()
{
bksge::static_string<N> const s1 = "ab abc abcd";
VERIFY(s1.find('a') == 0);
VERIFY(s1.find('b') == 1);
VERIFY(s1.find('c') == 5);
VERIFY(s1.find('d') == 10);
VERIFY(s1.find('e') == bksge::static_string<N>::npos);
VERIFY(s1.find('a', 1) == 3);
VERIFY(s1.find('a', 4) == 7);
VERIFY(s1.find('a', 8) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindStringViewTest()
{
bksge::static_string<N> const s1 = "ab abc abcd";
VERIFY(s1.find(bksge::string_view{"a"}) == 0);
VERIFY(s1.find(bksge::string_view{"ab"}) == 0);
VERIFY(s1.find(bksge::string_view{"abc"}) == 3);
VERIFY(s1.find(bksge::string_view{"abcd"}) == 7);
VERIFY(s1.find(bksge::string_view{"abcde"}) == bksge::static_string<N>::npos);
VERIFY(s1.find(bksge::string_view{"a"}, 1) == 3);
VERIFY(s1.find(bksge::string_view{"ab"}, 1) == 3);
VERIFY(s1.find(bksge::string_view{"abc"}, 1) == 3);
VERIFY(s1.find(bksge::string_view{"abcd"}, 1) == 7);
VERIFY(s1.find(bksge::string_view{"abcde"}, 1) == bksge::static_string<N>::npos);
return true;
}
GTEST_TEST(StaticStringTest, FindTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool RFindStringTest()
{
bksge::static_string<N1> const s1 = "abcd abc ab";
VERIFY(s1.rfind(bksge::static_string<N2>{"a"}) == 9);
VERIFY(s1.rfind(bksge::static_string<N2>{"ab"}) == 9);
VERIFY(s1.rfind(bksge::static_string<N2>{"abc"}) == 5);
VERIFY(s1.rfind(bksge::static_string<N2>{"abcd"}) == 0);
VERIFY(s1.rfind(bksge::static_string<N2>{"abcde"}) == bksge::static_string<N1>::npos);
VERIFY(s1.rfind(bksge::static_string<N2>{"a"}, 10) == 9);
VERIFY(s1.rfind(bksge::static_string<N2>{"ab"}, 10) == 9);
VERIFY(s1.rfind(bksge::static_string<N2>{"abc"}, 10) == 5);
VERIFY(s1.rfind(bksge::static_string<N2>{"abcd"}, 10) == 0);
VERIFY(s1.rfind(bksge::static_string<N2>{"abcde"}, 10) == bksge::static_string<N1>::npos);
VERIFY(s1.rfind(bksge::static_string<N2>{"a"}, 8) == 5);
VERIFY(s1.rfind(bksge::static_string<N2>{"ab"}, 8) == 5);
VERIFY(s1.rfind(bksge::static_string<N2>{"abc"}, 8) == 5);
VERIFY(s1.rfind(bksge::static_string<N2>{"abcd"}, 8) == 0);
VERIFY(s1.rfind(bksge::static_string<N2>{"abcde"}, 8) == bksge::static_string<N1>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool RFindCharPtrTest()
{
bksge::static_string<N> const s1 = "abcd abc ab";
VERIFY(s1.rfind("a") == 9);
VERIFY(s1.rfind("ab") == 9);
VERIFY(s1.rfind("abc") == 5);
VERIFY(s1.rfind("abcd") == 0);
VERIFY(s1.rfind("abcde") == bksge::static_string<N>::npos);
VERIFY(s1.rfind("a", 6) == 5);
VERIFY(s1.rfind("ab", 6) == 5);
VERIFY(s1.rfind("abc", 6) == 5);
VERIFY(s1.rfind("abcd", 6) == 0);
VERIFY(s1.rfind("abcde", 6) == bksge::static_string<N>::npos);
VERIFY(s1.rfind("abcde", 7, 1) == 5);
VERIFY(s1.rfind("abcde", 7, 2) == 5);
VERIFY(s1.rfind("abcde", 7, 3) == 5);
VERIFY(s1.rfind("abcde", 7, 4) == 0);
VERIFY(s1.rfind("abcde", 7, 5) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool RFindCharTest()
{
bksge::static_string<N> const s1 = "abcd abc ab";
VERIFY(s1.rfind('a') == 9);
VERIFY(s1.rfind('b') == 10);
VERIFY(s1.rfind('c') == 7);
VERIFY(s1.rfind('d') == 3);
VERIFY(s1.rfind('e') == bksge::static_string<N>::npos);
VERIFY(s1.rfind('b', 10) == 10);
VERIFY(s1.rfind('b', 9) == 6);
VERIFY(s1.rfind('b', 5) == 1);
VERIFY(s1.rfind('b', 0) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool RFindStringViewTest()
{
bksge::static_string<N> const s1 = "abcd abc ab";
VERIFY(s1.rfind(bksge::string_view{"a"}) == 9);
VERIFY(s1.rfind(bksge::string_view{"ab"}) == 9);
VERIFY(s1.rfind(bksge::string_view{"abc"}) == 5);
VERIFY(s1.rfind(bksge::string_view{"abcd"}) == 0);
VERIFY(s1.rfind(bksge::string_view{"abcde"}) == bksge::static_string<N>::npos);
VERIFY(s1.rfind(bksge::string_view{"a"}, 10) == 9);
VERIFY(s1.rfind(bksge::string_view{"ab"}, 10) == 9);
VERIFY(s1.rfind(bksge::string_view{"abc"}, 10) == 5);
VERIFY(s1.rfind(bksge::string_view{"abcd"}, 10) == 0);
VERIFY(s1.rfind(bksge::string_view{"abcde"}, 10) == bksge::static_string<N>::npos);
VERIFY(s1.rfind(bksge::string_view{"a"}, 8) == 5);
VERIFY(s1.rfind(bksge::string_view{"ab"}, 8) == 5);
VERIFY(s1.rfind(bksge::string_view{"abc"}, 8) == 5);
VERIFY(s1.rfind(bksge::string_view{"abcd"}, 8) == 0);
VERIFY(s1.rfind(bksge::string_view{"abcde"}, 8) == bksge::static_string<N>::npos);
return true;
}
GTEST_TEST(StaticStringTest, RFindTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((RFindStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((RFindStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((RFindStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((RFindStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((RFindStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((RFindStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(RFindStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstOfStringTest()
{
bksge::static_string<N1> const s1 = "abcde abcde";
VERIFY(s1.find_first_of(bksge::static_string<N2>{"a"}) == 0);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"b"}) == 1);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"c"}) == 2);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"d"}) == 3);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"e"}) == 4);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyz"}) == bksge::static_string<N1>::npos);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyze"}) == 4);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzed"}) == 3);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzedc"}) == 2);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzedcb"}) == 1);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzedcba"}) == 0);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyz"}, 2) == bksge::static_string<N1>::npos);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyze"}, 2) == 4);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzed"}, 2) == 3);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzedc"}, 2) == 2);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzedcb"}, 2) == 2);
VERIFY(s1.find_first_of(bksge::static_string<N2>{"xyzedcba"}, 2) == 2);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstOfCharPtrTest()
{
bksge::static_string<N> const s1 = "abcde abcde";
VERIFY(s1.find_first_of("a") == 0);
VERIFY(s1.find_first_of("b") == 1);
VERIFY(s1.find_first_of("c") == 2);
VERIFY(s1.find_first_of("d") == 3);
VERIFY(s1.find_first_of("e") == 4);
VERIFY(s1.find_first_of("xyz") == bksge::static_string<N>::npos);
VERIFY(s1.find_first_of("xyze") == 4);
VERIFY(s1.find_first_of("xyzed") == 3);
VERIFY(s1.find_first_of("xyzedc") == 2);
VERIFY(s1.find_first_of("xyzedcb") == 1);
VERIFY(s1.find_first_of("xyzedcba") == 0);
VERIFY(s1.find_first_of("xyz", 2) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_of("xyze", 2) == 4);
VERIFY(s1.find_first_of("xyzed", 2) == 3);
VERIFY(s1.find_first_of("xyzedc", 2) == 2);
VERIFY(s1.find_first_of("xyzedcb", 2) == 2);
VERIFY(s1.find_first_of("xyzedcba", 2) == 2);
VERIFY(s1.find_first_of("xedcba", 1, 1) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_of("xedcba", 1, 2) == 4);
VERIFY(s1.find_first_of("xedcba", 1, 3) == 3);
VERIFY(s1.find_first_of("xedcba", 1, 4) == 2);
VERIFY(s1.find_first_of("xedcba", 1, 5) == 1);
VERIFY(s1.find_first_of("xedcba", 1, 6) == 1);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstOfCharTest()
{
bksge::static_string<N> const s1 = "ab abc abcd";
VERIFY(s1.find_first_of('a') == 0);
VERIFY(s1.find_first_of('b') == 1);
VERIFY(s1.find_first_of('c') == 5);
VERIFY(s1.find_first_of('d') == 10);
VERIFY(s1.find_first_of('e') == bksge::static_string<N>::npos);
VERIFY(s1.find_first_of('a', 1) == 3);
VERIFY(s1.find_first_of('a', 4) == 7);
VERIFY(s1.find_first_of('a', 8) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstOfStringViewTest()
{
bksge::static_string<N> const s1 = "abcde abcde";
VERIFY(s1.find_first_of(bksge::string_view{"a"}) == 0);
VERIFY(s1.find_first_of(bksge::string_view{"b"}) == 1);
VERIFY(s1.find_first_of(bksge::string_view{"c"}) == 2);
VERIFY(s1.find_first_of(bksge::string_view{"d"}) == 3);
VERIFY(s1.find_first_of(bksge::string_view{"e"}) == 4);
VERIFY(s1.find_first_of(bksge::string_view{"xyz"}) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_of(bksge::string_view{"xyze"}) == 4);
VERIFY(s1.find_first_of(bksge::string_view{"xyzed"}) == 3);
VERIFY(s1.find_first_of(bksge::string_view{"xyzedc"}) == 2);
VERIFY(s1.find_first_of(bksge::string_view{"xyzedcb"}) == 1);
VERIFY(s1.find_first_of(bksge::string_view{"xyzedcba"}) == 0);
VERIFY(s1.find_first_of(bksge::string_view{"xyz"}, 2) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_of(bksge::string_view{"xyze"}, 2) == 4);
VERIFY(s1.find_first_of(bksge::string_view{"xyzed"}, 2) == 3);
VERIFY(s1.find_first_of(bksge::string_view{"xyzedc"}, 2) == 2);
VERIFY(s1.find_first_of(bksge::string_view{"xyzedcb"}, 2) == 2);
VERIFY(s1.find_first_of(bksge::string_view{"xyzedcba"}, 2) == 2);
return true;
}
GTEST_TEST(StaticStringTest, FindFirstOfTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstOfStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstOfStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstOfStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstOfStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstOfStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstOfStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstOfStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool FindLastOfStringTest()
{
bksge::static_string<N1> const s1 = "abcde abcde";
VERIFY(s1.find_last_of(bksge::static_string<N2>{"a"}) == 6);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"b"}) == 7);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"c"}) == 8);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"d"}) == 9);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"e"}) == 10);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyz"}) == bksge::static_string<N1>::npos);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyze"}) == 10);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzed"}) == 10);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzedc"}) == 10);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzedcb"}) == 10);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzedcba"}) == 10);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyz"}, 8) == bksge::static_string<N1>::npos);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyze"}, 8) == 4);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzed"}, 8) == 4);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzedc"}, 8) == 8);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzedcb"}, 8) == 8);
VERIFY(s1.find_last_of(bksge::static_string<N2>{"xyzedcba"}, 8) == 8);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindLastOfCharPtrTest()
{
bksge::static_string<N> const s1 = "abcde abcde";
VERIFY(s1.find_last_of("a") == 6);
VERIFY(s1.find_last_of("b") == 7);
VERIFY(s1.find_last_of("c") == 8);
VERIFY(s1.find_last_of("d") == 9);
VERIFY(s1.find_last_of("e") == 10);
VERIFY(s1.find_last_of("xyz") == bksge::static_string<N>::npos);
VERIFY(s1.find_last_of("xyze") == 10);
VERIFY(s1.find_last_of("xyzed") == 10);
VERIFY(s1.find_last_of("xyzedc") == 10);
VERIFY(s1.find_last_of("xyzedcb") == 10);
VERIFY(s1.find_last_of("xyzedcba") == 10);
VERIFY(s1.find_last_of("xyz", 8) == bksge::static_string<N>::npos);
VERIFY(s1.find_last_of("xyze", 8) == 4);
VERIFY(s1.find_last_of("xyzed", 8) == 4);
VERIFY(s1.find_last_of("xyzedc", 8) == 8);
VERIFY(s1.find_last_of("xyzedcb", 8) == 8);
VERIFY(s1.find_last_of("xyzedcba", 8) == 8);
VERIFY(s1.find_last_of("Xabcde", 8, 1) == bksge::static_string<N>::npos);
VERIFY(s1.find_last_of("Xabcde", 8, 2) == 6);
VERIFY(s1.find_last_of("Xabcde", 8, 3) == 7);
VERIFY(s1.find_last_of("Xabcde", 8, 4) == 8);
VERIFY(s1.find_last_of("Xabcde", 8, 5) == 8);
VERIFY(s1.find_last_of("Xabcde", 8, 6) == 8);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindLastOfCharTest()
{
bksge::static_string<N> const s1 = "ab abc abcd";
VERIFY(s1.find_last_of('a') == 7);
VERIFY(s1.find_last_of('b') == 8);
VERIFY(s1.find_last_of('c') == 9);
VERIFY(s1.find_last_of('d') == 10);
VERIFY(s1.find_last_of('e') == bksge::static_string<N>::npos);
VERIFY(s1.find_last_of('b', 8) == 8);
VERIFY(s1.find_last_of('b', 7) == 4);
VERIFY(s1.find_last_of('b', 4) == 4);
VERIFY(s1.find_last_of('b', 3) == 1);
VERIFY(s1.find_last_of('b', 1) == 1);
VERIFY(s1.find_last_of('b', 0) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindLastOfStringViewTest()
{
bksge::static_string<N> const s1 = "abcde abcde";
VERIFY(s1.find_last_of(bksge::string_view{"a"}) == 6);
VERIFY(s1.find_last_of(bksge::string_view{"b"}) == 7);
VERIFY(s1.find_last_of(bksge::string_view{"c"}) == 8);
VERIFY(s1.find_last_of(bksge::string_view{"d"}) == 9);
VERIFY(s1.find_last_of(bksge::string_view{"e"}) == 10);
VERIFY(s1.find_last_of(bksge::string_view{"xyz"}) == bksge::static_string<N>::npos);
VERIFY(s1.find_last_of(bksge::string_view{"xyze"}) == 10);
VERIFY(s1.find_last_of(bksge::string_view{"xyzed"}) == 10);
VERIFY(s1.find_last_of(bksge::string_view{"xyzedc"}) == 10);
VERIFY(s1.find_last_of(bksge::string_view{"xyzedcb"}) == 10);
VERIFY(s1.find_last_of(bksge::string_view{"xyzedcba"}) == 10);
VERIFY(s1.find_last_of(bksge::string_view{"xyz"}, 8) == bksge::static_string<N>::npos);
VERIFY(s1.find_last_of(bksge::string_view{"xyze"}, 8) == 4);
VERIFY(s1.find_last_of(bksge::string_view{"xyzed"}, 8) == 4);
VERIFY(s1.find_last_of(bksge::string_view{"xyzedc"}, 8) == 8);
VERIFY(s1.find_last_of(bksge::string_view{"xyzedcb"}, 8) == 8);
VERIFY(s1.find_last_of(bksge::string_view{"xyzedcba"}, 8) == 8);
return true;
}
GTEST_TEST(StaticStringTest, FindLastOfTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastOfStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastOfStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastOfStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastOfStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastOfStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastOfStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastOfStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstNotOfStringTest()
{
bksge::static_string<N1> const s1 = "abcde";
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"a"}) == 1);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"b"}) == 0);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"c"}) == 0);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"d"}) == 0);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"e"}) == 0);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"ba"}) == 2);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"cba"}) == 3);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"dcba"}) == 4);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"edcba"}) == bksge::static_string<N1>::npos);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"xyzedcba"}) == bksge::static_string<N1>::npos);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"de"}, 1) == 1);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"de"}, 2) == 2);
VERIFY(s1.find_first_not_of(bksge::static_string<N2>{"de"}, 3) == bksge::static_string<N1>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstNotOfCharPtrTest()
{
bksge::static_string<N> const s1 = "abcde";
VERIFY(s1.find_first_not_of("a") == 1);
VERIFY(s1.find_first_not_of("b") == 0);
VERIFY(s1.find_first_not_of("c") == 0);
VERIFY(s1.find_first_not_of("d") == 0);
VERIFY(s1.find_first_not_of("e") == 0);
VERIFY(s1.find_first_not_of("ba") == 2);
VERIFY(s1.find_first_not_of("cba") == 3);
VERIFY(s1.find_first_not_of("dcba") == 4);
VERIFY(s1.find_first_not_of("edcba") == bksge::static_string<N>::npos);
VERIFY(s1.find_first_not_of("xyzedcba") == bksge::static_string<N>::npos);
VERIFY(s1.find_first_not_of("de", 1) == 1);
VERIFY(s1.find_first_not_of("de", 2) == 2);
VERIFY(s1.find_first_not_of("de", 3) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_not_of("abcde", 1, 1) == 1);
VERIFY(s1.find_first_not_of("abcde", 1, 2) == 2);
VERIFY(s1.find_first_not_of("abcde", 1, 3) == 3);
VERIFY(s1.find_first_not_of("abcde", 1, 4) == 4);
VERIFY(s1.find_first_not_of("abcde", 1, 5) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstNotOfCharTest()
{
bksge::static_string<N> const s1 = "aaaabbbccd";
VERIFY(s1.find_first_not_of('a') == 4);
VERIFY(s1.find_first_not_of('b') == 0);
VERIFY(s1.find_first_not_of('c') == 0);
VERIFY(s1.find_first_not_of('d') == 0);
VERIFY(s1.find_first_not_of('e') == 0);
VERIFY(s1.find_first_not_of('b', 4) == 7);
VERIFY(s1.find_first_not_of('b', 8) == 8);
VERIFY(s1.find_first_not_of('b', 9) == 9);
VERIFY(s1.find_first_not_of('b', 10) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_not_of('d', 4) == 4);
VERIFY(s1.find_first_not_of('d', 8) == 8);
VERIFY(s1.find_first_not_of('d', 9) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_not_of('d', 10) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindFirstNotOfStringViewTest()
{
bksge::static_string<N> const s1 = "abcde";
VERIFY(s1.find_first_not_of(bksge::string_view{"a"}) == 1);
VERIFY(s1.find_first_not_of(bksge::string_view{"b"}) == 0);
VERIFY(s1.find_first_not_of(bksge::string_view{"c"}) == 0);
VERIFY(s1.find_first_not_of(bksge::string_view{"d"}) == 0);
VERIFY(s1.find_first_not_of(bksge::string_view{"e"}) == 0);
VERIFY(s1.find_first_not_of(bksge::string_view{"ba"}) == 2);
VERIFY(s1.find_first_not_of(bksge::string_view{"cba"}) == 3);
VERIFY(s1.find_first_not_of(bksge::string_view{"dcba"}) == 4);
VERIFY(s1.find_first_not_of(bksge::string_view{"edcba"}) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_not_of(bksge::string_view{"xyzedcba"}) == bksge::static_string<N>::npos);
VERIFY(s1.find_first_not_of(bksge::string_view{"de"}, 1) == 1);
VERIFY(s1.find_first_not_of(bksge::string_view{"de"}, 2) == 2);
VERIFY(s1.find_first_not_of(bksge::string_view{"de"}, 3) == bksge::static_string<N>::npos);
return true;
}
GTEST_TEST(StaticStringTest, FindFirstNotOfTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstNotOfStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstNotOfStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstNotOfStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstNotOfStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstNotOfStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindFirstNotOfStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindFirstNotOfStringViewTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool FindLastNotOfStringTest()
{
bksge::static_string<N1> const s1 = "ddddcccbba";
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"a"}) == 8);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"b"}) == 9);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"c"}) == 9);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"d"}) == 9);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"e"}) == 9);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"ab"}) == 6);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"abc"}) == 3);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"abcd"}) == bksge::static_string<N1>::npos);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"abcde"}) == bksge::static_string<N1>::npos);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"cd"}, 8) == 8);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"cd"}, 7) == 7);
VERIFY(s1.find_last_not_of(bksge::static_string<N2>{"cd"}, 6) == bksge::static_string<N1>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindLastNotOfCharPtrTest()
{
bksge::static_string<N> const s1 = "ddddcccbba";
VERIFY(s1.find_last_not_of("a") == 8);
VERIFY(s1.find_last_not_of("b") == 9);
VERIFY(s1.find_last_not_of("c") == 9);
VERIFY(s1.find_last_not_of("d") == 9);
VERIFY(s1.find_last_not_of("e") == 9);
VERIFY(s1.find_last_not_of("ab") == 6);
VERIFY(s1.find_last_not_of("abc") == 3);
VERIFY(s1.find_last_not_of("abcd") == bksge::static_string<N>::npos);
VERIFY(s1.find_last_not_of("abcde") == bksge::static_string<N>::npos);
VERIFY(s1.find_last_not_of("cd", 8) == 8);
VERIFY(s1.find_last_not_of("cd", 7) == 7);
VERIFY(s1.find_last_not_of("cd", 6) == bksge::static_string<N>::npos);
VERIFY(s1.find_last_not_of("abcde", 8, 1) == 8);
VERIFY(s1.find_last_not_of("abcde", 8, 2) == 6);
VERIFY(s1.find_last_not_of("abcde", 8, 3) == 3);
VERIFY(s1.find_last_not_of("abcde", 8, 4) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindLastNotOfCharTest()
{
bksge::static_string<N> const s1 = "ddddcccbba";
VERIFY(s1.find_last_not_of('a') == 8);
VERIFY(s1.find_last_not_of('b') == 9);
VERIFY(s1.find_last_not_of('c') == 9);
VERIFY(s1.find_last_not_of('d') == 9);
VERIFY(s1.find_last_not_of('e') == 9);
VERIFY(s1.find_last_not_of('d', 5) == 5);
VERIFY(s1.find_last_not_of('d', 4) == 4);
VERIFY(s1.find_last_not_of('d', 3) == bksge::static_string<N>::npos);
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool FindLastNotOfStringViewTest()
{
bksge::static_string<N> const s1 = "ddddcccbba";
VERIFY(s1.find_last_not_of(bksge::string_view{"a"}) == 8);
VERIFY(s1.find_last_not_of(bksge::string_view{"b"}) == 9);
VERIFY(s1.find_last_not_of(bksge::string_view{"c"}) == 9);
VERIFY(s1.find_last_not_of(bksge::string_view{"d"}) == 9);
VERIFY(s1.find_last_not_of(bksge::string_view{"e"}) == 9);
VERIFY(s1.find_last_not_of(bksge::string_view{"ab"}) == 6);
VERIFY(s1.find_last_not_of(bksge::string_view{"abc"}) == 3);
VERIFY(s1.find_last_not_of(bksge::string_view{"abcd"}) == bksge::static_string<N>::npos);
VERIFY(s1.find_last_not_of(bksge::string_view{"abcde"}) == bksge::static_string<N>::npos);
VERIFY(s1.find_last_not_of(bksge::string_view{"cd"}, 8) == 8);
VERIFY(s1.find_last_not_of(bksge::string_view{"cd"}, 7) == 7);
VERIFY(s1.find_last_not_of(bksge::string_view{"cd"}, 6) == bksge::static_string<N>::npos);
return true;
}
GTEST_TEST(StaticStringTest, FindLastNotOfTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastNotOfStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastNotOfStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastNotOfStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastNotOfStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastNotOfStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((FindLastNotOfStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfStringViewTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfStringViewTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(FindLastNotOfStringViewTest<100>());
}
#if !defined(BKSGE_GCC)
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool SubstrTest()
{
bksge::static_string<N> const s1 = "abcde";
auto s2 = s1.substr();
auto s3 = s1.substr(1);
auto s4 = s1.substr(2);
auto s5 = s1.substr(1, 1);
auto s6 = s1.substr(1, 2);
auto s7 = s1.substr(1, 3);
auto s8 = s1.substr(2, 1);
auto s9 = s1.substr(2, 2);
auto s10 = s1.substr(2, 3);
auto s11 = s1.substr(2, 4);
VERIFY(s2 == "abcde");
VERIFY(s3 == "bcde");
VERIFY(s4 == "cde");
VERIFY(s5 == "b");
VERIFY(s6 == "bc");
VERIFY(s7 == "bcd");
VERIFY(s8 == "c");
VERIFY(s9 == "cd");
VERIFY(s10 == "cde");
VERIFY(s11 == "cde");
return true;
}
GTEST_TEST(StaticStringTest, SubstrTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(SubstrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(SubstrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(SubstrTest<100>());
}
#endif
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool StartsWithTest()
{
bksge::static_string<N> const s = "abcde";
VERIFY(s.starts_with(bksge::string_view{"abcde"}) == true);
VERIFY(s.starts_with(bksge::string_view{"abc"}) == true);
VERIFY(s.starts_with(bksge::string_view{"a"}) == true);
VERIFY(s.starts_with(bksge::string_view{"abcdef"}) == false);
VERIFY(s.starts_with(bksge::string_view{"abd"}) == false);
VERIFY(s.starts_with(bksge::string_view{"bc"}) == false);
VERIFY(s.starts_with('a') == true);
VERIFY(s.starts_with('b') == false);
VERIFY(s.starts_with('e') == false);
VERIFY(s.starts_with("abcde") == true);
VERIFY(s.starts_with("abc") == true);
VERIFY(s.starts_with("a") == true);
VERIFY(s.starts_with("abcdef") == false);
VERIFY(s.starts_with("abd") == false);
VERIFY(s.starts_with("bc") == false);
return true;
}
GTEST_TEST(StaticStringTest, StartsWithTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(StartsWithTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(StartsWithTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(StartsWithTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool EndsWithTest()
{
bksge::static_string<N> const s = "abcde";
VERIFY(s.ends_with(bksge::string_view{"abcde"}) == true);
VERIFY(s.ends_with(bksge::string_view{"cde"}) == true);
VERIFY(s.ends_with(bksge::string_view{"e"}) == true);
VERIFY(s.ends_with(bksge::string_view{"abcdef"}) == false);
VERIFY(s.ends_with(bksge::string_view{"dde"}) == false);
VERIFY(s.ends_with(bksge::string_view{"cdf"}) == false);
VERIFY(s.ends_with(bksge::string_view{"cd"}) == false);
VERIFY(s.ends_with('e') == true);
VERIFY(s.ends_with('d') == false);
VERIFY(s.ends_with('a') == false);
VERIFY(s.ends_with("abcde") == true);
VERIFY(s.ends_with("cde") == true);
VERIFY(s.ends_with("e") == true);
VERIFY(s.ends_with("abcdef") == false);
VERIFY(s.ends_with("dde") == false);
VERIFY(s.ends_with("cdf") == false);
VERIFY(s.ends_with("cd") == false);
return true;
}
GTEST_TEST(StaticStringTest, EndsWithTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EndsWithTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EndsWithTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(EndsWithTest<100>());
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool DataTest()
{
{
bksge::static_string<N> const s = "abc";
auto p = s.data();
VERIFY(p[0] == 'a');
VERIFY(p[1] == 'b');
VERIFY(p[2] == 'c');
VERIFY(c_str_test(s, "abc"));
}
{
bksge::static_string<N> s = "abc";
auto p = s.data();
VERIFY(p[0] == 'a');
VERIFY(p[1] == 'b');
VERIFY(p[2] == 'c');
p[1] = 'X';
VERIFY(c_str_test(s, "aXc"));
}
return true;
}
GTEST_TEST(StaticStringTest, DataTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(DataTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(DataTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(DataTest<100>());
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool SwapTest()
{
{
bksge::static_string<N1> s1 = "abc";
bksge::static_string<N2> s2 = "12345";
s1.swap(s2);
VERIFY(c_str_test(s1, "12345"));
VERIFY(c_str_test(s2, "abc"));
}
{
bksge::static_string<N1> s1 = "abcdefg";
bksge::static_string<N2> s2 = "123";
bksge::ranges::swap(s1, s2);
VERIFY(c_str_test(s1, "123"));
VERIFY(c_str_test(s2, "abcdefg"));
}
return true;
}
GTEST_TEST(StaticStringTest, SwapTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((SwapTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((SwapTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((SwapTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((SwapTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((SwapTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((SwapTest<100, 100>()));
}
template <std::size_t N1, std::size_t N2>
inline BKSGE_CXX14_CONSTEXPR bool AddStringStringTest()
{
{
bksge::static_string<N1> const s1 = "abc";
bksge::static_string<N2> const s2 = "12345";
auto s3 = s1 + s2;
VERIFY(c_str_test(s3, "abc12345"));
}
{
bksge::static_string<N1> const s1 = "abc";
bksge::static_string<N2> const s2 = "123";
auto s3 = "xxx" + s1 + 'y' + s2 + 'z' + "AA";
VERIFY(c_str_test(s3, "xxxabcy123zAA"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AddStringCharPtrTest()
{
{
bksge::static_string<N> const s1 = "abc";
auto s2 = s1 + "defg";
VERIFY(c_str_test(s2, "abcdefg"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AddStringCharTest()
{
{
bksge::static_string<N> const s1 = "abc";
auto s2 = s1 + '1';
VERIFY(c_str_test(s2, "abc1"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AddCharPtrStringTest()
{
{
bksge::static_string<N> const s1 = "abc";
auto s2 = "defg" + s1;
VERIFY(c_str_test(s2, "defgabc"));
}
return true;
}
template <std::size_t N>
inline BKSGE_CXX14_CONSTEXPR bool AddCharStringTest()
{
{
bksge::static_string<N> const s1 = "abc";
auto s2 = '1' + s1;
VERIFY(c_str_test(s2, "1abc"));
}
return true;
}
GTEST_TEST(StaticStringTest, AddTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AddStringStringTest<16, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AddStringStringTest<16, 24>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AddStringStringTest<32, 16>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AddStringStringTest<32, 32>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AddStringStringTest<100, 50>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE((AddStringStringTest<100, 100>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddStringCharPtrTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddStringCharPtrTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddStringCharPtrTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddStringCharTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddStringCharTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddStringCharTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddCharPtrStringTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddCharPtrStringTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddCharPtrStringTest<100>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddCharStringTest<16>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddCharStringTest<32>());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(AddCharStringTest<100>());
}
GTEST_TEST(StaticStringTest, InputStreamTest)
{
{
std::stringstream ss("abc");
bksge::static_string<16> s;
ss >> s;
EXPECT_TRUE(s == "abc");
}
{
std::stringstream ss("Hello World");
bksge::static_string<32> s;
ss >> s;
EXPECT_TRUE(s == "Hello");
ss >> s;
EXPECT_TRUE(s == "World");
}
}
GTEST_TEST(StaticStringTest, OutputStreamTest)
{
{
bksge::static_string<16> const s = "abc";
std::stringstream ss;
ss << s;
EXPECT_TRUE(ss.str() == "abc");
}
{
bksge::static_string<32> const s = "Hello World";
std::stringstream ss;
ss << s;
EXPECT_TRUE(ss.str() == "Hello World");
}
}
#undef VERIFY
} // namespace bksge_static_string_test
|
/* -------------------------------------------------------------------------
*
* nodeBitmapHeapscan.cpp
* Routines to support bitmapped scans of relations
*
* NOTE: it is critical that this plan type only be used with MVCC-compliant
* snapshots (ie, regular snapshots, not SnapshotNow or one of the other
* special snapshots). The reason is that since index and heap scans are
* decoupled, there can be no assurance that the index tuple prompting a
* visit to a particular heap TID still exists when the visit is made.
* Therefore the tuple might not exist anymore either (which is OK because
* heap_fetch will cope) --- but worse, the tuple slot could have been
* re-used for a newer tuple. With an MVCC snapshot the newer tuple is
* certain to fail the time qual and so it will not be mistakenly returned.
* With SnapshotNow we might return a tuple that doesn't meet the required
* index qual conditions.
*
*
* Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd.
* Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/gausskernel/runtime/executor/nodeBitmapHeapscan.cpp
*
* -------------------------------------------------------------------------
*
* INTERFACE ROUTINES
* ExecBitmapHeapScan scans a relation using bitmap info
* ExecBitmapHeapNext workhorse for above
* ExecInitBitmapHeapScan creates and initializes state info.
* ExecReScanBitmapHeapScan prepares to rescan the plan.
* ExecEndBitmapHeapScan releases all storage.
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include "access/relscan.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "executor/execdebug.h"
#include "executor/nodeBitmapHeapscan.h"
#include "pgstat.h"
#include "storage/bufmgr.h"
#include "storage/predicate.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/rel_gs.h"
#include "utils/snapmgr.h"
#include "utils/tqual.h"
#include "gstrace/gstrace_infra.h"
#include "gstrace/access_gstrace.h"
static TupleTableSlot* BitmapHbucketTblNext(BitmapHeapScanState* node);
static TupleTableSlot* BitmapHeapTblNext(BitmapHeapScanState* node);
static void bitgetpage(HeapScanDesc scan, TBMIterateResult* tbmres);
static void ExecInitPartitionForBitmapHeapScan(BitmapHeapScanState* scanstate, EState* estate);
static void ExecInitNextPartitionForBitmapHeapScan(BitmapHeapScanState* node);
void BitmapHeapFree(BitmapHeapScanState* node)
{
if (node->tbmiterator != NULL) {
tbm_end_iterate(node->tbmiterator);
node->tbmiterator = NULL;
}
if (node->prefetch_iterator != NULL) {
tbm_end_iterate(node->prefetch_iterator);
node->prefetch_iterator = NULL;
}
if (node->tbm != NULL) {
tbm_free(node->tbm);
node->tbm = NULL;
}
node->tbmres = NULL;
}
static TupleTableSlot* BitmapHbucketTblNext(BitmapHeapScanState* node)
{
Assert(node->ss.ss_currentScanDesc != NULL);
Assert(node->ss.ss_currentScanDesc->type == T_ScanDesc_HBucket);
HBktTblScanDesc hpScan = (HBktTblScanDesc)node->ss.ss_currentScanDesc;
TupleTableSlot* slot = NULL;
while (true) {
node->ss.ps.hbktScanSlot.currSlot = hpScan->curr_slot;
node->ss.ps.lefttree->hbktScanSlot.currSlot = hpScan->curr_slot;
slot = BitmapHeapTblNext(node);
if (!TupIsNull(slot)) {
return slot;
}
if (!hbkt_bitmapheap_scan_nextbucket(hpScan)) {
return NULL;
}
BitmapHeapFree(node);
}
}
/* ----------------------------------------------------------------
* BitmapHeapNext
*
* Retrieve next tuple from the BitmapHeapScan node's currentRelation
* ----------------------------------------------------------------
*/
static TupleTableSlot* BitmapHeapTblNext(BitmapHeapScanState* node)
{
ExprContext* econtext = NULL;
HeapScanDesc scan = NULL;
TIDBitmap* tbm = NULL;
TBMIterator* tbmiterator = NULL;
TBMIterateResult* tbmres = NULL;
#ifdef USE_PREFETCH
TBMIterator* prefetch_iterator = NULL;
#endif
OffsetNumber targoffset;
TupleTableSlot* slot = NULL;
/*
* extract necessary information from index scan node
*/
econtext = node->ss.ps.ps_ExprContext;
slot = node->ss.ss_ScanTupleSlot;
scan = GetHeapScanDesc(node->ss.ss_currentScanDesc);
tbm = node->tbm;
tbmiterator = node->tbmiterator;
tbmres = node->tbmres;
#ifdef USE_PREFETCH
prefetch_iterator = node->prefetch_iterator;
#endif
/*
* If we haven't yet performed the underlying index scan, do it, and begin
* the iteration over the bitmap.
*
* For prefetching, we use *two* iterators, one for the pages we are
* actually scanning and another that runs ahead of the first for
* prefetching. node->prefetch_pages tracks exactly how many pages ahead
* the prefetch iterator is. Also, node->prefetch_target tracks the
* desired prefetch distance, which starts small and increases up to the
* GUC-controlled maximum, target_prefetch_pages. This is to avoid doing
* a lot of prefetching in a scan that stops after a few tuples because of
* a LIMIT.
*/
if (tbm == NULL) {
tbm = (TIDBitmap*)MultiExecProcNode(outerPlanState(node));
if (tbm == NULL || !IsA(tbm, TIDBitmap)) {
ereport(ERROR,
(errcode(ERRCODE_UNRECOGNIZED_NODE_TYPE),
errmodule(MOD_EXECUTOR),
errmsg("unrecognized result from subplan for BitmapHeapScan.")));
}
node->tbm = tbm;
node->tbmiterator = tbmiterator = tbm_begin_iterate(tbm);
node->tbmres = tbmres = NULL;
#ifdef USE_PREFETCH
if (u_sess->storage_cxt.target_prefetch_pages > 0) {
node->prefetch_iterator = prefetch_iterator = tbm_begin_iterate(tbm);
node->prefetch_pages = 0;
node->prefetch_target = -1;
}
#endif
}
for (;;) {
Page dp;
ItemId lp;
/*
* Get next page of results if needed
*/
if (tbmres == NULL) {
node->tbmres = tbmres = tbm_iterate(tbmiterator);
if (tbmres == NULL) {
/* no more entries in the bitmap */
break;
}
#ifdef USE_PREFETCH
if (node->prefetch_pages > 0) {
/* The main iterator has closed the distance by one page */
node->prefetch_pages--;
} else if (prefetch_iterator != NULL) {
/* Do not let the prefetch iterator get behind the main one */
TBMIterateResult* tbmpre = tbm_iterate(prefetch_iterator);
if (tbmpre == NULL || tbmpre->blockno != tbmres->blockno) {
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmodule(MOD_EXECUTOR),
errmsg("prefetch and main iterators are out of sync for BitmapHeapScan.")));
}
}
#endif /* USE_PREFETCH */
/*
* Ignore any claimed entries past what we think is the end of the
* relation. (This is probably not necessary given that we got at
* least AccessShareLock on the table before performing any of the
* indexscans, but let's be safe.)
*/
if (tbmres->blockno >= scan->rs_nblocks) {
node->tbmres = tbmres = NULL;
continue;
}
/*
* Fetch the current heap page and identify candidate tuples.
*/
bitgetpage(scan, tbmres);
/* In single mode and hot standby, we may get a null buffer if index
* replayed before the tid replayed. This is acceptable, so we skip
* directly without reporting error.
*/
#ifndef ENABLE_MULTIPLE_NODES
if(!BufferIsValid(scan->rs_cbuf)) {
node->tbmres = tbmres = NULL;
continue;
}
#endif
/*
* Set rs_cindex to first slot to examine
*/
scan->rs_cindex = 0;
#ifdef USE_PREFETCH
/*
* Increase prefetch target if it's not yet at the max. Note that
* we will increase it to zero after fetching the very first
* page/tuple, then to one after the second tuple is fetched, then
* it doubles as later pages are fetched.
*/
if (node->prefetch_target >= u_sess->storage_cxt.target_prefetch_pages)
/* don't increase any further */;
else if (node->prefetch_target >= u_sess->storage_cxt.target_prefetch_pages / 2)
node->prefetch_target = u_sess->storage_cxt.target_prefetch_pages;
else if (node->prefetch_target > 0)
node->prefetch_target *= 2;
else
node->prefetch_target++;
#endif /* USE_PREFETCH */
} else {
/*
* Continuing in previously obtained page; advance rs_cindex
*/
scan->rs_cindex++;
#ifdef USE_PREFETCH
/*
* Try to prefetch at least a few pages even before we get to the
* second page if we don't stop reading after the first tuple.
*/
if (node->prefetch_target < u_sess->storage_cxt.target_prefetch_pages)
node->prefetch_target++;
#endif /* USE_PREFETCH */
}
/*
* Out of range? If so, nothing more to look at on this page
*/
if (scan->rs_cindex < 0 || scan->rs_cindex >= scan->rs_ntuples) {
node->tbmres = tbmres = NULL;
continue;
}
#ifdef USE_PREFETCH
/*
* We issue prefetch requests *after* fetching the current page to try
* to avoid having prefetching interfere with the main I/O. Also, this
* should happen only when we have determined there is still something
* to do on the current page, else we may uselessly prefetch the same
* page we are just about to request for real.
*/
if (prefetch_iterator != NULL) {
ADIO_RUN()
{
BlockNumber* blockList = NULL;
BlockNumber* blockListPtr = NULL;
int prefetchNow = 0;
int prefetchWindow = node->prefetch_target - node->prefetch_pages;
/* We expect to prefetch at most prefetchWindow pages */
if (prefetchWindow > 0) {
blockList = (BlockNumber*)palloc(sizeof(BlockNumber) * prefetchWindow);
blockListPtr = blockList;
}
while (node->prefetch_pages < node->prefetch_target) {
TBMIterateResult* tbmpre = tbm_iterate(prefetch_iterator);
if (tbmpre == NULL) {
/* No more pages to prefetch */
tbm_end_iterate(prefetch_iterator);
node->prefetch_iterator = prefetch_iterator = NULL;
break;
}
node->prefetch_pages++;
/* For Async Direct I/O we accumulate a list and send it */
*blockListPtr++ = tbmpre->blockno;
prefetchNow++;
}
/* Send the list we generated and free it */
if (prefetchNow) {
PageListPrefetch(scan->rs_rd, MAIN_FORKNUM, blockList, prefetchNow, 0, 0);
}
if (prefetchWindow > 0) {
pfree_ext(blockList);
}
}
ADIO_ELSE()
{
while (node->prefetch_pages < node->prefetch_target) {
TBMIterateResult* tbmpre = tbm_iterate(prefetch_iterator);
if (tbmpre == NULL) {
/* No more pages to prefetch */
tbm_end_iterate(prefetch_iterator);
node->prefetch_iterator = prefetch_iterator = NULL;
break;
}
node->prefetch_pages++;
/* For posix_fadvise() we just send the one request */
PrefetchBuffer(scan->rs_rd, MAIN_FORKNUM, tbmpre->blockno);
}
}
ADIO_END();
}
#endif /* USE_PREFETCH */
/*
* Okay to fetch the tuple
*/
targoffset = scan->rs_vistuples[scan->rs_cindex];
dp = (Page)BufferGetPage(scan->rs_cbuf);
lp = PageGetItemId(dp, targoffset);
Assert(ItemIdIsNormal(lp));
scan->rs_ctup.t_data = (HeapTupleHeader)PageGetItem((Page)dp, lp);
scan->rs_ctup.t_len = ItemIdGetLength(lp);
scan->rs_ctup.t_tableOid = RelationGetRelid(scan->rs_rd);
scan->rs_ctup.t_bucketId = RelationGetBktid(scan->rs_rd);
HeapTupleCopyBaseFromPage(&scan->rs_ctup, dp);
ItemPointerSet(&scan->rs_ctup.t_self, tbmres->blockno, targoffset);
pgstat_count_heap_fetch(scan->rs_rd);
/*
* Set up the result slot to point to this tuple. Note that the slot
* acquires a pin on the buffer.
*/
(void)ExecStoreTuple(&scan->rs_ctup, slot, scan->rs_cbuf, false);
/*
* If we are using lossy info, we have to recheck the qual conditions
* at every tuple.
*/
if (tbmres->recheck) {
econtext->ecxt_scantuple = slot;
ResetExprContext(econtext);
if (!ExecQual(node->bitmapqualorig, econtext, false)) {
/* Fails recheck, so drop it and loop back for another */
InstrCountFiltered2(node, 1);
(void)ExecClearTuple(slot);
continue;
}
}
/* OK to return this tuple */
return slot;
}
/*
* if we get here it means we are at the end of the scan..
*/
return ExecClearTuple(slot);
}
/*
* bitgetpage - subroutine for BitmapHeapNext()
*
* This routine reads and pins the specified page of the relation, then
* builds an array indicating which tuples on the page are both potentially
* interesting according to the bitmap, and visible according to the snapshot.
*/
static void bitgetpage(HeapScanDesc scan, TBMIterateResult* tbmres)
{
BlockNumber page = tbmres->blockno;
Buffer buffer;
Snapshot snapshot;
int ntup;
/*
* Acquire pin on the target heap page, trading in any pin we held before.
*/
Assert(page < scan->rs_nblocks);
gstrace_entry(GS_TRC_ID_bitgetpage);
scan->rs_cbuf = ReleaseAndReadBuffer(scan->rs_cbuf, scan->rs_rd, page);
/* In single mode and hot standby, we may get a null buffer if index
* replayed before the tid replayed. This is acceptable, so we return
* directly without reporting error.
*/
#ifndef ENABLE_MULTIPLE_NODES
if(!BufferIsValid(scan->rs_cbuf)) {
gstrace_exit(GS_TRC_ID_bitgetpage);
return;
}
#endif
buffer = scan->rs_cbuf;
snapshot = scan->rs_snapshot;
ntup = 0;
/*
* Prune and repair fragmentation for the whole page, if possible.
*/
heap_page_prune_opt(scan->rs_rd, buffer);
/*
* We must hold share lock on the buffer content while examining tuple
* visibility. Afterwards, however, the tuples we have found to be
* visible are guaranteed good as long as we hold the buffer pin.
*/
LockBuffer(buffer, BUFFER_LOCK_SHARE);
/*
* We need two separate strategies for lossy and non-lossy cases.
*/
if (tbmres->ntuples >= 0) {
/*
* Bitmap is non-lossy, so we just look through the offsets listed in
* tbmres; but we have to follow any HOT chain starting at each such
* offset.
*/
int curslot;
for (curslot = 0; curslot < tbmres->ntuples; curslot++) {
OffsetNumber offnum = tbmres->offsets[curslot];
ItemPointerData tid;
HeapTupleData heapTuple;
ItemPointerSet(&tid, page, offnum);
if (heap_hot_search_buffer(&tid, scan->rs_rd, buffer, snapshot, &heapTuple, NULL, NULL, true))
scan->rs_vistuples[ntup++] = ItemPointerGetOffsetNumber(&tid);
}
} else {
/*
* Bitmap is lossy, so we must examine each item pointer on the page.
* But we can ignore HOT chains, since we'll check each tuple anyway.
*/
Page dp = (Page)BufferGetPage(buffer);
OffsetNumber maxoff = PageGetMaxOffsetNumber(dp);
OffsetNumber offnum;
for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) {
ItemId lp;
HeapTupleData loctup;
bool valid = false;
lp = PageGetItemId(dp, offnum);
if (!ItemIdIsNormal(lp))
continue;
loctup.t_data = (HeapTupleHeader)PageGetItem((Page)dp, lp);
loctup.t_len = ItemIdGetLength(lp);
loctup.t_tableOid = RelationGetRelid(scan->rs_rd);
loctup.t_bucketId = RelationGetBktid(scan->rs_rd);
HeapTupleCopyBaseFromPage(&scan->rs_ctup, dp);
HeapTupleCopyBaseFromPage(&loctup, dp);
ItemPointerSet(&loctup.t_self, page, offnum);
valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
if (valid) {
scan->rs_vistuples[ntup++] = offnum;
PredicateLockTuple(scan->rs_rd, &loctup, snapshot);
}
CheckForSerializableConflictOut(valid, scan->rs_rd, &loctup, buffer, snapshot);
}
}
LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
Assert(ntup <= MaxHeapTuplesPerPage);
scan->rs_ntuples = ntup;
gstrace_exit(GS_TRC_ID_bitgetpage);
}
/*
* BitmapHeapRecheck -- access method routine to recheck a tuple in EvalPlanQual
*/
static bool BitmapHeapRecheck(BitmapHeapScanState* node, TupleTableSlot* slot)
{
ExprContext* econtext = NULL;
/*
* extract necessary information from index scan node
*/
econtext = node->ss.ps.ps_ExprContext;
/* Does the tuple meet the original qual conditions? */
econtext->ecxt_scantuple = slot;
ResetExprContext(econtext);
return ExecQual(node->bitmapqualorig, econtext, false);
}
/* ----------------------------------------------------------------
* ExecBitmapHeapScan(node)
* ----------------------------------------------------------------
*/
TupleTableSlot* ExecBitmapHeapScan(BitmapHeapScanState* node)
{
return ExecScan(&node->ss, node->ss.ScanNextMtd, (ExecScanRecheckMtd)BitmapHeapRecheck);
}
/* ----------------------------------------------------------------
* ExecReScanBitmapHeapScan(node)
* ----------------------------------------------------------------
*/
void ExecReScanBitmapHeapScan(BitmapHeapScanState* node)
{
/*
* deal with partitioned table
*/
if (node->ss.isPartTbl) {
if (!PointerIsValid(node->ss.partitions)) {
return;
}
/*
* if there are partitions for scaning, switch to the next partition;
* else return with doing nothing
*/
abs_tbl_endscan(node->ss.ss_currentScanDesc);
/* switch to next partition for scan */
ExecInitNextPartitionForBitmapHeapScan(node);
} else {
/* rescan to release any page pin */
abs_tbl_rescan(node->ss.ss_currentScanDesc, NULL);
}
/* rescan to release any page pin */
BitmapHeapFree(node);
ExecScanReScan(&node->ss);
/*
* if chgParam of subnode is not null or the relation is a partitioned table
* then plan will be re-scanned by first ExecProcNode.
*/
if (node->ss.isPartTbl || !PointerIsValid(node->ss.ps.lefttree->chgParam))
ExecReScan(node->ss.ps.lefttree);
}
/* ----------------------------------------------------------------
* ExecEndBitmapHeapScan
* ----------------------------------------------------------------
*/
void ExecEndBitmapHeapScan(BitmapHeapScanState* node)
{
/*
* extract information from the node
*/
Relation relation = node->ss.ss_currentRelation;
/*
* Free the exprcontext
*/
ExecFreeExprContext(&node->ss.ps);
/*
* clear out tuple table slots
*/
(void)ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
(void)ExecClearTuple(node->ss.ss_ScanTupleSlot);
/*
* close down subplans
*/
ExecEndNode(outerPlanState(node));
/*
* release bitmap if any
*/
BitmapHeapFree(node);
if (node->ss.ss_currentScanDesc != NULL) {
abs_tbl_endscan(node->ss.ss_currentScanDesc);
}
/* close heap scan */
if (node->ss.isPartTbl && PointerIsValid(node->ss.partitions)) {
/* close table partition */
Assert(node->ss.ss_currentPartition);
releaseDummyRelation(&(node->ss.ss_currentPartition));
releasePartitionList(node->ss.ss_currentRelation, &(node->ss.partitions), NoLock);
}
/*
* close the heap relation.
*/
ExecCloseScanRelation(relation);
}
static inline void InitBitmapHeapScanNextMtd(BitmapHeapScanState* bmstate)
{
if (RELATION_OWN_BUCKET(bmstate->ss.ss_currentRelation)) {
bmstate->ss.ScanNextMtd = (ExecScanAccessMtd)BitmapHbucketTblNext;
return;
}
bmstate->ss.ScanNextMtd = (ExecScanAccessMtd)BitmapHeapTblNext;
}
/* ----------------------------------------------------------------
* ExecInitBitmapHeapScan
*
* Initializes the scan's state information.
* ----------------------------------------------------------------
*/
BitmapHeapScanState* ExecInitBitmapHeapScan(BitmapHeapScan* node, EState* estate, int eflags)
{
BitmapHeapScanState* scanstate = NULL;
Relation currentRelation;
/* check for unsupported flags */
Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
/*
* Assert caller didn't ask for an unsafe snapshot --- see comments at
* head of file.
*/
Assert(IsMVCCSnapshot(estate->es_snapshot));
/*
* create state structure
*/
scanstate = makeNode(BitmapHeapScanState);
scanstate->ss.ps.plan = (Plan*)node;
scanstate->ss.ps.state = estate;
scanstate->tbm = NULL;
scanstate->tbmiterator = NULL;
scanstate->tbmres = NULL;
scanstate->prefetch_iterator = NULL;
scanstate->prefetch_pages = 0;
scanstate->prefetch_target = 0;
scanstate->ss.isPartTbl = node->scan.isPartTbl;
scanstate->ss.currentSlot = 0;
scanstate->ss.partScanDirection = node->scan.partScanDirection;
/*
* Miscellaneous initialization
*
* create expression context for node
*/
ExecAssignExprContext(estate, &scanstate->ss.ps);
scanstate->ss.ps.ps_TupFromTlist = false;
/*
* initialize child expressions
*/
scanstate->ss.ps.targetlist = (List*)ExecInitExpr((Expr*)node->scan.plan.targetlist, (PlanState*)scanstate);
scanstate->ss.ps.qual = (List*)ExecInitExpr((Expr*)node->scan.plan.qual, (PlanState*)scanstate);
scanstate->bitmapqualorig = (List*)ExecInitExpr((Expr*)node->bitmapqualorig, (PlanState*)scanstate);
/*
* tuple table initialization
*/
ExecInitResultTupleSlot(estate, &scanstate->ss.ps);
ExecInitScanTupleSlot(estate, &scanstate->ss);
/*
* open the base relation and acquire appropriate lock on it.
*/
currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid);
scanstate->ss.ss_currentRelation = currentRelation;
InitBitmapHeapScanNextMtd(scanstate);
/*
* Even though we aren't going to do a conventional seqscan, it is useful
* to create a HeapScanDesc --- most of the fields in it are usable.
*/
if (scanstate->ss.isPartTbl) {
scanstate->ss.ss_currentScanDesc = NULL;
ExecInitPartitionForBitmapHeapScan(scanstate, estate);
if (node->scan.itrs > 0) {
Partition partition = NULL;
Relation partitiontrel = NULL;
/* construct a dummy table relation with the next table partition for scan */
partition = (Partition)list_nth(scanstate->ss.partitions, 0);
partitiontrel = partitionGetRelation(currentRelation, partition);
scanstate->ss.ss_currentPartition = partitiontrel;
scanstate->ss.ss_currentScanDesc =
abs_tbl_beginscan_bm(partitiontrel, estate->es_snapshot, 0, NULL, &scanstate->ss);
}
} else {
scanstate->ss.ss_currentScanDesc =
abs_tbl_beginscan_bm(currentRelation, estate->es_snapshot, 0, NULL, &scanstate->ss);
}
if (scanstate->ss.ss_currentScanDesc == NULL) {
scanstate->ss.ps.stubType = PST_Scan;
}
/*
* get the scan type from the relation descriptor.
*/
ExecAssignScanType(&scanstate->ss, RelationGetDescr(currentRelation));
/*
* Initialize result tuple type and projection info.
*/
ExecAssignResultTypeFromTL(&scanstate->ss.ps);
ExecAssignScanProjectionInfo(&scanstate->ss);
/*
* initialize child nodes
*
* We do this last because the child nodes will open indexscans on our
* relation's indexes, and we want to be sure we have acquired a lock on
* the relation first.
*/
outerPlanState(scanstate) = ExecInitNode(outerPlan(node), estate, eflags);
/*
* all done.
*/
return scanstate;
}
/*
* @@GaussDB@@
* Target : data partition
* Brief : Initialize the table partition and the index partition for
* : index sacn
* Description :
* Input :
* Output :
* Notes :
*/
static void ExecInitNextPartitionForBitmapHeapScan(BitmapHeapScanState* node)
{
Partition currentpartition = NULL;
Relation currentpartitionrel = NULL;
BitmapHeapScan* plan = NULL;
int paramno = -1;
ParamExecData* param = NULL;
plan = (BitmapHeapScan*)(node->ss.ps.plan);
/* get partition sequnce */
paramno = plan->scan.plan.paramno;
param = &(node->ss.ps.state->es_param_exec_vals[paramno]);
node->ss.currentSlot = (int)param->value;
/* construct a dummy relation with the nextl table partition */
currentpartition = (Partition)list_nth(node->ss.partitions, node->ss.currentSlot);
currentpartitionrel = partitionGetRelation(node->ss.ss_currentRelation, currentpartition);
/* switch the partition that needs to be scanned */
Assert(PointerIsValid(node->ss.ss_currentPartition));
releaseDummyRelation(&(node->ss.ss_currentPartition));
node->ss.ss_currentPartition = currentpartitionrel;
/* Initialize scan descriptor. */
node->ss.ss_currentScanDesc =
abs_tbl_beginscan_bm(currentpartitionrel, node->ss.ps.state->es_snapshot, 0, NULL, &node->ss);
}
/*
* @@GaussDB@@
* Target : data partition
* Brief : get the table partition that need to be scanned, and add it
* : the list for the following scanning
* Description :
* Input :
* Output :
* Notes :
*/
static void ExecInitPartitionForBitmapHeapScan(BitmapHeapScanState* scanstate, EState* estate)
{
BitmapHeapScan* plan = NULL;
Relation currentRelation = NULL;
plan = (BitmapHeapScan*)scanstate->ss.ps.plan;
currentRelation = scanstate->ss.ss_currentRelation;
scanstate->ss.partitions = NIL;
scanstate->ss.ss_currentPartition = NULL;
if (plan->scan.itrs > 0) {
LOCKMODE lock = NoLock;
Partition tablepartition = NULL;
bool relistarget = false;
ListCell* cell = NULL;
List* part_seqs = plan->scan.pruningInfo->ls_rangeSelectedPartitions;
Assert(plan->scan.itrs == plan->scan.pruningInfo->ls_rangeSelectedPartitions->length);
relistarget = ExecRelationIsTargetRelation(estate, plan->scan.scanrelid);
lock = (relistarget ? RowExclusiveLock : AccessShareLock);
scanstate->ss.lockMode = lock;
foreach (cell, part_seqs) {
Oid tablepartitionid = InvalidOid;
int partSeq = lfirst_int(cell);
/* add table partition to list */
tablepartitionid = getPartitionOidFromSequence(currentRelation, partSeq);
tablepartition = partitionOpen(currentRelation, tablepartitionid, lock);
scanstate->ss.partitions = lappend(scanstate->ss.partitions, tablepartition);
}
}
}
|
#include <functional>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
#include "nlohmann/json.hpp"
#include <fstream>
#include <sstream>
#include "absl/flags/parse.h"
#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "contest_problem.pb.h"
#include "execution/py_locations.h"
#include "execution/py_tester_sandboxer.h"
#include "execution/status_macros.h"
#include "execution/tester_sandboxer.h"
#include "riegeli/bytes/fd_reader.h"
#include "riegeli/records/record_reader.h"
// for convenience
using json = nlohmann::json;
int main() {
// Import the .json file
std::ifstream sample_solutions_file("/home/maksgepner/CodeGenerationAnalysis/CodeContests/execution/sample_solutions.jsonl");
json sample_solutions;
sample_solutions_file >> sample_solutions;
// For getting the problem names
std::string problem_name = sample_solutions["problem_name"].get<std::string>();
std::cout << "\nProblem name: " << problem_name << "\n";
// For getting the languages of the solutions
// int i = 0;
// for (json soln : sample_solutions["generated_solutions"]) {
// std::string soln_lang = soln["language"].get<std::string>();
// std::cout << "Solution " << i << ", language: " << soln_lang << "\n";
// ++i;
// }
// For getting the code solutions
int i = 0;
int i_chosen = 0;
std::string soln_lang;
std::string target_language = "python3";
std::string target_correct = "correct";
std::string soln_correct;
absl::string_view soln_code;
for (json soln : sample_solutions["generated_solutions"]) {
soln_lang = soln["language"].get<std::string>();
if (soln["is_correct"].get<bool>() == true) {
soln_correct = "correct";
} else {
soln_correct = "incorrect";
}
// absl::string_view soln_code = soln["code"].get<absl::string_view>();
// std::cout << "\n\n\nSolution " << i << ", code (" << soln_lang << "):\n-------------------------\n" << soln_code;
if (soln_lang == target_language && soln_correct == "correct") {
soln_code = soln["code"].get<absl::string_view>();
i_chosen = i;
}
++i;
}
std::cout << "\n\nSolution " << i_chosen << " (" << target_correct << "), code (" \
<< target_language << "):\n---------------------------------------\n" << soln_code;
//std::string target_problem_name = "sds";// DEFINE THE DESIRED PROBLEM HERE as a string;
}
|
// cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2016
//
// 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)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_VIEW_REF_HPP
#define STL2_VIEW_REF_HPP
#include <memory>
#include <stl2/detail/fwd.hpp>
#include <stl2/detail/raw_ptr.hpp>
#include <stl2/detail/concepts/core.hpp>
#include <stl2/detail/concepts/object.hpp>
#include <stl2/detail/range/access.hpp>
#include <stl2/detail/range/concepts.hpp>
#include <stl2/detail/view/view_closure.hpp>
#include <stl2/view/view_interface.hpp>
STL2_OPEN_NAMESPACE {
// ref_view [ranges.view.ref]
template<Range R>
requires std::is_object_v<R>
struct ref_view;
// Not an extension: P1252 makes this user-visible
namespace __ref_view_detail {
struct __adl_hook {};
// Not to spec: should be hidden friends.
template<class R>
constexpr iterator_t<R> begin(ref_view<R> r) {
return r.begin();
}
template<class R>
constexpr sentinel_t<R> end(ref_view<R> r) {
return r.end();
}
}
template<Range R>
requires std::is_object_v<R>
struct ref_view
: private __ref_view_detail::__adl_hook
, view_interface<ref_view<R>> {
private:
R* r_ = nullptr;
static void fun(R&) noexcept; // not defined
static void fun(R&&) = delete;
public:
constexpr ref_view() noexcept = default;
#if STL2_WORKAROUND_CLANGC_42
template<class T>
requires _NotSameAs<T, ref_view> &&
requires(T&& t) { fun(static_cast<T&&>(t)); }
#else
template<_NotSameAs<ref_view> T>
requires requires(T&& t) { fun(static_cast<T&&>(t)); }
#endif
constexpr ref_view(T&& t)
#if 0
noexcept(std::is_nothrow_convertible_v<T, R&>) // strengthened
#else
noexcept(noexcept(fun(static_cast<T&&>(t)))) // strengthened
#endif
: r_{std::addressof(static_cast<R&>(static_cast<T&&>(t)))} {}
constexpr R& base() const noexcept { return *r_; }
constexpr iterator_t<R> begin() const { return __stl2::begin(*r_); }
constexpr sentinel_t<R> end() const { return __stl2::end(*r_); }
constexpr bool empty() const requires detail::CanEmpty<R> {
return __stl2::empty(*r_);
}
constexpr auto size() const requires SizedRange<R> {
return __stl2::size(*r_);
}
constexpr auto data() const requires ContiguousRange<R> {
return __stl2::data(*r_);
}
};
// This deduction guide is the P/R for LWG 3173
template<class R>
ref_view(R&) -> ref_view<R>;
namespace view::ext {
struct __ref_fn : detail::__pipeable<__ref_fn> {
template<class R>
auto operator()(R&& rng) const
STL2_REQUIRES_RETURN(
ref_view{std::forward<R>(rng)}
)
};
inline constexpr __ref_fn ref {};
} // namespace view::ext
} STL2_CLOSE_NAMESPACE
#endif
|
// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// basic_code_modules.cc: Contains all of the CodeModule objects that
// were loaded into a single process.
//
// See basic_code_modules.h for documentation.
//
// Author: Mark Mentovai
#include "processor/basic_code_modules.h"
#include <assert.h>
#include <vector>
#include "google_breakpad/processor/code_module.h"
#include "processor/linked_ptr.h"
#include "processor/logging.h"
#include "processor/range_map-inl.h"
namespace google_breakpad {
using std::vector;
BasicCodeModules::BasicCodeModules(const CodeModules* that,
MergeRangeStrategy strategy)
: main_address_(0), map_() {
BPLOG_IF(ERROR, !that) << "BasicCodeModules::BasicCodeModules requires "
"|that|";
assert(that);
map_.SetMergeStrategy(strategy);
const CodeModule *main_module = that->GetMainModule();
if (main_module)
main_address_ = main_module->base_address();
unsigned int count = that->module_count();
for (unsigned int i = 0; i < count; ++i) {
// Make a copy of the module and insert it into the map. Use
// GetModuleAtIndex because ordering is unimportant when slurping the
// entire list, and GetModuleAtIndex may be faster than
// GetModuleAtSequence.
linked_ptr<const CodeModule> module(that->GetModuleAtIndex(i)->Copy());
if (!map_.StoreRange(module->base_address(), module->size(), module)) {
BPLOG(ERROR) << "Module " << module->code_file()
<< " could not be stored";
}
}
// Report modules with shrunk ranges.
for (unsigned int i = 0; i < count; ++i) {
linked_ptr<const CodeModule> module(that->GetModuleAtIndex(i)->Copy());
uint64_t delta = 0;
if (map_.RetrieveRange(module->base_address() + module->size() - 1,
&module, NULL /* base */, &delta, NULL /* size */) &&
delta > 0) {
BPLOG(INFO) << "The range for module " << module->code_file()
<< " was shrunk down by " << HexString(delta) << " bytes.";
linked_ptr<CodeModule> shrunk_range_module(module->Copy());
shrunk_range_module->SetShrinkDownDelta(delta);
shrunk_range_modules_.push_back(shrunk_range_module);
}
}
// TODO(ivanpe): Report modules with conflicting ranges. The list of such
// modules should be copied from |that|.
}
BasicCodeModules::BasicCodeModules() : main_address_(0), map_() { }
BasicCodeModules::~BasicCodeModules() {
}
unsigned int BasicCodeModules::module_count() const {
return map_.GetCount();
}
const CodeModule* BasicCodeModules::GetModuleForAddress(
uint64_t address) const {
linked_ptr<const CodeModule> module;
if (!map_.RetrieveRange(address, &module, NULL /* base */, NULL /* delta */,
NULL /* size */)) {
BPLOG(INFO) << "No module at " << HexString(address);
return NULL;
}
return module.get();
}
const CodeModule* BasicCodeModules::GetMainModule() const {
return GetModuleForAddress(main_address_);
}
const CodeModule* BasicCodeModules::GetModuleAtSequence(
unsigned int sequence) const {
linked_ptr<const CodeModule> module;
if (!map_.RetrieveRangeAtIndex(sequence, &module, NULL /* base */,
NULL /* delta */, NULL /* size */)) {
BPLOG(ERROR) << "RetrieveRangeAtIndex failed for sequence " << sequence;
return NULL;
}
return module.get();
}
const CodeModule* BasicCodeModules::GetModuleAtIndex(
unsigned int index) const {
// This class stores everything in a RangeMap, without any more-efficient
// way to walk the list of CodeModule objects. Implement GetModuleAtIndex
// using GetModuleAtSequence, which meets all of the requirements, and
// in addition, guarantees ordering.
return GetModuleAtSequence(index);
}
const CodeModules* BasicCodeModules::Copy() const {
return new BasicCodeModules(this, map_.GetMergeStrategy());
}
vector<linked_ptr<const CodeModule> >
BasicCodeModules::GetShrunkRangeModules() const {
return shrunk_range_modules_;
}
} // namespace google_breakpad
|
// Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "xml.hxx"
namespace namespace_
{
// space
//
space::
space (value v)
: ::xml_schema::ncname (_xsd_space_literals_[v])
{
}
space::
space (const char* v)
: ::xml_schema::ncname (v)
{
}
space::
space (const ::std::string& v)
: ::xml_schema::ncname (v)
{
}
space::
space (const ::xml_schema::ncname& v)
: ::xml_schema::ncname (v)
{
}
space::
space (const space& v,
::xml_schema::flags f,
::xml_schema::container* c)
: ::xml_schema::ncname (v, f, c)
{
}
space& space::
operator= (value v)
{
static_cast< ::xml_schema::ncname& > (*this) =
::xml_schema::ncname (_xsd_space_literals_[v]);
return *this;
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
namespace namespace_
{
// space
//
space::
space (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::xml_schema::ncname (e, f, c)
{
_xsd_space_convert ();
}
space::
space (const ::xercesc::DOMAttr& a,
::xml_schema::flags f,
::xml_schema::container* c)
: ::xml_schema::ncname (a, f, c)
{
_xsd_space_convert ();
}
space::
space (const ::std::string& s,
const ::xercesc::DOMElement* e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::xml_schema::ncname (s, e, f, c)
{
_xsd_space_convert ();
}
space* space::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class space (*this, f, c);
}
space::value space::
_xsd_space_convert () const
{
::xsd::cxx::tree::enum_comparator< char > c (_xsd_space_literals_);
const value* i (::std::lower_bound (
_xsd_space_indexes_,
_xsd_space_indexes_ + 2,
*this,
c));
if (i == _xsd_space_indexes_ + 2 || _xsd_space_literals_[*i] != *this)
{
throw ::xsd::cxx::tree::unexpected_enumerator < char > (*this);
}
return *i;
}
const char* const space::
_xsd_space_literals_[2] =
{
"default",
"preserve"
};
const space::value space::
_xsd_space_indexes_[2] =
{
::namespace_::space::default_,
::namespace_::space::preserve
};
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace namespace_
{
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.