text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <stdexcept>
#include "gtest/gtest.h"
#include "map/Level.h"
#include "map/Tile.h"
TEST(LevelTest, DefaultLevelIsWalls)
{
Level l1(10, 10);
EXPECT_EQ(WallTile, l1.getTile(5, 5));
}
TEST(LevelTest, LevelGetTile)
{
Level l1(10, 10);
EXPECT_NO_THROW(l1.getTile(0, 0));
EXPECT_NO_THROW(l1.getTile(9, 9));
EXPECT_THROW(l1.getTile(10, 10), std::out_of_range);
}
TEST(LevelTest, LevelSetTile)
{
Level l1(10, 10);
EXPECT_EQ(WallTile, l1.getTile(0, 0));
l1.setTile(0, 0, FloorTile);
EXPECT_EQ(FloorTile, l1.getTile(0, 0));
}
TEST(LevelTest, LevelArrayAccess)
{
Level l1(10, 10);
EXPECT_NO_THROW(l1[0][0]);
EXPECT_NO_THROW(l1[9][9]);
EXPECT_THROW(l1[10][10], std::out_of_range);
}
<commit_msg>Renaming Level object to Map<commit_after>#include <stdexcept>
#include "gtest/gtest.h"
#include "map/Map.h"
#include "map/Tile.h"
TEST(MapTest, DefaultMapIsWalls)
{
Map m1(10, 10);
EXPECT_EQ(WallTile, m1.getTile(5, 5));
}
TEST(MapTest, MapGetTile)
{
Map m1(10, 10);
EXPECT_NO_THROW(m1.getTile(0, 0));
EXPECT_NO_THROW(m1.getTile(9, 9));
EXPECT_THROW(m1.getTile(10, 10), std::out_of_range);
}
TEST(MapTest, MapSetTile)
{
Map m1(10, 10);
EXPECT_EQ(WallTile, m1.getTile(0, 0));
m1.setTile(0, 0, FloorTile);
EXPECT_EQ(FloorTile, m1.getTile(0, 0));
}
TEST(MapTest, MapArrayAccess)
{
Map m1(10, 10);
EXPECT_NO_THROW(m1[0][0]);
EXPECT_NO_THROW(m1[9][9]);
EXPECT_THROW(m1[10][10], std::out_of_range);
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <iostream>
#include "Vcpu.h"
using namespace std;
#define MEMSIZE 65536
void tick(Vcpu *cpu);
void print_stats(Vcpu *cpu, int time);
int main(int argc, char **argv) {
Verilated::commandArgs(argc, argv);
if (argc < 2) {
cerr << "usage: " << argv[0] << " <6502 executable>" << endl;
return 1;
}
Vcpu *cpu = new Vcpu;
char memory[MEMSIZE];
memset((char *)memory, 9, sizeof(memory));
int time = 0;
uint16_t addr = 0;
uint8_t input;
/* Read assembled binary into simulated memory */
char *filename = argv[1];
FILE *binary = fopen(filename, "r");
if (binary == NULL) {
perror(filename);
return 2;
}
size_t len = fread(memory, 1, MEMSIZE, binary);
while (1) {
if (Verilated::gotFinish()) { break; }
addr = cpu->addr;
if (addr == (len+1)) { break; }
if (cpu->write) { memory[cpu->addr] = cpu->d_out; }
tick(cpu);
input = memory[addr];
cpu->d_in = input;
print_stats(cpu, time);
time++;
}
cpu->final();
delete cpu;
return 0;
}
void tick(Vcpu *cpu) {
cpu->clk = 0;
cpu->eval();
cpu->clk = 1;
cpu->eval();
}
void print_stats(Vcpu *cpu, int time) {
static int first = 1;
if (first) {
printf("Cycle Op A\n");// X Y P\n");
first = 0;
}
if (cpu->sync) {
printf("%5d %.2x %.2x\n",// %.2x %.2x %.2x\n",
time,
cpu->v__DOT__IR,
cpu->v__DOT__A);/*,
cpu->v__DOT__X,
cpu->v__DOT__Y,
cpu->v__DOT__P);*/
}
}
<commit_msg>cpu_tb.cpp: untabified and added missing cpu->eval()<commit_after>#include <cstdio>
#include <iostream>
#include "Vcpu.h"
using namespace std;
#define MEMSIZE 65536
void tick(Vcpu *cpu);
void print_stats(Vcpu *cpu, int time);
int main(int argc, char **argv) {
Verilated::commandArgs(argc, argv);
if (argc < 2) {
cerr << "usage: " << argv[0] << " <6502 executable>" << endl;
return 1;
}
Vcpu *cpu = new Vcpu;
char memory[MEMSIZE];
memset((char *)memory, 9, sizeof(memory));
int time = 0;
uint16_t addr = 0;
uint8_t input;
/* Read assembled binary into simulated memory */
char *filename = argv[1];
FILE *binary = fopen(filename, "r");
if (binary == NULL) {
perror(filename);
return 2;
}
size_t len = fread(memory, 1, MEMSIZE, binary);
while (1) {
if (Verilated::gotFinish()) { break; }
addr = cpu->addr;
if (addr == (len+1)) { break; }
if (cpu->write) { memory[cpu->addr] = cpu->d_out; }
tick(cpu);
input = memory[addr];
cpu->d_in = input;
cpu->eval();
print_stats(cpu, time);
time++;
}
cpu->final();
delete cpu;
return 0;
}
void tick(Vcpu *cpu) {
cpu->clk = 0;
cpu->eval();
cpu->clk = 1;
cpu->eval();
}
void print_stats(Vcpu *cpu, int time) {
static int first = 1;
if (first) {
printf("Cycle Op A\n");// X Y P\n");
first = 0;
}
if (cpu->sync) {
printf("%5d %.2x %.2x\n",// %.2x %.2x %.2x\n",
time,
cpu->v__DOT__IR,
cpu->v__DOT__A);/*,
cpu->v__DOT__X,
cpu->v__DOT__Y,
cpu->v__DOT__P);*/
}
}
<|endoftext|>
|
<commit_before>#include "thing/Portal.h"
#include "third-party/arduino-json-5.6.7/include/ArduinoJson.h"
namespace thing {
Portal::Portal()
: callback_([](const Config&){}),
debug_([](const char*){}) {}
void Portal::SetDebugHandler(std::function<void(const char* message)> handler) {
debug_ = std::move(handler);
}
void Portal::Start(const Config& config) {
config_ = config;
server_.on("/", [&] () {
static const PROGMEM char page[] = R"(
<head>
<script>
function fetch_config() {
document.getElementById('loading').style.display='inline'
var xhr = new XMLHttpRequest();
xhr.open("GET", "/config", true);
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
populate_values(JSON.parse(xhr.responseText));
document.getElementById('loading').style.display='none'
}
}
xhr.send();
}
function populate_values(config) {
document.getElementById('host').value = config.host;
document.getElementById('auth').value = config.auth;
document.getElementById('path').value = config.path;
document.getElementById('ssid').value = config.wifi_ssid;
document.getElementById('key').value = config.wifi_key;
}
function build_config() {
var config = {
host : document.getElementById('host').value,
auth : document.getElementById('auth').value,
path : document.getElementById('path').value,
wifi_ssid : document.getElementById('ssid').value,
wifi_key : document.getElementById('key').value
};
return config;
}
function send_config() {
document.getElementById('saving').style.display='inline'
var xhr = new XMLHttpRequest();
xhr.open("POST", "/config", true);
xhr.send("config=" + JSON.stringify(build_config()));
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById('saving').style.display='none'
}
}
}
function scan() {
document.getElementById('scanning').style.display='inline';
var xhr = new XMLHttpRequest();
xhr.open("GET", "/wifi/scan", true);
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
load_networks(JSON.parse(xhr.responseText));
document.getElementById('scanning').style.display='none';
}
}
xhr.send();
}
function load_networks(networks) {
select = document.getElementById('networks');
select.innerHtml = '';
networks.sort(function(a, b) {
return b.rssi - a.rssi;
});
networks.forEach(function(network) {
option = document.createElement('option');
option.value = network.ssid;
option.text = network.ssid + ' (' + network.rssi + ')';
select.add(option);
});
select.style.display='inline';
}
function set_network(select) {
document.getElementById('ssid').value = select[select.selectedIndex].value;
}
</script>
</head>
<body>
<div>Host: <input id='host'></div>
<div>Auth: <input id='auth'></div>
<div>Path: <input id='path'></div>
<div>Wifi SSID: <input id='ssid'><button onclick='scan();'>scan</button></div>
<div id='scanning' style='display:none'>Scanning...</div>
<div><select size=10 id='networks' style='display:none' onchange='set_network(this);'></select></div>
<div>Wifi Key: <input id='key'></div>
<div><button onclick='send_config();'>Save</button></div>
<div id='loading'>Loading....</div>
<div id='saving' style='display:none'>Saving....</div>
<script>fetch_config();</script>
</body>
)";
static const PROGMEM char type[] = "text/html";
server_.send_P(200, type, page);
debug_("served root page.");
});
server_.on("/config", [&] () {
if (server_.method() == HTTP_GET) {
auto client = server_.client();
config_.SerializeToJson(&client,
[this](int size) {
server_.setContentLength(size);
server_.send(200, "application/json");
});
debug_("config retrieved");
} else if (server_.method() == HTTP_POST) {
DynamicJsonBuffer jsonBuffer;
if (!server_.hasArg("config")) {
server_.send(500, "text/plain", "Missing config.\r\n");
debug_("Config updated called without param.");
return;
}
char* buffer;
{ // Scoped to free String memory.
String config = server_.arg("config");
buffer = (char*)malloc(config.length+1());
memcpy(buffer, config.c_str(), config.length()+1);
}
config_.ReadFromJson(buffer);
free(buffer);
callback_(config_);
server_.send(200, "text/plain", "");
debug_("config updated.");
}
});
server_.on("/wifi/scan", [&] () {
int net_count = WiFi.scanNetworks();
DynamicJsonBuffer json_buffer;
JsonArray& data = json_buffer.createArray();
for (int i=0; i < net_count; i++) {
JsonObject& entry = data.createNestedObject();
entry["ssid"] = WiFi.SSID(i);
entry["rssi"] = WiFi.RSSI(i);
}
// Free station info from memory.
WiFi.scanDelete();
String buffer;
data.printTo(buffer);
server_.send(200, "application/json", buffer);
debug_("served networks.");
});
server_.begin();
debug_("Portal started.");
}
void Portal::Loop() {
server_.handleClient();
}
void Portal::NotifyOnUpdate(std::function<void(const Config& config)> callback) {
callback_ = callback;
}
};
<commit_msg>fixed typo<commit_after>#include "thing/Portal.h"
#include "third-party/arduino-json-5.6.7/include/ArduinoJson.h"
namespace thing {
Portal::Portal()
: callback_([](const Config&){}),
debug_([](const char*){}) {}
void Portal::SetDebugHandler(std::function<void(const char* message)> handler) {
debug_ = std::move(handler);
}
void Portal::Start(const Config& config) {
config_ = config;
server_.on("/", [&] () {
static const PROGMEM char page[] = R"(
<head>
<script>
function fetch_config() {
document.getElementById('loading').style.display='inline'
var xhr = new XMLHttpRequest();
xhr.open("GET", "/config", true);
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
populate_values(JSON.parse(xhr.responseText));
document.getElementById('loading').style.display='none'
}
}
xhr.send();
}
function populate_values(config) {
document.getElementById('host').value = config.host;
document.getElementById('auth').value = config.auth;
document.getElementById('path').value = config.path;
document.getElementById('ssid').value = config.wifi_ssid;
document.getElementById('key').value = config.wifi_key;
}
function build_config() {
var config = {
host : document.getElementById('host').value,
auth : document.getElementById('auth').value,
path : document.getElementById('path').value,
wifi_ssid : document.getElementById('ssid').value,
wifi_key : document.getElementById('key').value
};
return config;
}
function send_config() {
document.getElementById('saving').style.display='inline'
var xhr = new XMLHttpRequest();
xhr.open("POST", "/config", true);
xhr.send("config=" + JSON.stringify(build_config()));
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById('saving').style.display='none'
}
}
}
function scan() {
document.getElementById('scanning').style.display='inline';
var xhr = new XMLHttpRequest();
xhr.open("GET", "/wifi/scan", true);
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200) {
load_networks(JSON.parse(xhr.responseText));
document.getElementById('scanning').style.display='none';
}
}
xhr.send();
}
function load_networks(networks) {
select = document.getElementById('networks');
select.innerHtml = '';
networks.sort(function(a, b) {
return b.rssi - a.rssi;
});
networks.forEach(function(network) {
option = document.createElement('option');
option.value = network.ssid;
option.text = network.ssid + ' (' + network.rssi + ')';
select.add(option);
});
select.style.display='inline';
}
function set_network(select) {
document.getElementById('ssid').value = select[select.selectedIndex].value;
}
</script>
</head>
<body>
<div>Host: <input id='host'></div>
<div>Auth: <input id='auth'></div>
<div>Path: <input id='path'></div>
<div>Wifi SSID: <input id='ssid'><button onclick='scan();'>scan</button></div>
<div id='scanning' style='display:none'>Scanning...</div>
<div><select size=10 id='networks' style='display:none' onchange='set_network(this);'></select></div>
<div>Wifi Key: <input id='key'></div>
<div><button onclick='send_config();'>Save</button></div>
<div id='loading'>Loading....</div>
<div id='saving' style='display:none'>Saving....</div>
<script>fetch_config();</script>
</body>
)";
static const PROGMEM char type[] = "text/html";
server_.send_P(200, type, page);
debug_("served root page.");
});
server_.on("/config", [&] () {
if (server_.method() == HTTP_GET) {
auto client = server_.client();
config_.SerializeToJson(&client,
[this](int size) {
server_.setContentLength(size);
server_.send(200, "application/json");
});
debug_("config retrieved");
} else if (server_.method() == HTTP_POST) {
DynamicJsonBuffer jsonBuffer;
if (!server_.hasArg("config")) {
server_.send(500, "text/plain", "Missing config.\r\n");
debug_("Config updated called without param.");
return;
}
char* buffer;
{ // Scoped to free String memory.
String config = server_.arg("config");
buffer = (char*)malloc(config.length()+1);
memcpy(buffer, config.c_str(), config.length()+1);
}
config_.ReadFromJson(buffer);
free(buffer);
callback_(config_);
server_.send(200, "text/plain", "");
debug_("config updated.");
}
});
server_.on("/wifi/scan", [&] () {
int net_count = WiFi.scanNetworks();
DynamicJsonBuffer json_buffer;
JsonArray& data = json_buffer.createArray();
for (int i=0; i < net_count; i++) {
JsonObject& entry = data.createNestedObject();
entry["ssid"] = WiFi.SSID(i);
entry["rssi"] = WiFi.RSSI(i);
}
// Free station info from memory.
WiFi.scanDelete();
String buffer;
data.printTo(buffer);
server_.send(200, "application/json", buffer);
debug_("served networks.");
});
server_.begin();
debug_("Portal started.");
}
void Portal::Loop() {
server_.handleClient();
}
void Portal::NotifyOnUpdate(std::function<void(const Config& config)> callback) {
callback_ = callback;
}
};
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MissionControllerManagerTest.h"
#include "LinkManager.h"
#include "MultiVehicleManager.h"
#include "QGCApplication.h"
MissionControllerManagerTest::MissionControllerManagerTest(void)
{
}
void MissionControllerManagerTest::cleanup(void)
{
delete _multiSpyMissionManager;
_multiSpyMissionManager = NULL;
UnitTest::cleanup();
}
void MissionControllerManagerTest::_initForFirmwareType(MAV_AUTOPILOT firmwareType)
{
_connectMockLink(firmwareType);
// Wait for the Mission Manager to finish it's initial load
_missionManager = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()->missionManager();
QVERIFY(_missionManager);
_rgMissionManagerSignals[newMissionItemsAvailableSignalIndex] = SIGNAL(newMissionItemsAvailable(bool));
_rgMissionManagerSignals[sendCompleteSignalIndex] = SIGNAL(sendComplete(void));
_rgMissionManagerSignals[inProgressChangedSignalIndex] = SIGNAL(inProgressChanged(bool));
_rgMissionManagerSignals[errorSignalIndex] = SIGNAL(error(int, const QString&));
_multiSpyMissionManager = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpyMissionManager);
QCOMPARE(_multiSpyMissionManager->init(_missionManager, _rgMissionManagerSignals, _cMissionManagerSignals), true);
if (_missionManager->inProgress()) {
_multiSpyMissionManager->waitForSignalByIndex(newMissionItemsAvailableSignalIndex, _missionManagerSignalWaitTime);
_multiSpyMissionManager->waitForSignalByIndex(inProgressChangedSignalIndex, _missionManagerSignalWaitTime);
QCOMPARE(_multiSpyMissionManager->checkSignalByMask(newMissionItemsAvailableSignalMask | inProgressChangedSignalMask), true);
}
QVERIFY(!_missionManager->inProgress());
QCOMPARE(_missionManager->missionItems().count(), 0);
_multiSpyMissionManager->clearAllSignals();
}
/// Checks the state of the inProgress value and signal to match the specified value
void MissionControllerManagerTest::_checkInProgressValues(bool inProgress)
{
QCOMPARE(_missionManager->inProgress(), inProgress);
QCOMPARE(_multiSpyMissionManager->pullBoolFromSignalIndex(inProgressChangedSignalIndex), inProgress);
}
<commit_msg>Fix for signal signature change<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MissionControllerManagerTest.h"
#include "LinkManager.h"
#include "MultiVehicleManager.h"
#include "QGCApplication.h"
MissionControllerManagerTest::MissionControllerManagerTest(void)
{
}
void MissionControllerManagerTest::cleanup(void)
{
delete _multiSpyMissionManager;
_multiSpyMissionManager = NULL;
UnitTest::cleanup();
}
void MissionControllerManagerTest::_initForFirmwareType(MAV_AUTOPILOT firmwareType)
{
_connectMockLink(firmwareType);
// Wait for the Mission Manager to finish it's initial load
_missionManager = qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()->missionManager();
QVERIFY(_missionManager);
_rgMissionManagerSignals[newMissionItemsAvailableSignalIndex] = SIGNAL(newMissionItemsAvailable(bool));
_rgMissionManagerSignals[sendCompleteSignalIndex] = SIGNAL(sendComplete(bool));
_rgMissionManagerSignals[inProgressChangedSignalIndex] = SIGNAL(inProgressChanged(bool));
_rgMissionManagerSignals[errorSignalIndex] = SIGNAL(error(int, const QString&));
_multiSpyMissionManager = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpyMissionManager);
QCOMPARE(_multiSpyMissionManager->init(_missionManager, _rgMissionManagerSignals, _cMissionManagerSignals), true);
if (_missionManager->inProgress()) {
_multiSpyMissionManager->waitForSignalByIndex(newMissionItemsAvailableSignalIndex, _missionManagerSignalWaitTime);
_multiSpyMissionManager->waitForSignalByIndex(inProgressChangedSignalIndex, _missionManagerSignalWaitTime);
QCOMPARE(_multiSpyMissionManager->checkSignalByMask(newMissionItemsAvailableSignalMask | inProgressChangedSignalMask), true);
}
QVERIFY(!_missionManager->inProgress());
QCOMPARE(_missionManager->missionItems().count(), 0);
_multiSpyMissionManager->clearAllSignals();
}
/// Checks the state of the inProgress value and signal to match the specified value
void MissionControllerManagerTest::_checkInProgressValues(bool inProgress)
{
QCOMPARE(_missionManager->inProgress(), inProgress);
QCOMPARE(_multiSpyMissionManager->pullBoolFromSignalIndex(inProgressChangedSignalIndex), inProgress);
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// tuple_transformer.cpp
//
// Identification: src/backend/bridge/dml/tuple/tuple_transformer.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include "backend/bridge/dml/tuple/tuple_transformer.h"
#include "backend/common/logger.h"
#include "backend/common/value_peeker.h"
#include "backend/storage/tuple.h"
#include "backend/common/types.h"
#include "backend/bridge/ddl/ddl.h"
#include "access/htup_details.h"
#include "nodes/print.h"
#include "utils/builtins.h"
namespace peloton {
namespace bridge {
/**
* @brief Convert from Datum to Value.
* @return converted Value.
*/
Value TupleTransformer::GetValue(Datum datum, Oid atttypid) {
Value value;
switch (atttypid) {
case POSTGRES_VALUE_TYPE_SMALLINT: {
int16_t smallint = DatumGetInt16(datum);
LOG_TRACE("%d\n", smallint);
value = ValueFactory::GetSmallIntValue(smallint);
} break;
case POSTGRES_VALUE_TYPE_INTEGER: {
int32_t integer = DatumGetInt32(datum);
LOG_TRACE("%d\n", integer);
value = ValueFactory::GetIntegerValue(integer);
} break;
case POSTGRES_VALUE_TYPE_BIGINT: {
int64_t bigint = DatumGetInt64(datum);
LOG_TRACE("%ld\n", bigint);
value = ValueFactory::GetBigIntValue(bigint);
} break;
/*
* In PG, BPCHAR and VARCHAR and TEXT are represented using
* 'struct varlena',
* which is a 4-byte header followed by the meat.
* However, the 4-byte header should not be accessed directly.
* It should be used in MACROS:
* VARSIZE(ptr), VARDATA(ptr) and VARHDRSZ.
* NB1: VARSIZE(ptr) is the size of the meat PLUS the header.
* NB2: DON'T assume strings have terminating-null's.
*/
case POSTGRES_VALUE_TYPE_BPCHAR: {
struct varlena *bpcharptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(bpcharptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(bpcharptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , bpchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_VARCHAR2: {
struct varlena *varlenptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(varlenptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(varlenptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , varchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TEXT: {
struct varlena *textptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(textptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(textptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , text = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TIMESTAMPS: {
long int timestamp = DatumGetInt64(datum);
value = ValueFactory::GetTimestampValue(timestamp);
} break;
default:
LOG_ERROR("Unknown atttypeid : %u ", atttypid);
break;
}
return value;
}
/**
* @brief Convert from Value to Datum.
* @return converted Datum.
*/
Datum TupleTransformer::GetDatum(Value value) {
ValueType value_type;
Datum datum;
value_type = value.GetValueType();
switch (value_type) {
case VALUE_TYPE_SMALLINT: {
int16_t smallint = ValuePeeker::PeekSmallInt(value);
LOG_TRACE("%d\n", smallint);
datum = Int16GetDatum(smallint);
} break;
case VALUE_TYPE_INTEGER: {
int32_t integer = ValuePeeker::PeekInteger(value);
LOG_TRACE("%d\n", integer);
datum = Int32GetDatum(integer);
} break;
case VALUE_TYPE_BIGINT: {
int64_t bigint = ValuePeeker::PeekBigInt(value);
LOG_TRACE("%ld\n", bigint);
datum = Int64GetDatum(bigint);
} break;
case VALUE_TYPE_DOUBLE: {
double double_precision = ValuePeeker::PeekDouble(value);
LOG_TRACE("%f\n", double_precision);
datum = Float8GetDatum(double_precision);
} break;
case VALUE_TYPE_VARCHAR: {
char *data_ptr = static_cast<char *>(ValuePeeker::PeekObjectValue(value));
auto data_len = ValuePeeker::PeekObjectLength(value);
// NB: Peloton object don't have terminating-null's, so
// we should use PG functions that take explicit length.
datum = PointerGetDatum(cstring_to_text_with_len(data_ptr, data_len));
} break;
case VALUE_TYPE_TIMESTAMP: {
long int timestamp = ValuePeeker::PeekTimestamp(value);
datum = Int64GetDatum(timestamp);
LOG_TRACE("%s\n", DatumGetCString(timestamp));
} break;
default:
datum = PointerGetDatum(nullptr);
LOG_ERROR("Unrecognized value type : %u\n", value_type);
break;
}
return datum;
}
/**
* @brief Convert a Postgres tuple into Peloton tuple
* @param slot Postgres tuple
* @param schema Peloton scheme of the table to which the tuple belongs
* @return a Peloton tuple
*/
storage::Tuple *TupleTransformer::GetPelotonTuple(
TupleTableSlot *slot, const catalog::Schema *schema) {
assert(slot);
TupleDesc tuple_desc = slot->tts_tupleDescriptor;
int natts = tuple_desc->natts;
bool isnull;
// Allocate space for a new tuple with given schema
storage::Tuple *tuple = new storage::Tuple(schema, true);
// Go over each attribute and convert Datum to Value
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Datum attr = slot_getattr(slot, att_itr + 1, &isnull);
if (isnull) continue;
Form_pg_attribute attribute_info = tuple_desc->attrs[att_itr];
Oid attribute_type_id = attribute_info->atttypid;
Value value = GetValue(attr, attribute_type_id);
tuple->SetValue(att_itr++, value);
}
return tuple;
}
/**
* @brief Convert a Peloton tuple into Postgres tuple slot
* @param tuple Peloton tuple
* @return a Postgres tuple
*/
TupleTableSlot *TupleTransformer::GetPostgresTuple(storage::Tuple *tuple,
TupleDesc tuple_desc) {
assert(tuple);
assert(tuple_desc);
TupleTableSlot *slot = NULL;
HeapTuple heap_tuple;
int natts = tuple_desc->natts;
Datum *datums;
bool *nulls;
if (tuple->GetColumnCount() != natts) {
LOG_WARN("tuple attr count : %u tuple desc attr count : %d \n",
tuple->GetColumnCount(), natts);
return nullptr;
}
// Allocate space for datums
datums = (Datum *)palloc0(natts * sizeof(Datum));
nulls = (bool *)palloc0(natts * sizeof(bool));
// Go over each attribute and convert Value to Datum
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Value value = tuple->GetValue(att_itr);
Datum datum = GetDatum(value);
LOG_INFO("ByVal :: %d ", tuple_desc->attrs[att_itr]->attbyval);
LOG_INFO("Type :: %d ", value.GetValueType());
assert(tuple_desc->attrs[att_itr]->attbyval == true ||
value.GetValueType() == VALUE_TYPE_VARCHAR ||
value.GetValueType() == VALUE_TYPE_VARBINARY);
datums[att_itr] = datum;
nulls[att_itr] = tuple->IsNull(att_itr) ? true : false;
}
// Construct tuple
// PG does a deep copy in heap_form_tuple()
heap_tuple = heap_form_tuple(tuple_desc, datums, nulls);
// Construct slot
slot = MakeSingleTupleTableSlot(tuple_desc);
// Store tuple in slot
// This function just sets a point in slot to the heap_tuple.
ExecStoreTuple(heap_tuple, slot, InvalidBuffer, true);
// Clean up Datums (A-B): seems we have to do the cleaning manually (no PG
// utility?)
// (A) Clean up any possible varlena's
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
if (tuple_desc->attrs[att_itr]->attlen < 0) { // should be a varlena
assert(tuple_desc->attrs[att_itr]->attbyval == false);
pfree((void *)(datums[att_itr]));
}
}
// (B) Free the datum array itself
pfree(datums);
pfree(nulls);
return slot;
}
} // namespace bridge
} // namespace peloton
<commit_msg>Remove log comment.<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// tuple_transformer.cpp
//
// Identification: src/backend/bridge/dml/tuple/tuple_transformer.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include "backend/bridge/dml/tuple/tuple_transformer.h"
#include "backend/common/logger.h"
#include "backend/common/value_peeker.h"
#include "backend/storage/tuple.h"
#include "backend/common/types.h"
#include "backend/bridge/ddl/ddl.h"
#include "access/htup_details.h"
#include "nodes/print.h"
#include "utils/builtins.h"
namespace peloton {
namespace bridge {
/**
* @brief Convert from Datum to Value.
* @return converted Value.
*/
Value TupleTransformer::GetValue(Datum datum, Oid atttypid) {
Value value;
switch (atttypid) {
case POSTGRES_VALUE_TYPE_SMALLINT: {
int16_t smallint = DatumGetInt16(datum);
LOG_TRACE("%d\n", smallint);
value = ValueFactory::GetSmallIntValue(smallint);
} break;
case POSTGRES_VALUE_TYPE_INTEGER: {
int32_t integer = DatumGetInt32(datum);
LOG_TRACE("%d\n", integer);
value = ValueFactory::GetIntegerValue(integer);
} break;
case POSTGRES_VALUE_TYPE_BIGINT: {
int64_t bigint = DatumGetInt64(datum);
LOG_TRACE("%ld\n", bigint);
value = ValueFactory::GetBigIntValue(bigint);
} break;
/*
* In PG, BPCHAR and VARCHAR and TEXT are represented using
* 'struct varlena',
* which is a 4-byte header followed by the meat.
* However, the 4-byte header should not be accessed directly.
* It should be used in MACROS:
* VARSIZE(ptr), VARDATA(ptr) and VARHDRSZ.
* NB1: VARSIZE(ptr) is the size of the meat PLUS the header.
* NB2: DON'T assume strings have terminating-null's.
*/
case POSTGRES_VALUE_TYPE_BPCHAR: {
struct varlena *bpcharptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(bpcharptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(bpcharptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , bpchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_VARCHAR2: {
struct varlena *varlenptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(varlenptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(varlenptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , varchar = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TEXT: {
struct varlena *textptr = reinterpret_cast<struct varlena *>(datum);
int len = VARSIZE(textptr) - VARHDRSZ;
char *varchar = static_cast<char *>(VARDATA(textptr));
Pool *data_pool = nullptr;
std::string str(varchar, len);
LOG_TRACE("len = %d , text = \"%s\"", len, str.c_str());
value = ValueFactory::GetStringValue(str, data_pool);
} break;
case POSTGRES_VALUE_TYPE_TIMESTAMPS: {
long int timestamp = DatumGetInt64(datum);
value = ValueFactory::GetTimestampValue(timestamp);
} break;
default:
LOG_ERROR("Unknown atttypeid : %u ", atttypid);
break;
}
return value;
}
/**
* @brief Convert from Value to Datum.
* @return converted Datum.
*/
Datum TupleTransformer::GetDatum(Value value) {
ValueType value_type;
Datum datum;
value_type = value.GetValueType();
switch (value_type) {
case VALUE_TYPE_SMALLINT: {
int16_t smallint = ValuePeeker::PeekSmallInt(value);
LOG_TRACE("%d\n", smallint);
datum = Int16GetDatum(smallint);
} break;
case VALUE_TYPE_INTEGER: {
int32_t integer = ValuePeeker::PeekInteger(value);
LOG_TRACE("%d\n", integer);
datum = Int32GetDatum(integer);
} break;
case VALUE_TYPE_BIGINT: {
int64_t bigint = ValuePeeker::PeekBigInt(value);
LOG_TRACE("%ld\n", bigint);
datum = Int64GetDatum(bigint);
} break;
case VALUE_TYPE_DOUBLE: {
double double_precision = ValuePeeker::PeekDouble(value);
LOG_TRACE("%f\n", double_precision);
datum = Float8GetDatum(double_precision);
} break;
case VALUE_TYPE_VARCHAR: {
char *data_ptr = static_cast<char *>(ValuePeeker::PeekObjectValue(value));
auto data_len = ValuePeeker::PeekObjectLength(value);
// NB: Peloton object don't have terminating-null's, so
// we should use PG functions that take explicit length.
datum = PointerGetDatum(cstring_to_text_with_len(data_ptr, data_len));
} break;
case VALUE_TYPE_TIMESTAMP: {
long int timestamp = ValuePeeker::PeekTimestamp(value);
datum = Int64GetDatum(timestamp);
LOG_TRACE("%s\n", DatumGetCString(timestamp));
} break;
default:
datum = PointerGetDatum(nullptr);
LOG_ERROR("Unrecognized value type : %u\n", value_type);
break;
}
return datum;
}
/**
* @brief Convert a Postgres tuple into Peloton tuple
* @param slot Postgres tuple
* @param schema Peloton scheme of the table to which the tuple belongs
* @return a Peloton tuple
*/
storage::Tuple *TupleTransformer::GetPelotonTuple(
TupleTableSlot *slot, const catalog::Schema *schema) {
assert(slot);
TupleDesc tuple_desc = slot->tts_tupleDescriptor;
int natts = tuple_desc->natts;
bool isnull;
// Allocate space for a new tuple with given schema
storage::Tuple *tuple = new storage::Tuple(schema, true);
// Go over each attribute and convert Datum to Value
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Datum attr = slot_getattr(slot, att_itr + 1, &isnull);
if (isnull) continue;
Form_pg_attribute attribute_info = tuple_desc->attrs[att_itr];
Oid attribute_type_id = attribute_info->atttypid;
Value value = GetValue(attr, attribute_type_id);
tuple->SetValue(att_itr++, value);
}
return tuple;
}
/**
* @brief Convert a Peloton tuple into Postgres tuple slot
* @param tuple Peloton tuple
* @return a Postgres tuple
*/
TupleTableSlot *TupleTransformer::GetPostgresTuple(storage::Tuple *tuple,
TupleDesc tuple_desc) {
assert(tuple);
assert(tuple_desc);
TupleTableSlot *slot = NULL;
HeapTuple heap_tuple;
int natts = tuple_desc->natts;
Datum *datums;
bool *nulls;
if (tuple->GetColumnCount() != natts) {
LOG_WARN("tuple attr count : %u tuple desc attr count : %d \n",
tuple->GetColumnCount(), natts);
return nullptr;
}
// Allocate space for datums
datums = (Datum *)palloc0(natts * sizeof(Datum));
nulls = (bool *)palloc0(natts * sizeof(bool));
// Go over each attribute and convert Value to Datum
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
Value value = tuple->GetValue(att_itr);
Datum datum = GetDatum(value);
assert(tuple_desc->attrs[att_itr]->attbyval == true ||
value.GetValueType() == VALUE_TYPE_VARCHAR ||
value.GetValueType() == VALUE_TYPE_VARBINARY);
datums[att_itr] = datum;
nulls[att_itr] = tuple->IsNull(att_itr) ? true : false;
}
// Construct tuple
// PG does a deep copy in heap_form_tuple()
heap_tuple = heap_form_tuple(tuple_desc, datums, nulls);
// Construct slot
slot = MakeSingleTupleTableSlot(tuple_desc);
// Store tuple in slot
// This function just sets a point in slot to the heap_tuple.
ExecStoreTuple(heap_tuple, slot, InvalidBuffer, true);
// Clean up Datums (A-B): seems we have to do the cleaning manually (no PG
// utility?)
// (A) Clean up any possible varlena's
for (oid_t att_itr = 0; att_itr < natts; ++att_itr) {
if (tuple_desc->attrs[att_itr]->attlen < 0) { // should be a varlena
assert(tuple_desc->attrs[att_itr]->attbyval == false);
pfree((void *)(datums[att_itr]));
}
}
// (B) Free the datum array itself
pfree(datums);
pfree(nulls);
return slot;
}
} // namespace bridge
} // namespace peloton
<|endoftext|>
|
<commit_before>/*
MIT License
Copyright (c) 2017 Alan Tonks
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 "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
Serial::Serial() {
PORT = "/dev/ttyUSB0";
Serial(4800, PORT, true);
}
Serial::Serial(speed_t baud, std::string port)
{
Serial(baud, port, true);
}
Serial::Serial(speed_t baud, std::string port, bool canon)
{
// Make a copy of the current configuration so it can be
// restored in destructor.
isCanonical = canon;
if (setBaud(baud) == 0) BAUDRATE = baud; // baudrate must be multiple of 2400
isOpen = false;
struct stat stat_buf; // See if specified port exists
if (stat(port.c_str(), &stat_buf) == 0) PORT = port;
else { // Port doesn't exist
std::cout << "Device not found." << std::endl;
exit(-1);
}
// open port for read and write, not controlling, ignore DCD line
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("In function: Serial()\n Failed to open device: ");
exit(-1);
}
else isOpen = true;
init();
}
// Open and configure the port
void Serial::init()
{
tcgetattr(dev_fd, &oldConfig);
// memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical) terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status_i = -1;
int status_o = -1;
switch (baud) {
case 2400:
status_i = cfsetispeed(&terminalConfiguration, B2400);
status_o = cfsetospeed(&terminalConfiguration, B2400);
break;
case 4800:
status_i = cfsetispeed(&terminalConfiguration, B4800);
status_o = cfsetospeed(&terminalConfiguration, B4800);
break;
case 9600:
status_i = cfsetispeed(&terminalConfiguration, B9600);
status_o = cfsetospeed(&terminalConfiguration, B9600);
break;
case 19200:
status_i = cfsetispeed(&terminalConfiguration, B19200);
status_o = cfsetospeed(&terminalConfiguration, B19200);
break;
case 38400:
status_i = cfsetispeed(&terminalConfiguration, B38400);
status_o = cfsetospeed(&terminalConfiguration, B38400);
break;
case 57600:
status_i = cfsetispeed(&terminalConfiguration, B57600);
status_o = cfsetospeed(&terminalConfiguration, B57600);
break;
case 115200:
status_i = cfsetispeed(&terminalConfiguration, B115200);
status_o = cfsetospeed(&terminalConfiguration, B115200);
break;
case 230400:
status_i = cfsetispeed(&terminalConfiguration, B230400);
status_o = cfsetospeed(&terminalConfiguration, B230400);
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status_i < 0 || status_o < 0) {
perror("In function: setBaud()\nFailed to set requested baudrate: ");
return -1;
}
else return status_i;
}
int Serial::applyNewConfig()
{
if (isOpen) {
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) perror("Could not apply configuration: ");
else return 0;
}
else return -1;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
if (setupRead() < 0) return -1;
int buf_size = 255; // 82 is longest NMEA Sentence
char buf[buf_size];
bytesReceived = read(dev_fd, buf, buf_size);
if (bytesReceived < 0) perror("In function serialRead()\nRead failed: ");
else buf[bytesReceived] = '\0'; // Null terminate the string
serialData.assign(buf); // store serialData as std::string
return bytesReceived;
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
//if (isOpen) return serialData;
else return "Open serial port first!\n";
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); /* Leave port how we found it. */
close(dev_fd); /* close the port */
}<commit_msg>Added debug output<commit_after>/*
MIT License
Copyright (c) 2017 Alan Tonks
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 "serial.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
Serial::Serial() {
PORT = "/dev/ttyUSB0";
Serial(4800, PORT, true);
}
Serial::Serial(speed_t baud, std::string port)
{
Serial(baud, port, true);
}
Serial::Serial(speed_t baud, std::string port, bool canon)
{
// Make a copy of the current configuration so it can be
// restored in destructor.
isCanonical = canon;
if (setBaud(baud) == 0) BAUDRATE = baud; // baudrate must be multiple of 2400
isOpen = false;
struct stat stat_buf; // See if specified port exists
if (stat(port.c_str(), &stat_buf) == 0) PORT = port;
else { // Port doesn't exist
std::cout << "Device not found." << std::endl;
exit(-1);
}
// open port for read and write, not controlling, ignore DCD line
dev_fd = open(PORT.c_str(), O_RDWR | O_NOCTTY);
if (dev_fd < 0) {
perror("In function: Serial()\n Failed to open device: ");
exit(-1);
}
else isOpen = true;
init();
}
// Open and configure the port
void Serial::init()
{
tcgetattr(dev_fd, &oldConfig);
// memset(&terminalConfiguration, 0, sizeof(terminalConfiguration)); // Clear junk from location of terminalConfiguration to start with clean slate
tcgetattr(dev_fd, &terminalConfiguration);
// TERMIOS CONFIGURATION
// BAUDRATE: Integer multiple of 2400
// CRTSCTS: Hardware flow control
// CS8: 8N1
// CLOCAL: No modem control. (local device)
// CREAD: Receive chars
terminalConfiguration.c_cflag |= (BAUDRATE | CS8 | CLOCAL | CREAD);
// IGNPAR: Ignore parity errors
terminalConfiguration.c_iflag |= IGNPAR;
// 0 for raw output
terminalConfiguration.c_oflag = 0;
// Setting input mode
if (isCanonical) terminalConfiguration.c_lflag |= (ICANON | ECHO | ECHOE); // Canonical input
else {
//Configure non-canonical mode
terminalConfiguration.c_lflag &= ~(ICANON | ECHO | ECHOE); // Disable canonical mode and echo
terminalConfiguration.c_cc[VMIN] = 1; // Minimum number of chars to read before returning
terminalConfiguration.c_cc[VTIME] = 0; // Timeout in deciseconds. 0 to disregard timing between bytes
}
tcflush(dev_fd, TCIFLUSH);
applyNewConfig();
}
int Serial::setBaud(speed_t baud)
{
int status_i = -1;
int status_o = -1;
switch (baud) {
case 2400:
status_i = cfsetispeed(&terminalConfiguration, B2400);
status_o = cfsetospeed(&terminalConfiguration, B2400);
break;
case 4800:
status_i = cfsetispeed(&terminalConfiguration, B4800);
status_o = cfsetospeed(&terminalConfiguration, B4800);
break;
case 9600:
status_i = cfsetispeed(&terminalConfiguration, B9600);
status_o = cfsetospeed(&terminalConfiguration, B9600);
break;
case 19200:
status_i = cfsetispeed(&terminalConfiguration, B19200);
status_o = cfsetospeed(&terminalConfiguration, B19200);
break;
case 38400:
status_i = cfsetispeed(&terminalConfiguration, B38400);
status_o = cfsetospeed(&terminalConfiguration, B38400);
break;
case 57600:
status_i = cfsetispeed(&terminalConfiguration, B57600);
status_o = cfsetospeed(&terminalConfiguration, B57600);
break;
case 115200:
status_i = cfsetispeed(&terminalConfiguration, B115200);
status_o = cfsetospeed(&terminalConfiguration, B115200);
break;
case 230400:
status_i = cfsetispeed(&terminalConfiguration, B230400);
status_o = cfsetospeed(&terminalConfiguration, B230400);
break;
default:
std::cout << "Invalid baudrate requested.\n";
return -1;
}
if (status_i < 0 || status_o < 0) {
perror("In function: setBaud()\nFailed to set requested baudrate: ");
return -1;
}
else return status_i;
}
int Serial::applyNewConfig()
{
if (isOpen) {
if (tcsetattr(dev_fd, TCSANOW, &terminalConfiguration) < 0) perror("Could not apply configuration: ");
else return 0;
}
else return -1;
}
speed_t Serial::getBaud()
{
return cfgetispeed(&terminalConfiguration);
}
termios Serial::getConfig()
{
return terminalConfiguration;
}
// Helper function checks if port is open,
// then flushes the serial line.
int Serial::setupRead()
{
if (!isOpen) return -1;
if (tcflush(dev_fd, TCIOFLUSH < 0)) {
perror("Could not flush line: ");
return -1;
}
else return 0;
}
int Serial::serialRead()
{
if (setupRead() < 0) return -1;
int buf_size = 255; // 82 is longest NMEA Sentence
char buf[buf_size];
bytesReceived = read(dev_fd, buf, buf_size);
if (bytesReceived < 0) perror("In function serialRead()\nRead failed: ");
else buf[bytesReceived] = '\0'; // Null terminate the string
serialData.assign(buf); // store serialData as std::string
return bytesReceived;
}
int Serial::serialRead(int bytes)
{
if (setupRead() < 0) return -1;
int buf_size = bytes;
char buf[buf_size];
bytesReceived = read(dev_fd, buf, bytes);
if (bytesReceived < 0) perror("Read failed: ");
else buf[bytesReceived] = '\0'; // Null terminated
serialData.assign(buf); // Store as std::string
return bytesReceived;
}
int Serial::flush()
{
return tcflush(dev_fd, TCIOFLUSH);
}
int Serial::serialWrite(std::string str)
{
if (!isOpen) return -1;
int write_status = write(dev_fd, str.c_str(), str.length());
if (write_status < 0) {
perror("Failed to write to port: ");
return -1;
}
else return write_status;
}
std::string Serial::getData()
{
//if (isOpen) return serialData;
return "Open serial port first!\n";
}
Serial::~Serial()
{
tcsetattr(dev_fd, TCSANOW, &oldConfig); /* Leave port how we found it. */
close(dev_fd); /* close the port */
}<|endoftext|>
|
<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 15 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendFile()) cout << "GET Testfile complete." << endl;
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
cout << "In loadWindow's secret base, index is: " << i-base << endl;
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
}
/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
}
/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
fd_set stReadFDS;
struct timeval stTimeOut;
FD_ZERO(&stReadFDS);
stTimeOut.tv_sec = 0;
stTimeOut.tv_usec = 1000 * TIMEOUT;
FD_SET(s, &stReadFDS);
base = 0;
int desc_ready;
int finale = -1;
int max_sd;
bool hasRead = false;
while(base * BUFSIZE < length) {
loadWindow();
if(p.str()[0] == '\0') finale = p.getSequenceNum();
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
while(finale < 15) {
cout << endl << "beginning of loop " << finale << endl;
FD_ZERO(&stReadFDS);
stTimeOut.tv_sec = 0;
stTimeOut.tv_usec = 1000 * TIMEOUT;
FD_SET(s, &stReadFDS);
max_sd = s;
cout << endl << "before select" << endl;
int t = select(max_sd + 1, &stReadFDS, NULL, NULL, &stTimeOut);
cout << "after select" << endl;
if (t == -1){
perror("select()");
}
if (t == 0) {
cout << "=== ACK TIMEOUT (select)" << endl;
}
desc_ready = t;
for(int u = 0; u <= max_sd && desc_ready > 0; u++){
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT (recvfrom)" << endl;
} else hasRead = true;
if(!hasRead) continue;
if(isAck()) {
cout << "if isAck()" << endl;
handleAck();
finale++;
cout << "Finale is: " << finale << endl;
} else {
cout << "Not an ACK!" << endl;
}
}
cout << "end of loop " << finale << endl;
/*if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;}
memset(b, 0, BUFSIZE);
}*/
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '\0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<commit_msg>attempt to end the loop<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 15 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendFile()) cout << "GET Testfile complete." << endl;
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
cout << "In loadWindow's secret base, index is: " << i-base << endl;
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
}
/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
}
/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
fd_set stReadFDS;
struct timeval stTimeOut;
FD_ZERO(&stReadFDS);
stTimeOut.tv_sec = 0;
stTimeOut.tv_usec = 1000 * TIMEOUT;
FD_SET(s, &stReadFDS);
base = 0;
int desc_ready;
int finale = -1;
int max_sd;
bool hasRead = false;
while(base * BUFSIZE < length) {
loadWindow();
if(p.str()[0] == '\0') finale = p.getSequenceNum();
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
while(finale < 14) {
cout << endl << "beginning of loop " << finale << endl;
FD_ZERO(&stReadFDS);
stTimeOut.tv_sec = 0;
stTimeOut.tv_usec = 1000 * TIMEOUT;
FD_SET(s, &stReadFDS);
max_sd = s;
cout << endl << "before select" << endl;
int t = select(max_sd + 1, &stReadFDS, NULL, NULL, &stTimeOut);
cout << "after select" << endl;
if (t == -1){
perror("select()");
}
if (t == 0) {
cout << "=== ACK TIMEOUT (select)" << endl;
}
desc_ready = t;
for(int u = 0; u <= max_sd && desc_ready > 0; u++){
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT (recvfrom)" << endl;
} else hasRead = true;
if(!hasRead) continue;
if(isAck()) {
cout << "if isAck()" << endl;
handleAck();
finale++;
cout << "Finale is: " << finale << endl;
} else {
cout << "Not an ACK!" << endl;
}
}
cout << "end of loop " << finale << endl;
/*if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;}
memset(b, 0, BUFSIZE);
}*/
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '\0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<|endoftext|>
|
<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') {
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
return;
}
cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;
}
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
base = 0;
while(base * BUFSIZE < length) {
loadWindow();
cout << "packet " << base + 1 << ": " << window[1].str() << endl;
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
if(p.str()[0] == '\0') break;
for(int x = 0; x < WIN_SIZE; x++) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
memset(b, 0, BUFSIZE);
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<commit_msg>WHAT IS GOING ON<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 100 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE - 1 && window[i-base].getDataBuffer()[0] != 'G') {
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
return;
}
cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;
}
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
base = 0;
while(base * BUFSIZE < length) {
loadWindow();
cout << "packet " << base + 1 << ": " << window[1].str() << endl;
cout << "packet " << base + 2 << ": " << window[2].str() << endl;
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
if(p.str()[0] == '\0') break;
for(int x = 0; x < WIN_SIZE; x++) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
x--;
continue;
}
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
memset(b, 0, BUFSIZE);
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<|endoftext|>
|
<commit_before>/* ----------------------------------------------------------------------- *//**
*
* @file dbconnector.hpp
*
* @brief This file should be included by user code (and nothing else)
*
*//* ----------------------------------------------------------------------- */
#ifndef MADLIB_POSTGRES_DBCONNECTOR_HPP
#define MADLIB_POSTGRES_DBCONNECTOR_HPP
// On platforms based on PostgreSQL we can include a different set of headers.
// Also, there may be different compatibility headers for other platforms.
#ifndef MADLIB_POSTGRES_HEADERS
#define MADLIB_POSTGRES_HEADERS
// A recent change in the postgres port.h file plays some havoc with /usr/include/stdlib.h
// (commit https://github.com/postgres/postgres/commit/a919937f112eb2f548d5f9bd1b3a7298375e6380)
// Since we don't need anything from ports.h we can cheat and say its already been declared.
// Warning: This could cause problems in the future...
#define PG_PORT_H
extern "C" {
#include <postgres.h>
#include <pg_config.h> // Use the macro defined in the header to detect the platform
#include <funcapi.h>
#include <catalog/pg_proc.h>
#include <catalog/pg_type.h>
#include <executor/executor.h> // For GetAttributeByNum()
#include <miscadmin.h> // Memory allocation, e.g., HOLD_INTERRUPTS
#include <utils/acl.h>
#include <utils/array.h>
#include <utils/builtins.h> // needed for format_procedure()
#include <utils/datum.h>
#include <utils/lsyscache.h> // for type lookup, e.g., type_is_rowtype
#include <utils/memutils.h>
#include <utils/syscache.h> // for direct access to catalog, e.g., SearchSysCache()
#include <utils/typcache.h> // type conversion, e.g., lookup_rowtype_tupdesc
#include "../../../../methods/svec/src/pg_gp/sparse_vector.h" // Legacy sparse vectors
} // extern "C"
#include "Compatibility.hpp"
#endif // !defined(MADLIB_POSTGRES_HEADERS)
// Unfortunately, we have to clean up some #defines in PostgreSQL headers. They
// interfere with C++ code.
// From c.h:
#ifdef Abs
#undef Abs
#endif
#ifdef Max
#undef Max
#endif
#ifdef Min
#undef Min
#endif
#ifdef gettext
#undef gettext
#endif
#ifdef dgettext
#undef dgettext
#endif
#ifdef ngettext
#undef ngettext
#endif
#ifdef dngettext
#undef dngettext
#endif
// Note: If errors occur in the following include files, it could indicate that
// new macros have been added to PostgreSQL header files.
#include <boost/mpl/if.hpp>
#include <boost/any.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/tr1/array.hpp>
#include <boost/tr1/functional.hpp>
#include <boost/tr1/tuple.hpp>
#include <algorithm>
#include <complex>
#include <limits>
#include <stdexcept>
#include <vector>
#include <fstream>
#include <dbal/dbal_proto.hpp>
#include <utils/Reference.hpp>
#include <utils/Math.hpp>
namespace std {
// Import names from TR1.
// The following are currently provided by boost.
using tr1::array;
using tr1::bind;
using tr1::function;
using tr1::get;
using tr1::make_tuple;
using tr1::tie;
using tr1::tuple;
}
#if !defined(NDEBUG) && !defined(EIGEN_NO_DEBUG)
#define eigen_assert(x) \
do { \
if(!Eigen::internal::copy_bool(x)) \
throw std::runtime_error(std::string( \
"Internal error. Eigen assertion failed (" \
EIGEN_MAKESTRING(x) ") in function ") + __PRETTY_FUNCTION__ + \
" at " __FILE__ ":" EIGEN_MAKESTRING(__LINE__)); \
} while(false)
#endif // !defined(NDEBUG) && !defined(EIGEN_NO_DEBUG)
// We need to make _oldContext volatile because if an exception occurs, the
// register holding its value might have been overwritten (and the variable
// value is read from in the PG_CATCH block). On the other hand, no need to make
// _errorData volatile: If no PG exception occurs, no register will be
// overwritten. If an exception occurs, _errorData will be set before it is read
// again.
#define MADLIB_PG_TRY \
do { \
volatile MemoryContext _oldContext \
= CurrentMemoryContext; \
ErrorData* _errorData = NULL; \
PG_TRY();
// CopyErrorData() copies into the current memory context, so we
// need to switch away from the error context first
#define MADLIB_PG_CATCH \
PG_CATCH(); { \
MemoryContextSwitchTo(_oldContext); \
_errorData = CopyErrorData(); \
FlushErrorState(); \
} PG_END_TRY(); \
if (_errorData)
#define MADLIB_PG_END_TRY \
} while(false)
#define MADLIB_PG_RE_THROW \
throw PGException(_errorData)
#define MADLIB_PG_ERROR_DATA() \
_errorData
#define MADLIB_PG_DEFAULT_CATCH_AND_END_TRY \
MADLIB_PG_CATCH { \
MADLIB_PG_RE_THROW; \
} MADLIB_PG_END_TRY
#define MADLIB_WRAP_PG_FUNC(_returntype, _pgfunc, _arglist, _passedlist) \
inline \
_returntype \
madlib ## _ ## _pgfunc _arglist { \
_returntype _result = static_cast<_returntype>(0); \
MADLIB_PG_TRY { \
_result = _pgfunc _passedlist; \
} MADLIB_PG_DEFAULT_CATCH_AND_END_TRY; \
return _result; \
}
#define MADLIB_WRAP_VOID_PG_FUNC(_pgfunc, _arglist, _passedlist) \
inline \
void \
madlib ## _ ## _pgfunc _arglist { \
MADLIB_PG_TRY { \
_pgfunc _passedlist; \
} MADLIB_PG_DEFAULT_CATCH_AND_END_TRY; \
}
/**
* The maximum number of arguments that can be passed to a function via a
* FunctionHandle.
* Note that PostgreSQL defines FUNC_MAX_ARGS, which we could use here. However,
* this can be a fairly large number that might exceed BOOST_PP_LIMIT_REPEAT.
* In fmgr.h, PostgreSQL provides support functions (FunctionCall*Coll) for only
* up to 9 arguments.
*/
#define MADLIB_FUNC_MAX_ARGS 9
/**
* The maximum number of dimensions in an array
*/
#define MADLIB_MAX_ARRAY_DIMS 2
#include "Allocator_proto.hpp"
#include "ArrayHandle_proto.hpp"
#include "ArrayWithNullException_proto.hpp"
#include "AnyType_proto.hpp"
#include "ByteString_proto.hpp"
#include "NativeRandomNumberGenerator_proto.hpp"
#include "PGException_proto.hpp"
#include "OutputStreamBuffer_proto.hpp"
#include "SystemInformation_proto.hpp"
#include "TransparentHandle_proto.hpp"
#include "TypeTraits_proto.hpp"
#include "UDF_proto.hpp"
// Need to move FunctionHandle down because it has dependencies
#include "FunctionHandle_proto.hpp"
// Several backend functions (APIs) need a wrapper, so that they can be called
// safely from a C++ context.
#include "Backend.hpp"
namespace madlib {
// Import MADlib types into madlib namespace
using dbconnector::postgres::Allocator;
using dbconnector::postgres::AnyType;
using dbconnector::postgres::ArrayHandle;
using dbconnector::postgres::ByteString;
using dbconnector::postgres::FunctionHandle;
using dbconnector::postgres::MutableArrayHandle;
using dbconnector::postgres::MutableByteString;
using dbconnector::postgres::NativeRandomNumberGenerator;
using dbconnector::postgres::TransparentHandle;
// Import MADlib functions into madlib namespace
using dbconnector::postgres::AnyType_cast;
using dbconnector::postgres::defaultAllocator;
using dbconnector::postgres::funcPtr;
using dbconnector::postgres::Null;
// Import MADlib exceptions into madlib namespace
using dbconnector::postgres::ArrayWithNullException;
namespace dbconnector {
namespace postgres {
#ifndef NDEBUG
extern std::ostream dbout;
extern std::ostream dberr;
#endif
} // namespace postgres
} // namespace dbconnector
#ifndef NDEBUG
// Import MADlib global variables into madlib namespace
using dbconnector::postgres::dbout;
using dbconnector::postgres::dberr;
#endif
// A wrapper function added as a workaround to fix MADLIB-769
// To support grouping, we cannot throw an exception because
// it will exit the process. Instead, we print a message and
// set an internal status in the state variable in the C++ code.
inline void warning(std::string msg){
elog(WARNING, "%s", msg.c_str());
}
} // namespace madlib
#include <dbal/dbal_impl.hpp>
// FIXME: The following include should be further up. Currently dependent on
// dbal_impl.hpp which depends on the memory allocator.
#include "EigenIntegration_proto.hpp"
#include "Allocator_impl.hpp"
#include "AnyType_impl.hpp"
#include "ArrayHandle_impl.hpp"
#include "ByteString_impl.hpp"
#include "EigenIntegration_impl.hpp"
#include "FunctionHandle_impl.hpp"
#include "NativeRandomNumberGenerator_impl.hpp"
#include "OutputStreamBuffer_impl.hpp"
#include "TransparentHandle_impl.hpp"
#include "TypeTraits_impl.hpp"
#include "UDF_impl.hpp"
#include "SystemInformation_impl.hpp"
namespace madlib {
typedef dbal::DynamicStructRootContainer<
ByteString, dbconnector::postgres::TypeTraits> RootContainer;
typedef dbal::DynamicStructRootContainer<
MutableByteString, dbconnector::postgres::TypeTraits> MutableRootContainer;
} // namespace madlib
#define DECLARE_UDF(_module, _name) \
namespace madlib { \
namespace modules { \
namespace _module { \
struct _name : public dbconnector::postgres::UDF { \
inline _name() { } \
AnyType run(AnyType &args); \
inline void *SRF_init(AnyType&) {return NULL;}; \
inline AnyType SRF_next(void *, bool *){return AnyType();}; \
}; \
} \
} \
}
#define DECLARE_SR_UDF(_module, _name) \
namespace madlib { \
namespace modules { \
namespace _module { \
struct _name : public dbconnector::postgres::UDF { \
inline _name() { } \
inline AnyType run(AnyType &){return AnyType();}; \
void *SRF_init(AnyType &args); \
AnyType SRF_next(void *user_fctx, bool *is_last_call); \
}; \
} \
} \
}
#define DECLARE_UDF_EXTERNAL(_module, _name) \
namespace external { \
extern "C" { \
PG_FUNCTION_INFO_V1(_name); \
Datum _name(PG_FUNCTION_ARGS) { \
return madlib::dbconnector::postgres::UDF::call< \
madlib::modules::_module::_name>(fcinfo); \
} \
} \
}
#endif // defined(MADLIB_POSTGRES_DBCONNECTOR_HPP)
<commit_msg>update for pipelinedb<commit_after>/* ----------------------------------------------------------------------- *//**
*
* @file dbconnector.hpp
*
* @brief This file should be included by user code (and nothing else)
*
*//* ----------------------------------------------------------------------- */
#ifndef MADLIB_POSTGRES_DBCONNECTOR_HPP
#define MADLIB_POSTGRES_DBCONNECTOR_HPP
// On platforms based on PostgreSQL we can include a different set of headers.
// Also, there may be different compatibility headers for other platforms.
#ifndef MADLIB_POSTGRES_HEADERS
#define MADLIB_POSTGRES_HEADERS
// A recent change in the postgres port.h file plays some havoc with /usr/include/stdlib.h
// (commit https://github.com/postgres/postgres/commit/a919937f112eb2f548d5f9bd1b3a7298375e6380)
// Since we don't need anything from ports.h we can cheat and say its already been declared.
// Warning: This could cause problems in the future...
//#define PG_PORT_H
#define PIPELINE_QUERY_FN_H
extern "C" {
#include <postgres.h>
#include <pg_config.h> // Use the macro defined in the header to detect the platform
#include <funcapi.h>
#include <catalog/pg_proc.h>
#include <catalog/pg_type.h>
#include <executor/executor.h> // For GetAttributeByNum()
#include <miscadmin.h> // Memory allocation, e.g., HOLD_INTERRUPTS
#include <utils/acl.h>
#include <utils/array.h>
#include <utils/builtins.h> // needed for format_procedure()
#include <utils/datum.h>
#include <utils/lsyscache.h> // for type lookup, e.g., type_is_rowtype
#include <utils/memutils.h>
#include <utils/syscache.h> // for direct access to catalog, e.g., SearchSysCache()
#include <utils/typcache.h> // type conversion, e.g., lookup_rowtype_tupdesc
#include "../../../../methods/svec/src/pg_gp/sparse_vector.h" // Legacy sparse vectors
} // extern "C"
#include "Compatibility.hpp"
#endif // !defined(MADLIB_POSTGRES_HEADERS)
// Unfortunately, we have to clean up some #defines in PostgreSQL headers. They
// interfere with C++ code.
// From c.h:
#ifdef Abs
#undef Abs
#endif
#ifdef Max
#undef Max
#endif
#ifdef Min
#undef Min
#endif
#ifdef gettext
#undef gettext
#endif
#ifdef dgettext
#undef dgettext
#endif
#ifdef ngettext
#undef ngettext
#endif
#ifdef dngettext
#undef dngettext
#endif
// Note: If errors occur in the following include files, it could indicate that
// new macros have been added to PostgreSQL header files.
#include <boost/mpl/if.hpp>
#include <boost/any.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/remove_cv.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/tr1/array.hpp>
#include <boost/tr1/functional.hpp>
#include <boost/tr1/tuple.hpp>
#include <algorithm>
#include <complex>
#include <limits>
#include <stdexcept>
#include <vector>
#include <fstream>
#include <dbal/dbal_proto.hpp>
#include <utils/Reference.hpp>
#include <utils/Math.hpp>
namespace std {
// Import names from TR1.
// The following are currently provided by boost.
using tr1::array;
using tr1::bind;
using tr1::function;
using tr1::get;
using tr1::make_tuple;
using tr1::tie;
using tr1::tuple;
}
#if !defined(NDEBUG) && !defined(EIGEN_NO_DEBUG)
#define eigen_assert(x) \
do { \
if(!Eigen::internal::copy_bool(x)) \
throw std::runtime_error(std::string( \
"Internal error. Eigen assertion failed (" \
EIGEN_MAKESTRING(x) ") in function ") + __PRETTY_FUNCTION__ + \
" at " __FILE__ ":" EIGEN_MAKESTRING(__LINE__)); \
} while(false)
#endif // !defined(NDEBUG) && !defined(EIGEN_NO_DEBUG)
// We need to make _oldContext volatile because if an exception occurs, the
// register holding its value might have been overwritten (and the variable
// value is read from in the PG_CATCH block). On the other hand, no need to make
// _errorData volatile: If no PG exception occurs, no register will be
// overwritten. If an exception occurs, _errorData will be set before it is read
// again.
#define MADLIB_PG_TRY \
do { \
volatile MemoryContext _oldContext \
= CurrentMemoryContext; \
ErrorData* _errorData = NULL; \
PG_TRY();
// CopyErrorData() copies into the current memory context, so we
// need to switch away from the error context first
#define MADLIB_PG_CATCH \
PG_CATCH(); { \
MemoryContextSwitchTo(_oldContext); \
_errorData = CopyErrorData(); \
FlushErrorState(); \
} PG_END_TRY(); \
if (_errorData)
#define MADLIB_PG_END_TRY \
} while(false)
#define MADLIB_PG_RE_THROW \
throw PGException(_errorData)
#define MADLIB_PG_ERROR_DATA() \
_errorData
#define MADLIB_PG_DEFAULT_CATCH_AND_END_TRY \
MADLIB_PG_CATCH { \
MADLIB_PG_RE_THROW; \
} MADLIB_PG_END_TRY
#define MADLIB_WRAP_PG_FUNC(_returntype, _pgfunc, _arglist, _passedlist) \
inline \
_returntype \
madlib ## _ ## _pgfunc _arglist { \
_returntype _result = static_cast<_returntype>(0); \
MADLIB_PG_TRY { \
_result = _pgfunc _passedlist; \
} MADLIB_PG_DEFAULT_CATCH_AND_END_TRY; \
return _result; \
}
#define MADLIB_WRAP_VOID_PG_FUNC(_pgfunc, _arglist, _passedlist) \
inline \
void \
madlib ## _ ## _pgfunc _arglist { \
MADLIB_PG_TRY { \
_pgfunc _passedlist; \
} MADLIB_PG_DEFAULT_CATCH_AND_END_TRY; \
}
/**
* The maximum number of arguments that can be passed to a function via a
* FunctionHandle.
* Note that PostgreSQL defines FUNC_MAX_ARGS, which we could use here. However,
* this can be a fairly large number that might exceed BOOST_PP_LIMIT_REPEAT.
* In fmgr.h, PostgreSQL provides support functions (FunctionCall*Coll) for only
* up to 9 arguments.
*/
#define MADLIB_FUNC_MAX_ARGS 9
/**
* The maximum number of dimensions in an array
*/
#define MADLIB_MAX_ARRAY_DIMS 2
#include "Allocator_proto.hpp"
#include "ArrayHandle_proto.hpp"
#include "ArrayWithNullException_proto.hpp"
#include "AnyType_proto.hpp"
#include "ByteString_proto.hpp"
#include "NativeRandomNumberGenerator_proto.hpp"
#include "PGException_proto.hpp"
#include "OutputStreamBuffer_proto.hpp"
#include "SystemInformation_proto.hpp"
#include "TransparentHandle_proto.hpp"
#include "TypeTraits_proto.hpp"
#include "UDF_proto.hpp"
// Need to move FunctionHandle down because it has dependencies
#include "FunctionHandle_proto.hpp"
// Several backend functions (APIs) need a wrapper, so that they can be called
// safely from a C++ context.
#include "Backend.hpp"
namespace madlib {
// Import MADlib types into madlib namespace
using dbconnector::postgres::Allocator;
using dbconnector::postgres::AnyType;
using dbconnector::postgres::ArrayHandle;
using dbconnector::postgres::ByteString;
using dbconnector::postgres::FunctionHandle;
using dbconnector::postgres::MutableArrayHandle;
using dbconnector::postgres::MutableByteString;
using dbconnector::postgres::NativeRandomNumberGenerator;
using dbconnector::postgres::TransparentHandle;
// Import MADlib functions into madlib namespace
using dbconnector::postgres::AnyType_cast;
using dbconnector::postgres::defaultAllocator;
using dbconnector::postgres::funcPtr;
using dbconnector::postgres::Null;
// Import MADlib exceptions into madlib namespace
using dbconnector::postgres::ArrayWithNullException;
namespace dbconnector {
namespace postgres {
#ifndef NDEBUG
extern std::ostream dbout;
extern std::ostream dberr;
#endif
} // namespace postgres
} // namespace dbconnector
#ifndef NDEBUG
// Import MADlib global variables into madlib namespace
using dbconnector::postgres::dbout;
using dbconnector::postgres::dberr;
#endif
// A wrapper function added as a workaround to fix MADLIB-769
// To support grouping, we cannot throw an exception because
// it will exit the process. Instead, we print a message and
// set an internal status in the state variable in the C++ code.
inline void warning(std::string msg){
elog(WARNING, "%s", msg.c_str());
}
} // namespace madlib
#include <dbal/dbal_impl.hpp>
// FIXME: The following include should be further up. Currently dependent on
// dbal_impl.hpp which depends on the memory allocator.
#include "EigenIntegration_proto.hpp"
#include "Allocator_impl.hpp"
#include "AnyType_impl.hpp"
#include "ArrayHandle_impl.hpp"
#include "ByteString_impl.hpp"
#include "EigenIntegration_impl.hpp"
#include "FunctionHandle_impl.hpp"
#include "NativeRandomNumberGenerator_impl.hpp"
#include "OutputStreamBuffer_impl.hpp"
#include "TransparentHandle_impl.hpp"
#include "TypeTraits_impl.hpp"
#include "UDF_impl.hpp"
#include "SystemInformation_impl.hpp"
namespace madlib {
typedef dbal::DynamicStructRootContainer<
ByteString, dbconnector::postgres::TypeTraits> RootContainer;
typedef dbal::DynamicStructRootContainer<
MutableByteString, dbconnector::postgres::TypeTraits> MutableRootContainer;
} // namespace madlib
#define DECLARE_UDF(_module, _name) \
namespace madlib { \
namespace modules { \
namespace _module { \
struct _name : public dbconnector::postgres::UDF { \
inline _name() { } \
AnyType run(AnyType &args); \
inline void *SRF_init(AnyType&) {return NULL;}; \
inline AnyType SRF_next(void *, bool *){return AnyType();}; \
}; \
} \
} \
}
#define DECLARE_SR_UDF(_module, _name) \
namespace madlib { \
namespace modules { \
namespace _module { \
struct _name : public dbconnector::postgres::UDF { \
inline _name() { } \
inline AnyType run(AnyType &){return AnyType();}; \
void *SRF_init(AnyType &args); \
AnyType SRF_next(void *user_fctx, bool *is_last_call); \
}; \
} \
} \
}
#define DECLARE_UDF_EXTERNAL(_module, _name) \
namespace external { \
extern "C" { \
PG_FUNCTION_INFO_V1(_name); \
Datum _name(PG_FUNCTION_ARGS) { \
return madlib::dbconnector::postgres::UDF::call< \
madlib::modules::_module::_name>(fcinfo); \
} \
} \
}
#endif // defined(MADLIB_POSTGRES_DBCONNECTOR_HPP)
<|endoftext|>
|
<commit_before>#ifndef BONEFISH_WAMP_TRACE_HPP
#define BONEFISH_WAMP_TRACE_HPP
#include <boost/format.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/variadic/size.hpp>
#include <iostream>
#include <string.h>
namespace bonefish {
namespace trace {
extern bool _enabled;
inline bool is_enabled()
{
return _enabled;
}
inline void set_enabled(bool is_enabled)
{
_enabled = is_enabled;
}
inline const char* base_file_name(const char* file_path)
{
const char* file_name = strrchr(file_path, '/');
return file_name == nullptr ? file_path : file_name + 1;
}
} // namespace trace
} // namespace bonefish
// Macro for facilitating debug trace logging.
#define BONEFISH_TRACE(fmt, ...) \
BOOST_PP_IF(BOOST_PP_SUB(BOOST_PP_VARIADIC_SIZE("dummy", ##__VA_ARGS__), 1), BONFISH_TRACE_ARGS(fmt, __VA_ARGS__), BONFISH_TRACE_NOARGS(fmt, __VA_ARGS__))
#define BONFISH_TRACE_NOARGS(fmt, ...) \
std::cerr << "[" << bonefish::trace::base_file_name(__FILE__) << ":" << __LINE__ << "][" << __FUNCTION__ << "] " \
<< boost::format(fmt) << std::endl;
#define BONFISH_TRACE_ARGS(fmt, ...) \
std::cerr << "[" << bonefish::trace::base_file_name(__FILE__) << ":" << __LINE__ << "][" << __FUNCTION__ << "] " \
<< (boost::format(fmt) % __VA_ARGS__) << std::endl;
#endif // BONEFISH_WAMP_TRACE_HPP
<commit_msg>[trace] Only trace if it is enabled<commit_after>#ifndef BONEFISH_WAMP_TRACE_HPP
#define BONEFISH_WAMP_TRACE_HPP
#include <boost/format.hpp>
#include <boost/preprocessor/arithmetic/sub.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/variadic/size.hpp>
#include <iostream>
#include <string.h>
namespace bonefish {
namespace trace {
extern bool _enabled;
inline bool is_enabled()
{
return _enabled;
}
inline void set_enabled(bool is_enabled)
{
_enabled = is_enabled;
}
inline const char* base_file_name(const char* file_path)
{
const char* file_name = strrchr(file_path, '/');
return file_name == nullptr ? file_path : file_name + 1;
}
} // namespace trace
} // namespace bonefish
// Macro for facilitating debug trace logging.
#define BONEFISH_TRACE(fmt, ...) \
BOOST_PP_IF(BOOST_PP_SUB(BOOST_PP_VARIADIC_SIZE("dummy", ##__VA_ARGS__), 1), BONFISH_TRACE_ARGS(fmt, __VA_ARGS__), BONFISH_TRACE_NOARGS(fmt, __VA_ARGS__))
#define BONFISH_TRACE_NOARGS(fmt, ...) \
if (bonefish::trace::is_enabled()) { \
std::cerr << "[" << bonefish::trace::base_file_name(__FILE__) << ":" << __LINE__ << "][" << __FUNCTION__ << "] " \
<< boost::format(fmt) << std::endl; \
}
#define BONFISH_TRACE_ARGS(fmt, ...) \
if (bonefish::trace::is_enabled()) { \
std::cerr << "[" << bonefish::trace::base_file_name(__FILE__) << ":" << __LINE__ << "][" << __FUNCTION__ << "] " \
<< (boost::format(fmt) % __VA_ARGS__) << std::endl; \
}
#endif // BONEFISH_WAMP_TRACE_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MasterScriptProvider.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:29:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
#define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
#include <rtl/ustring>
#include <cppuhelper/implbase5.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>
#include <com/sun/star/script/browse/XBrowseNode.hpp>
#include "ProviderCache.hxx"
namespace func_provider
{
// for simplification
#define css ::com::sun::star
typedef ::cppu::WeakImplHelper5<
css::script::provider::XScriptProvider,
css::script::browse::XBrowseNode, css::lang::XServiceInfo,
css::lang::XInitialization,
css::container::XNameContainer > t_helper;
class MasterScriptProvider :
public t_helper
{
public:
MasterScriptProvider(
const css::uno::Reference< css::uno::XComponentContext >
& xContext ) throw( css::uno::RuntimeException );
~MasterScriptProvider();
// XServiceInfo implementation
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw( css::uno::RuntimeException );
// XBrowseNode implementation
virtual ::rtl::OUString SAL_CALL getName()
throw ( css::uno::RuntimeException );
virtual css::uno::Sequence< css::uno::Reference< css::script::browse::XBrowseNode > > SAL_CALL getChildNodes()
throw ( css::uno::RuntimeException );
virtual sal_Bool SAL_CALL hasChildNodes()
throw ( css::uno::RuntimeException );
virtual sal_Int16 SAL_CALL getType()
throw ( css::uno::RuntimeException );
// XNameContainer
virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, css::uno::RuntimeException);
virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
// XNameReplace
virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
// XNameAccess
virtual css::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw ( css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);
// XElementAccess
virtual css::uno::Type SAL_CALL getElementType( ) throw ( css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements( ) throw ( css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw( css::uno::RuntimeException );
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
throw( css::uno::RuntimeException );
// XScriptProvider implementation
virtual css::uno::Reference < css::script::provider::XScript > SAL_CALL
getScript( const ::rtl::OUString& scriptURI )
throw( css::script::provider::ScriptFrameworkErrorException,
css::uno::RuntimeException );
/**
* XInitialise implementation
*
* @param args expected to contain a single ::rtl::OUString
* containing the URI
*/
virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args )
throw ( css::uno::Exception, css::uno::RuntimeException);
// Public method to return all Language Providers in this MasterScriptProviders
// context.
css::uno::Sequence< css::uno::Reference< css::script::provider::XScriptProvider > > SAL_CALL
getAllProviders() throw ( css::uno::RuntimeException );
bool isPkgProvider() { return m_bIsPkgMSP; }
css::uno::Reference< css::script::provider::XScriptProvider > getPkgProvider() { return m_xMSPPkg; }
// returns context string for this provider, eg
::rtl::OUString getContextString() { return m_sCtxString; }
css::uno::Reference< css::frame::XModel > getModel() { return m_xModel; }
private:
::rtl::OUString parseLocationName( const ::rtl::OUString& location );
void createPkgProvider();
bool isValid();
::rtl::OUString getURLForModel();
const css::uno::Sequence< ::rtl::OUString >& getProviderNames();
ProviderCache* providerCache();
/* to obtain other services if needed */
css::uno::Reference< css::uno::XComponentContext > m_xContext;
css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
css::uno::Reference< css::frame::XModel > m_xModel;
css::uno::Sequence< css::uno::Any > m_sAargs;
::rtl::OUString m_sNodeName;
// This component supports XInitialization, it can be created
// using createInstanceXXX() or createInstanceWithArgumentsXXX using
// the service Mangager.
// Need to detect proper initialisation and validity
// for the object, so m_bIsValid indicates that the object is valid is set in ctor
// in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset
// and then set to true when initialisation is complete
bool m_bIsValid;
// m_bInitialised ensure initialisation only takes place once.
bool m_bInitialised;
bool m_bIsPkgMSP;
css::uno::Reference< css::script::provider::XScriptProvider > m_xMSPPkg;
ProviderCache* m_pPCache;
osl::Mutex m_mutex;
::rtl::OUString m_sCtxString;
};
} // namespace func_provider
#endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
<commit_msg>INTEGRATION: CWS warnings01 (1.12.14); FILE MERGED 2005/12/22 14:40:53 ab 1.12.14.1: #i53898# Removed warnings for unxlngi6, unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MasterScriptProvider.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2006-06-19 10:21:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
#define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
#include <rtl/ustring.hxx>
#include <cppuhelper/implbase5.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>
#include <com/sun/star/script/browse/XBrowseNode.hpp>
#include "ProviderCache.hxx"
namespace func_provider
{
// for simplification
#define css ::com::sun::star
typedef ::cppu::WeakImplHelper5<
css::script::provider::XScriptProvider,
css::script::browse::XBrowseNode, css::lang::XServiceInfo,
css::lang::XInitialization,
css::container::XNameContainer > t_helper;
class MasterScriptProvider :
public t_helper
{
public:
MasterScriptProvider(
const css::uno::Reference< css::uno::XComponentContext >
& xContext ) throw( css::uno::RuntimeException );
~MasterScriptProvider();
// XServiceInfo implementation
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw( css::uno::RuntimeException );
// XBrowseNode implementation
virtual ::rtl::OUString SAL_CALL getName()
throw ( css::uno::RuntimeException );
virtual css::uno::Sequence< css::uno::Reference< css::script::browse::XBrowseNode > > SAL_CALL getChildNodes()
throw ( css::uno::RuntimeException );
virtual sal_Bool SAL_CALL hasChildNodes()
throw ( css::uno::RuntimeException );
virtual sal_Int16 SAL_CALL getType()
throw ( css::uno::RuntimeException );
// XNameContainer
virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, css::uno::RuntimeException);
virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
// XNameReplace
virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
// XNameAccess
virtual css::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw ( css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);
// XElementAccess
virtual css::uno::Type SAL_CALL getElementType( ) throw ( css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasElements( ) throw ( css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw( css::uno::RuntimeException );
virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
throw( css::uno::RuntimeException );
// XScriptProvider implementation
virtual css::uno::Reference < css::script::provider::XScript > SAL_CALL
getScript( const ::rtl::OUString& scriptURI )
throw( css::script::provider::ScriptFrameworkErrorException,
css::uno::RuntimeException );
/**
* XInitialise implementation
*
* @param args expected to contain a single ::rtl::OUString
* containing the URI
*/
virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args )
throw ( css::uno::Exception, css::uno::RuntimeException);
// Public method to return all Language Providers in this MasterScriptProviders
// context.
css::uno::Sequence< css::uno::Reference< css::script::provider::XScriptProvider > > SAL_CALL
getAllProviders() throw ( css::uno::RuntimeException );
bool isPkgProvider() { return m_bIsPkgMSP; }
css::uno::Reference< css::script::provider::XScriptProvider > getPkgProvider() { return m_xMSPPkg; }
// returns context string for this provider, eg
::rtl::OUString getContextString() { return m_sCtxString; }
css::uno::Reference< css::frame::XModel > getModel() { return m_xModel; }
private:
::rtl::OUString parseLocationName( const ::rtl::OUString& location );
void createPkgProvider();
bool isValid();
::rtl::OUString getURLForModel();
const css::uno::Sequence< ::rtl::OUString >& getProviderNames();
ProviderCache* providerCache();
/* to obtain other services if needed */
css::uno::Reference< css::uno::XComponentContext > m_xContext;
css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
css::uno::Reference< css::frame::XModel > m_xModel;
css::uno::Sequence< css::uno::Any > m_sAargs;
::rtl::OUString m_sNodeName;
// This component supports XInitialization, it can be created
// using createInstanceXXX() or createInstanceWithArgumentsXXX using
// the service Mangager.
// Need to detect proper initialisation and validity
// for the object, so m_bIsValid indicates that the object is valid is set in ctor
// in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset
// and then set to true when initialisation is complete
bool m_bIsValid;
// m_bInitialised ensure initialisation only takes place once.
bool m_bInitialised;
bool m_bIsPkgMSP;
css::uno::Reference< css::script::provider::XScriptProvider > m_xMSPPkg;
ProviderCache* m_pPCache;
osl::Mutex m_mutex;
::rtl::OUString m_sCtxString;
};
} // namespace func_provider
#endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
<|endoftext|>
|
<commit_before>
#include "cocos-ext.h"
#include "HelloWorldScene.h"
#include "Render.h"
#include "FileInfo.h"
#include "TriggerCode/EventDef.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include "../cocos2dx/platform/android/jni/JniHelper.h"
#include <android/log.h>
#endif
using namespace cocos2d;
using namespace cocos2d::extension;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setScale(2.0);
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width,
origin.y + pCloseItem->getContentSize().height));
// create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
this->addChild(pMenu, 3);
std::string path = std::string(FileInfo::sharedFileInfo()->getSavePath());
if(path.empty())
{
CCLabelTTF *pLabel = CCLabelTTF::create("File Error! File unzip error or null",
"Arial",30);
CCSize size = CCDirector::sharedDirector()->getWinSize();
pLabel->setPosition(ccp(size.width/2, size.height/2));
addChild(pLabel);
}
else
{
//save file path
std::vector<std::string> searchPaths = CCFileUtils::sharedFileUtils()->getSearchPaths();
searchPaths.insert(searchPaths.begin(), path);
CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);
Render* scene = new Render(FileInfo::sharedFileInfo()->getFilename());
this->addChild(scene,2);
}
sendEvent(TRIGGEREVENT_INITSCENE);
this->schedule(schedule_selector(SceneEditorTestLayer::gameLogic));
this->setTouchEnabled(true);
this->setTouchMode(kCCTouchesOneByOne);
return true;
}
void SceneEditorTestLayer::onEnter()
{
CCLayer::onEnter();
sendEvent(TRIGGEREVENT_ENTERSCENE);
}
void SceneEditorTestLayer::onExit()
{
CCLayer::onExit();
sendEvent(TRIGGEREVENT_LEAVESCENE);
}
bool SceneEditorTestLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHBEGAN);
return true;
}
void SceneEditorTestLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHMOVED);
}
void SceneEditorTestLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHENDED);
}
void SceneEditorTestLayer::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHCANCELLED);
}
void SceneEditorTestLayer::gameLogic(float dt)
{
sendEvent(TRIGGEREVENT_UPDATESCENE);
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
CloseScene(true);
}
void CloseScene(bool autonomous)
{
if(autonomous)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#define LOG_TAG "JniHelper"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
JniMethodInfo minfo;
jobject jobj;
bool b = JniHelper::getStaticMethodInfo(minfo,
"cn/cocostudio/render/CocoRender",
"exitRenderScene",
"()V");
if (!b) {
LOGD("JniHelper::getStaticMethodInfo error...");
}else{
jobj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);
}
#endif
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
#endif
}
<commit_msg>fixed #3677 update trigger.<commit_after>
#include "cocos-ext.h"
#include "HelloWorldScene.h"
#include "Render.h"
#include "FileInfo.h"
#include "TriggerCode/EventDef.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include "../cocos2dx/platform/android/jni/JniHelper.h"
#include <android/log.h>
#endif
using namespace cocos2d;
using namespace cocos2d::extension;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setScale(2.0);
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width,
origin.y + pCloseItem->getContentSize().height));
// create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
this->addChild(pMenu, 3);
std::string path = std::string(FileInfo::sharedFileInfo()->getSavePath());
if(path.empty())
{
CCLabelTTF *pLabel = CCLabelTTF::create("File Error! File unzip error or null",
"Arial",30);
CCSize size = CCDirector::sharedDirector()->getWinSize();
pLabel->setPosition(ccp(size.width/2, size.height/2));
addChild(pLabel);
}
else
{
//save file path
std::vector<std::string> searchPaths = CCFileUtils::sharedFileUtils()->getSearchPaths();
searchPaths.insert(searchPaths.begin(), path);
CCFileUtils::sharedFileUtils()->setSearchPaths(searchPaths);
Render* scene = new Render(FileInfo::sharedFileInfo()->getFilename());
this->addChild(scene,2);
}
sendEvent(TRIGGEREVENT_INITSCENE);
this->schedule(schedule_selector(HelloWorld::gameLogic));
this->setTouchEnabled(true);
this->setTouchMode(kCCTouchesOneByOne);
return true;
}
void HelloWorld::onEnter()
{
CCLayer::onEnter();
sendEvent(TRIGGEREVENT_ENTERSCENE);
}
void HelloWorld::onExit()
{
CCLayer::onExit();
sendEvent(TRIGGEREVENT_LEAVESCENE);
}
bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHBEGAN);
return true;
}
void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHMOVED);
}
void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHENDED);
}
void HelloWorld::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
sendEvent(TRIGGEREVENT_TOUCHCANCELLED);
}
void HelloWorld::gameLogic(float dt)
{
sendEvent(TRIGGEREVENT_UPDATESCENE);
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
CloseScene(true);
}
void CloseScene(bool autonomous)
{
if(autonomous)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#define LOG_TAG "JniHelper"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
JniMethodInfo minfo;
jobject jobj;
bool b = JniHelper::getStaticMethodInfo(minfo,
"cn/cocostudio/render/CocoRender",
"exitRenderScene",
"()V");
if (!b) {
LOGD("JniHelper::getStaticMethodInfo error...");
}else{
jobj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);
}
#endif
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
#endif
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "CircleMaxOriginalElementSize.h"
#include "libmesh/parallel_algebra.h"
template<>
InputParameters validParams<CircleMaxOriginalElementSize>()
{
InputParameters params = validParams<ElementUserObject>();
params.addCoupledVar("periodic_variable", "Use perodic boundary conditions of this variable to determine the distance to the function peak location");
return params;
}
CircleMaxOriginalElementSize::CircleMaxOriginalElementSize(const InputParameters & parameters) :
ElementUserObject(parameters),
_periodic_var(isCoupled("periodic_variable") ? (int) coupled("periodic_variable") : -1),
_mesh(_fe_problem.mesh())
{
}
Real
CircleMaxOriginalElementSize::value(const Point & p, const Real & radius) const
{
// Loop over elements
for (std::map<dof_id_type, Point>::const_iterator it = _centroids.begin();
it != _centroids.end();
++it)
{
dof_id_type id = it->first;
Point centroid = it->second;
Real r = distance(p, centroid);
// check if distance between points is less than supplied radius
if (r < radius)
if (_original_element_sizes.find(id) == _original_element_sizes.end())
mooseError("In CircleMaxOriginalElementSize, element id " << id << " not found.");
else
return _original_element_sizes.at(id);
}
return 0.0;
}
void
CircleMaxOriginalElementSize::initialize()
{
// clear maps of values
_original_element_sizes.clear();
_centroids.clear();
}
void
CircleMaxOriginalElementSize::execute()
{
// Get pointer to original element of this (possibly) refined element
const Elem * original_element = _current_elem->top_parent();
// Store the parent element size value
_original_element_sizes[_current_elem->id()] = original_element->hmax();
// Store the parent element centroid
_centroids[_current_elem->id()] = original_element->centroid();
}
void
CircleMaxOriginalElementSize::threadJoin(const UserObject & y)
{
// We are joining with another class like this one so do a cast so we can get to it's data
const CircleMaxOriginalElementSize & uo = dynamic_cast<const CircleMaxOriginalElementSize &>(y);
_original_element_sizes.insert(uo._original_element_sizes.begin(), uo._original_element_sizes.end());
_centroids.insert(uo._centroids.begin(), uo._centroids.end());
}
void
CircleMaxOriginalElementSize::finalize()
{
_communicator.set_union(_original_element_sizes);
_communicator.set_union(_centroids);
}
Real
CircleMaxOriginalElementSize::distance(Point p1, Point p2) const
{
// distance between supplied point and element centroid depends on perodicity
if (_periodic_var < 0)
return (p1 - p2).norm();
return _mesh.minPeriodicDistance(_periodic_var, p1, p2);
}
<commit_msg>bug in CircleMaxOriginalElementSize, closes #31<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "CircleMaxOriginalElementSize.h"
#include "libmesh/parallel_algebra.h"
template<>
InputParameters validParams<CircleMaxOriginalElementSize>()
{
InputParameters params = validParams<ElementUserObject>();
params.addCoupledVar("periodic_variable", "Use perodic boundary conditions of this variable to determine the distance to the function peak location");
return params;
}
CircleMaxOriginalElementSize::CircleMaxOriginalElementSize(const InputParameters & parameters) :
ElementUserObject(parameters),
_periodic_var(isCoupled("periodic_variable") ? (int) coupled("periodic_variable") : -1),
_mesh(_fe_problem.mesh())
{
}
Real
CircleMaxOriginalElementSize::value(const Point & p, const Real & radius) const
{
Real max_element_size = 0.0;
// Loop over elements
for (std::map<dof_id_type, Point>::const_iterator it = _centroids.begin();
it != _centroids.end();
++it)
{
dof_id_type id = it->first;
Point centroid = it->second;
Real r = distance(p, centroid);
// check if distance between points is less than supplied radius
if (r < radius)
{
if (_original_element_sizes.find(id) == _original_element_sizes.end())
mooseError("In CircleMaxOriginalElementSize, element id " << id << " not found.");
else
{
Real element_size = _original_element_sizes.at(id);
if (element_size > max_element_size)
max_element_size = element_size;
}
}
}
return max_element_size;
}
void
CircleMaxOriginalElementSize::initialize()
{
// clear maps of values
_original_element_sizes.clear();
_centroids.clear();
}
void
CircleMaxOriginalElementSize::execute()
{
// Get pointer to original element of this (possibly) refined element
const Elem * original_element = _current_elem->top_parent();
// Store the parent element size value
_original_element_sizes[_current_elem->id()] = original_element->hmax();
// Store the parent element centroid
_centroids[_current_elem->id()] = original_element->centroid();
}
void
CircleMaxOriginalElementSize::threadJoin(const UserObject & y)
{
// We are joining with another class like this one so do a cast so we can get to it's data
const CircleMaxOriginalElementSize & uo = dynamic_cast<const CircleMaxOriginalElementSize &>(y);
_original_element_sizes.insert(uo._original_element_sizes.begin(), uo._original_element_sizes.end());
_centroids.insert(uo._centroids.begin(), uo._centroids.end());
}
void
CircleMaxOriginalElementSize::finalize()
{
_communicator.set_union(_original_element_sizes);
_communicator.set_union(_centroids);
}
Real
CircleMaxOriginalElementSize::distance(Point p1, Point p2) const
{
// distance between supplied point and element centroid depends on perodicity
if (_periodic_var < 0)
return (p1 - p2).norm();
return _mesh.minPeriodicDistance(_periodic_var, p1, p2);
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.2 2001/11/15 17:10:19 knoaman
* Particle derivation checking support.
*
* Revision 1.1 2001/11/02 14:08:40 knoaman
* Add support for identity constraints.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <validators/schema/identity/IC_Selector.hpp>
#include <validators/schema/identity/XercesXPath.hpp>
#include <validators/schema/identity/IdentityConstraint.hpp>
#include <validators/schema/identity/FieldActivator.hpp>
// ---------------------------------------------------------------------------
// SelectorMatcher: Constructors and Destructor
// ---------------------------------------------------------------------------
SelectorMatcher::SelectorMatcher(XercesXPath* const xpath,
IC_Selector* const selector,
FieldActivator* const fieldActivator)
: XPathMatcher(xpath, false, selector->getIdentityConstraint())
, fElementDepth(0)
, fMatchedDepth(-1)
, fSelector(selector)
, fFieldActivator(fieldActivator)
{
}
// ---------------------------------------------------------------------------
// FieldMatcher: XMLDocumentHandler methods
// ---------------------------------------------------------------------------
void SelectorMatcher::startDocumentFragment() {
XPathMatcher::startDocumentFragment();
fElementDepth = 0;
fMatchedDepth = -1;
}
void SelectorMatcher::startElement(const XMLElementDecl& elemDecl,
const unsigned int urlId,
const XMLCh* const elemPrefix,
const RefVectorOf<XMLAttr>& attrList,
const unsigned int attrCount) {
XPathMatcher::startElement(elemDecl, urlId, elemPrefix, attrList, attrCount);
fElementDepth++;
// activate the fields, if selector is matched
if (fMatchedDepth == -1 && isMatched()) {
IdentityConstraint* ic = fSelector->getIdentityConstraint();
int count = ic->getFieldCount();
fMatchedDepth = fElementDepth;
fFieldActivator->startValueScopeFor(ic);
for (int i = 0; i < count; i++) {
IC_Field* field = ic->getFieldAt(i);
XPathMatcher* matcher = fFieldActivator->activateField(field);
matcher->startElement(elemDecl, urlId, elemPrefix, attrList, attrCount);
}
}
}
void SelectorMatcher::endElement(const XMLElementDecl& elemDecl) {
XPathMatcher::endElement(elemDecl);
if (fElementDepth-- == fMatchedDepth) {
fMatchedDepth = -1;
fFieldActivator->endValueScopeFor(fSelector->getIdentityConstraint());
}
}
// ---------------------------------------------------------------------------
// IC_Selector: Constructors and Destructor
// ---------------------------------------------------------------------------
IC_Selector::IC_Selector(XercesXPath* const xpath,
IdentityConstraint* const identityConstraint)
: fXPath(xpath)
, fIdentityConstraint(identityConstraint)
{
}
IC_Selector::~IC_Selector()
{
delete fXPath;
}
// ---------------------------------------------------------------------------
// IC_Selector: operators
// ---------------------------------------------------------------------------
bool IC_Selector::operator ==(const IC_Selector& other) const {
return (*fXPath == *(other.fXPath));
}
bool IC_Selector::operator !=(const IC_Selector& other) const {
return !operator==(other);
}
// ---------------------------------------------------------------------------
// IC_Selector: Factory methods
// ---------------------------------------------------------------------------
XPathMatcher* IC_Selector::createMatcher(FieldActivator* const fieldActivator) {
return new SelectorMatcher(fXPath, this, fieldActivator);
}
/**
* End of file IC_Selector.cpp
*/
<commit_msg>Eliminate Warning from AIX xlC 3.6:1540-399: (W) "XMLAttr" is undefined. The delete operator will not call a destructor.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.3 2001/11/23 18:35:33 tng
* Eliminate Warning from AIX xlC 3.6:1540-399: (W) "XMLAttr" is undefined. The delete operator will not call a destructor.
*
* Revision 1.2 2001/11/15 17:10:19 knoaman
* Particle derivation checking support.
*
* Revision 1.1 2001/11/02 14:08:40 knoaman
* Add support for identity constraints.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <framework/XMLAttr.hpp>
#include <validators/schema/identity/IC_Selector.hpp>
#include <validators/schema/identity/XercesXPath.hpp>
#include <validators/schema/identity/IdentityConstraint.hpp>
#include <validators/schema/identity/FieldActivator.hpp>
// ---------------------------------------------------------------------------
// SelectorMatcher: Constructors and Destructor
// ---------------------------------------------------------------------------
SelectorMatcher::SelectorMatcher(XercesXPath* const xpath,
IC_Selector* const selector,
FieldActivator* const fieldActivator)
: XPathMatcher(xpath, false, selector->getIdentityConstraint())
, fElementDepth(0)
, fMatchedDepth(-1)
, fSelector(selector)
, fFieldActivator(fieldActivator)
{
}
// ---------------------------------------------------------------------------
// FieldMatcher: XMLDocumentHandler methods
// ---------------------------------------------------------------------------
void SelectorMatcher::startDocumentFragment() {
XPathMatcher::startDocumentFragment();
fElementDepth = 0;
fMatchedDepth = -1;
}
void SelectorMatcher::startElement(const XMLElementDecl& elemDecl,
const unsigned int urlId,
const XMLCh* const elemPrefix,
const RefVectorOf<XMLAttr>& attrList,
const unsigned int attrCount) {
XPathMatcher::startElement(elemDecl, urlId, elemPrefix, attrList, attrCount);
fElementDepth++;
// activate the fields, if selector is matched
if (fMatchedDepth == -1 && isMatched()) {
IdentityConstraint* ic = fSelector->getIdentityConstraint();
int count = ic->getFieldCount();
fMatchedDepth = fElementDepth;
fFieldActivator->startValueScopeFor(ic);
for (int i = 0; i < count; i++) {
IC_Field* field = ic->getFieldAt(i);
XPathMatcher* matcher = fFieldActivator->activateField(field);
matcher->startElement(elemDecl, urlId, elemPrefix, attrList, attrCount);
}
}
}
void SelectorMatcher::endElement(const XMLElementDecl& elemDecl) {
XPathMatcher::endElement(elemDecl);
if (fElementDepth-- == fMatchedDepth) {
fMatchedDepth = -1;
fFieldActivator->endValueScopeFor(fSelector->getIdentityConstraint());
}
}
// ---------------------------------------------------------------------------
// IC_Selector: Constructors and Destructor
// ---------------------------------------------------------------------------
IC_Selector::IC_Selector(XercesXPath* const xpath,
IdentityConstraint* const identityConstraint)
: fXPath(xpath)
, fIdentityConstraint(identityConstraint)
{
}
IC_Selector::~IC_Selector()
{
delete fXPath;
}
// ---------------------------------------------------------------------------
// IC_Selector: operators
// ---------------------------------------------------------------------------
bool IC_Selector::operator ==(const IC_Selector& other) const {
return (*fXPath == *(other.fXPath));
}
bool IC_Selector::operator !=(const IC_Selector& other) const {
return !operator==(other);
}
// ---------------------------------------------------------------------------
// IC_Selector: Factory methods
// ---------------------------------------------------------------------------
XPathMatcher* IC_Selector::createMatcher(FieldActivator* const fieldActivator) {
return new SelectorMatcher(fXPath, this, fieldActivator);
}
/**
* End of file IC_Selector.cpp
*/
<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is licensed under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// __END_LICENSE__
/// \file Core/Cache.cc
///
/// Types and functions to assist cacheing regeneratable data.
///
#include <vw/Core/Cache.h>
void vw::Cache::allocate( size_t size, CacheLineBase* line ) {
// Put the current cache line at the top of the list (so the most
// recently used). If the cache size is beyond the storage limit,
// de-allocate the least recently used elements.
// Note: Doing allocation implies the need to call validate.
// WARNING! YOU CAN NOT HOLD THE CACHE MUTEX AND THEN CALL
// INVALIDATE. That's a line -> cache -> line mutex hold. A
// deadlock!
// The lock below is recursive, so if a resource is locked by a
// thread, it can still be accessed by this thread, but not by
// others.
RecursiveMutex::Lock cache_lock( m_line_mgmt_mutex );
uint64 local_evictions = 0;
validate( line ); // Call here to insure that last_valid is not us!
m_size += size; // Update the size after adding the new line
VW_CACHE_DEBUG( VW_OUT(DebugMessage, "cache") << "Cache allocated " << size
<< " bytes (" << m_size << " / " << m_max_size << " used)" << "\n"; );
CacheLineBase* local_last_valid = m_last_valid;
while ( m_size > m_max_size ) {
if ( local_last_valid == line || !local_last_valid ) {
// De-allocated all lines except the current one which are not
// held up currently by other threads.
break;
}
bool invalidated = local_last_valid->try_invalidate();
if (invalidated) {
local_evictions++;
local_last_valid = m_last_valid;
} else {
// If we can't deallocate current line,
// switch to the one used a bit more recently.
local_last_valid = local_last_valid->m_prev;
}
}
{
Mutex::WriteLock cache_lock( m_stats_mutex );
m_evictions += local_evictions;
}
// Warn about exceeding the cache size max_num_warnings times.
int max_num_warnings = 1000;
if ( m_size > m_max_size && m_num_warnings < max_num_warnings){
VW_OUT(WarningMessage, "cache")
<< "Cached object (" << size
<< ") larger than requested maximum cache size (" << m_max_size
<< "). Current size = " << m_size << "\n";
Mutex::WriteLock cache_lock( m_stats_mutex );
m_num_warnings++;
if (m_num_warnings == max_num_warnings){
VW_OUT(WarningMessage, "cache") << "Reached " << max_num_warnings << " warnings. Will stop printing more.\n";
}
}
}
}
void vw::Cache::resize( size_t size ) {
// WARNING! YOU CAN NOT HOLD THE CACHE MUTEX AND THEN CALL
// INVALIDATE. That's a line -> cache -> line mutex hold. A
// deadlock!
size_t local_size, local_max_size;
CacheLineBase* local_last_valid;
{ // Locally buffer variables that require Cache Mutex
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
m_max_size = size;
local_size = m_size;
local_max_size = m_max_size;
local_last_valid = m_last_valid;
}
while ( local_size > local_max_size ) {
VW_ASSERT( local_last_valid, LogicErr() << "Cache is empty but has nonzero size!" );
m_last_valid->invalidate(); // Problem ( probably grabs a line's mutex too )
{ // Update local buffer by grabbing cache buffer
RecursiveMutex::Lock cache_lock( m_line_mgmt_mutex );
local_size = m_size;
local_last_valid = m_last_valid;
}
}
}
size_t vw::Cache::max_size() {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
return m_max_size;
}
void vw::Cache::deallocate( size_t size, CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
// This call implies the need to call invalidate
invalidate( line );
m_size -= size;
VW_CACHE_DEBUG( VW_OUT(DebugMessage, "cache") << "Cache deallocated " << size << " bytes (" << m_size << " / " << m_max_size << " used)" << "\n"; )
}
// Move the cache line to the top of the valid list.
void vw::Cache::validate( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_first_valid ) return;
if( line == m_last_valid ) m_last_valid = line->m_prev;
if( line == m_first_invalid ) m_first_invalid = line->m_next;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_next = m_first_valid;
line->m_prev = 0;
if( m_first_valid ) m_first_valid->m_prev = line;
m_first_valid = line;
if( ! m_last_valid ) m_last_valid = line;
}
// Move the cache line to the top of the invalid list.
void vw::Cache::invalidate( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_first_valid ) m_first_valid = line->m_next;
if( line == m_last_valid ) m_last_valid = line->m_prev;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_next = m_first_invalid;
line->m_prev = 0;
if( m_first_invalid ) m_first_invalid->m_prev = line;
m_first_invalid = line;
}
// Remove the cache line from the cache lists.
void vw::Cache::remove( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_first_valid ) m_first_valid = line->m_next;
if( line == m_last_valid ) m_last_valid = line->m_prev;
if( line == m_first_invalid ) m_first_invalid = line->m_next;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_next = line->m_prev = 0;
}
// Move the cache line to the bottom of the valid list.
void vw::Cache::deprioritize( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_last_valid ) return;
if( line == m_first_valid ) m_first_valid = line->m_next;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_prev = m_last_valid;
line->m_next = 0;
m_last_valid->m_next = line;
m_last_valid = line;
}
// Statistics request methods
vw::uint64 vw::Cache::hits() {
Mutex::ReadLock cache_lock( m_stats_mutex );
return m_hits;
}
vw::uint64 vw::Cache::misses() {
Mutex::ReadLock cache_lock( m_stats_mutex );
return m_misses;
}
vw::uint64 vw::Cache::evictions() {
Mutex::ReadLock cache_lock( m_stats_mutex );
return m_evictions;
}
void vw::Cache::clear_stats() {
Mutex::WriteLock cache_lock( m_stats_mutex );
m_hits = m_misses = m_evictions = 0;
}
<commit_msg>Cache: refine previous fix<commit_after>// __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is licensed under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// __END_LICENSE__
/// \file Core/Cache.cc
///
/// Types and functions to assist cacheing regeneratable data.
///
#include <vw/Core/Cache.h>
void vw::Cache::allocate( size_t size, CacheLineBase* line ) {
// Put the current cache line at the top of the list (so the most
// recently used). If the cache size is beyond the storage limit,
// de-allocate the least recently used elements.
// Note: Doing allocation implies the need to call validate.
// WARNING! YOU CAN NOT HOLD THE CACHE MUTEX AND THEN CALL
// INVALIDATE. That's a line -> cache -> line mutex hold. A
// deadlock!
// The lock below is recursive, so if a resource is locked by a
// thread, it can still be accessed by this thread, but not by
// others.
RecursiveMutex::Lock cache_lock( m_line_mgmt_mutex );
uint64 local_evictions = 0;
validate( line ); // Call here to insure that last_valid is not us!
m_size += size; // Update the size after adding the new line
VW_CACHE_DEBUG( VW_OUT(DebugMessage, "cache") << "Cache allocated " << size
<< " bytes (" << m_size << " / " << m_max_size << " used)" << "\n"; );
CacheLineBase* local_last_valid = m_last_valid;
while ( m_size > m_max_size ) {
if ( local_last_valid == line || !local_last_valid ) {
// De-allocated all lines except the current one which are not
// held up currently by other threads.
break;
}
bool invalidated = local_last_valid->try_invalidate();
if (invalidated) {
local_evictions++;
local_last_valid = m_last_valid;
} else {
// If we can't deallocate current line,
// switch to the one used a bit more recently.
local_last_valid = local_last_valid->m_prev;
}
}
{
Mutex::WriteLock cache_lock( m_stats_mutex );
m_evictions += local_evictions;
}
// Warn about exceeding the cache size max_num_warnings times.
size_t max_num_warnings = 1000;
if ( m_size > m_max_size && m_num_warnings < max_num_warnings){
VW_OUT(WarningMessage, "cache")
<< "Cached object (" << size
<< ") larger than requested maximum cache size (" << m_max_size
<< "). Current size = " << m_size << "\n";
{
Mutex::WriteLock cache_lock( m_stats_mutex );
m_num_warnings++;
if (m_num_warnings == max_num_warnings){
VW_OUT(WarningMessage, "cache") << "Reached " << max_num_warnings << " warnings. Will stop printing more.\n";
}
}
}
}
void vw::Cache::resize( size_t size ) {
// WARNING! YOU CAN NOT HOLD THE CACHE MUTEX AND THEN CALL
// INVALIDATE. That's a line -> cache -> line mutex hold. A
// deadlock!
size_t local_size, local_max_size;
CacheLineBase* local_last_valid;
{ // Locally buffer variables that require Cache Mutex
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
m_max_size = size;
local_size = m_size;
local_max_size = m_max_size;
local_last_valid = m_last_valid;
}
while ( local_size > local_max_size ) {
VW_ASSERT( local_last_valid, LogicErr() << "Cache is empty but has nonzero size!" );
m_last_valid->invalidate(); // Problem ( probably grabs a line's mutex too )
{ // Update local buffer by grabbing cache buffer
RecursiveMutex::Lock cache_lock( m_line_mgmt_mutex );
local_size = m_size;
local_last_valid = m_last_valid;
}
}
}
size_t vw::Cache::max_size() {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
return m_max_size;
}
void vw::Cache::deallocate( size_t size, CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
// This call implies the need to call invalidate
invalidate( line );
m_size -= size;
VW_CACHE_DEBUG( VW_OUT(DebugMessage, "cache") << "Cache deallocated " << size << " bytes (" << m_size << " / " << m_max_size << " used)" << "\n"; )
}
// Move the cache line to the top of the valid list.
void vw::Cache::validate( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_first_valid ) return;
if( line == m_last_valid ) m_last_valid = line->m_prev;
if( line == m_first_invalid ) m_first_invalid = line->m_next;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_next = m_first_valid;
line->m_prev = 0;
if( m_first_valid ) m_first_valid->m_prev = line;
m_first_valid = line;
if( ! m_last_valid ) m_last_valid = line;
}
// Move the cache line to the top of the invalid list.
void vw::Cache::invalidate( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_first_valid ) m_first_valid = line->m_next;
if( line == m_last_valid ) m_last_valid = line->m_prev;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_next = m_first_invalid;
line->m_prev = 0;
if( m_first_invalid ) m_first_invalid->m_prev = line;
m_first_invalid = line;
}
// Remove the cache line from the cache lists.
void vw::Cache::remove( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_first_valid ) m_first_valid = line->m_next;
if( line == m_last_valid ) m_last_valid = line->m_prev;
if( line == m_first_invalid ) m_first_invalid = line->m_next;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_next = line->m_prev = 0;
}
// Move the cache line to the bottom of the valid list.
void vw::Cache::deprioritize( CacheLineBase *line ) {
RecursiveMutex::Lock cache_lock(m_line_mgmt_mutex);
if( line == m_last_valid ) return;
if( line == m_first_valid ) m_first_valid = line->m_next;
if( line->m_next ) line->m_next->m_prev = line->m_prev;
if( line->m_prev ) line->m_prev->m_next = line->m_next;
line->m_prev = m_last_valid;
line->m_next = 0;
m_last_valid->m_next = line;
m_last_valid = line;
}
// Statistics request methods
vw::uint64 vw::Cache::hits() {
Mutex::ReadLock cache_lock( m_stats_mutex );
return m_hits;
}
vw::uint64 vw::Cache::misses() {
Mutex::ReadLock cache_lock( m_stats_mutex );
return m_misses;
}
vw::uint64 vw::Cache::evictions() {
Mutex::ReadLock cache_lock( m_stats_mutex );
return m_evictions;
}
void vw::Cache::clear_stats() {
Mutex::WriteLock cache_lock( m_stats_mutex );
m_hits = m_misses = m_evictions = 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: attr.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2007-11-19 16:40:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ATTR_HXX
#define _ATTR_HXX
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XAttr.hpp>
#include "node.hxx"
#include <libxml/tree.h>
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;
namespace DOM
{
class CAttr : public cppu::ImplInheritanceHelper1< CNode, XAttr >
{
friend class CNode;
friend class CElement;
private:
xmlAttrPtr m_aAttrPtr;
protected:
CAttr(const xmlAttrPtr aAttrPtr);
public:
/**
Returns the name of this attribute.
*/
virtual OUString SAL_CALL getName() throw (RuntimeException);
/**
The Element node this attribute is attached to or null if this
attribute is not in use.
*/
virtual Reference< XElement > SAL_CALL getOwnerElement() throw (RuntimeException);
/**
If this attribute was explicitly given a value in the original
document, this is true; otherwise, it is false.
*/
virtual sal_Bool SAL_CALL getSpecified()throw (RuntimeException);
/**
On retrieval, the value of the attribute is returned as a string.
*/
virtual OUString SAL_CALL getValue() throw (RuntimeException);
/**
Sets the value of the attribute from a string.
*/
virtual void SAL_CALL setValue(const OUString& value) throw (DOMException);
// resolve uno inheritance problems...
// overrides for XNode base
virtual OUString SAL_CALL getNodeName()
throw (RuntimeException);
virtual OUString SAL_CALL getNodeValue()
throw (RuntimeException);
// --- delegation for XNde base.
virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild)
throw (DOMException)
{
return CNode::appendChild(newChild);
}
virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep)
throw (RuntimeException)
{
return CNode::cloneNode(deep);
}
virtual Reference< XNamedNodeMap > SAL_CALL getAttributes()
throw (RuntimeException)
{
return CNode::getAttributes();
}
virtual Reference< XNodeList > SAL_CALL getChildNodes()
throw (RuntimeException)
{
return CNode::getChildNodes();
}
virtual Reference< XNode > SAL_CALL getFirstChild()
throw (RuntimeException)
{
return CNode::getFirstChild();
}
virtual Reference< XNode > SAL_CALL getLastChild()
throw (RuntimeException)
{
return CNode::getLastChild();
}
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException)
{
return CNode::getLocalName();
}
virtual OUString SAL_CALL getNamespaceURI()
throw (RuntimeException)
{
return CNode::getNamespaceURI();
}
virtual Reference< XNode > SAL_CALL getNextSibling()
throw (RuntimeException)
{
return CNode::getNextSibling();
}
virtual NodeType SAL_CALL getNodeType()
throw (RuntimeException)
{
return CNode::getNodeType();
}
virtual Reference< XDocument > SAL_CALL getOwnerDocument()
throw (RuntimeException)
{
return CNode::getOwnerDocument();
}
virtual Reference< XNode > SAL_CALL getParentNode()
throw (RuntimeException)
{
return CNode::getParentNode();
}
virtual OUString SAL_CALL getPrefix()
throw (RuntimeException)
{
return CNode::getPrefix();
}
virtual Reference< XNode > SAL_CALL getPreviousSibling()
throw (RuntimeException)
{
return CNode::getPreviousSibling();
}
virtual sal_Bool SAL_CALL hasAttributes()
throw (RuntimeException)
{
return CNode::hasAttributes();
}
virtual sal_Bool SAL_CALL hasChildNodes()
throw (RuntimeException)
{
return CNode::hasChildNodes();
}
virtual Reference< XNode > SAL_CALL insertBefore(
const Reference< XNode >& newChild, const Reference< XNode >& refChild)
throw (DOMException)
{
return CNode::insertBefore(newChild, refChild);
}
virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver)
throw (RuntimeException)
{
return CNode::isSupported(feature, ver);
}
virtual void SAL_CALL normalize()
throw (RuntimeException)
{
CNode::normalize();
}
virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild)
throw (DOMException)
{
return CNode::removeChild(oldChild);
}
virtual Reference< XNode > SAL_CALL replaceChild(
const Reference< XNode >& newChild, const Reference< XNode >& oldChild)
throw (DOMException)
{
return CNode::replaceChild(newChild, oldChild);
}
virtual void SAL_CALL setNodeValue(const OUString& nodeValue)
throw (DOMException)
{
return setValue(nodeValue);
}
virtual void SAL_CALL setPrefix(const OUString& prefix)
throw (DOMException)
{
return CNode::setPrefix(prefix);
}
};
}
#endif
<commit_msg>INTEGRATION: CWS os108 (1.6.40); FILE MERGED 2007/11/19 15:25:13 mst 1.6.40.1: - uno/xml/source/dom/*.{hc}xx: add RuntimeException to exception specifications of 172 methods of the DOM implementation where it was missing; fixes #i83675#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: attr.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2007-12-06 10:58:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ATTR_HXX
#define _ATTR_HXX
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XAttr.hpp>
#include "node.hxx"
#include <libxml/tree.h>
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;
namespace DOM
{
class CAttr : public cppu::ImplInheritanceHelper1< CNode, XAttr >
{
friend class CNode;
friend class CElement;
private:
xmlAttrPtr m_aAttrPtr;
protected:
CAttr(const xmlAttrPtr aAttrPtr);
public:
/**
Returns the name of this attribute.
*/
virtual OUString SAL_CALL getName() throw (RuntimeException);
/**
The Element node this attribute is attached to or null if this
attribute is not in use.
*/
virtual Reference< XElement > SAL_CALL getOwnerElement() throw (RuntimeException);
/**
If this attribute was explicitly given a value in the original
document, this is true; otherwise, it is false.
*/
virtual sal_Bool SAL_CALL getSpecified()throw (RuntimeException);
/**
On retrieval, the value of the attribute is returned as a string.
*/
virtual OUString SAL_CALL getValue() throw (RuntimeException);
/**
Sets the value of the attribute from a string.
*/
virtual void SAL_CALL setValue(const OUString& value) throw (RuntimeException, DOMException);
// resolve uno inheritance problems...
// overrides for XNode base
virtual OUString SAL_CALL getNodeName()
throw (RuntimeException);
virtual OUString SAL_CALL getNodeValue()
throw (RuntimeException);
// --- delegation for XNde base.
virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild)
throw (RuntimeException, DOMException)
{
return CNode::appendChild(newChild);
}
virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep)
throw (RuntimeException)
{
return CNode::cloneNode(deep);
}
virtual Reference< XNamedNodeMap > SAL_CALL getAttributes()
throw (RuntimeException)
{
return CNode::getAttributes();
}
virtual Reference< XNodeList > SAL_CALL getChildNodes()
throw (RuntimeException)
{
return CNode::getChildNodes();
}
virtual Reference< XNode > SAL_CALL getFirstChild()
throw (RuntimeException)
{
return CNode::getFirstChild();
}
virtual Reference< XNode > SAL_CALL getLastChild()
throw (RuntimeException)
{
return CNode::getLastChild();
}
virtual OUString SAL_CALL getLocalName()
throw (RuntimeException)
{
return CNode::getLocalName();
}
virtual OUString SAL_CALL getNamespaceURI()
throw (RuntimeException)
{
return CNode::getNamespaceURI();
}
virtual Reference< XNode > SAL_CALL getNextSibling()
throw (RuntimeException)
{
return CNode::getNextSibling();
}
virtual NodeType SAL_CALL getNodeType()
throw (RuntimeException)
{
return CNode::getNodeType();
}
virtual Reference< XDocument > SAL_CALL getOwnerDocument()
throw (RuntimeException)
{
return CNode::getOwnerDocument();
}
virtual Reference< XNode > SAL_CALL getParentNode()
throw (RuntimeException)
{
return CNode::getParentNode();
}
virtual OUString SAL_CALL getPrefix()
throw (RuntimeException)
{
return CNode::getPrefix();
}
virtual Reference< XNode > SAL_CALL getPreviousSibling()
throw (RuntimeException)
{
return CNode::getPreviousSibling();
}
virtual sal_Bool SAL_CALL hasAttributes()
throw (RuntimeException)
{
return CNode::hasAttributes();
}
virtual sal_Bool SAL_CALL hasChildNodes()
throw (RuntimeException)
{
return CNode::hasChildNodes();
}
virtual Reference< XNode > SAL_CALL insertBefore(
const Reference< XNode >& newChild, const Reference< XNode >& refChild)
throw (RuntimeException, DOMException)
{
return CNode::insertBefore(newChild, refChild);
}
virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver)
throw (RuntimeException)
{
return CNode::isSupported(feature, ver);
}
virtual void SAL_CALL normalize()
throw (RuntimeException)
{
CNode::normalize();
}
virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild)
throw (RuntimeException, DOMException)
{
return CNode::removeChild(oldChild);
}
virtual Reference< XNode > SAL_CALL replaceChild(
const Reference< XNode >& newChild, const Reference< XNode >& oldChild)
throw (RuntimeException, DOMException)
{
return CNode::replaceChild(newChild, oldChild);
}
virtual void SAL_CALL setNodeValue(const OUString& nodeValue)
throw (RuntimeException, DOMException)
{
return setValue(nodeValue);
}
virtual void SAL_CALL setPrefix(const OUString& prefix)
throw (RuntimeException, DOMException)
{
return CNode::setPrefix(prefix);
}
};
}
#endif
<|endoftext|>
|
<commit_before>#include "h5test.h"
#include "parallel_io.h"
#include "comm.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"
struct Var_t
{
const char * name;
const char * descript;
};
Var_t varT[] =
{
{"T", "Temp in K"},
{"p", "Pressure in N/m^2"},
{"u", "X Velocity in m/s"},
{"v", "Y Velocity in m/s"},
{"w", "Z Velocity in m/s"},
{"a", "A Velocity in m/s"},
{"b", "B Velocity in m/s"},
{"c", "C Velocity in m/s"},
{"d", "D Velocity in m/s"},
{"e", "E Velocity in m/s"},
};
ParallelIO::ParallelIO()
: m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0),
m_dne_stripes(-1), m_auto_max_stripes(-1), m_nStripesT3(-1)
{}
#ifndef USE_HDF5
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
if (P.myProc == 0)
printf("This program requires HDF5 which is not available => quitting\n");
}
void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
}
#else
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
hid_t file_id; //file identifier
hid_t group_id; //group identifier
hid_t dset_id; //Dataset identifier
hid_t filespace; //Dataspace id in file
hid_t memspace; //Dataspace id in memory.
hid_t plist_id; //Property List id
hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;
hsize_t is, num;
int ierr;
MPI_Comm commF;
H5FD_mpio_xfer_t xfer_mode; // HDF5 transfer mode (indep or collective)
const char * fn = "UNSTRUCT.h5";
// compute size info
rem = cmd.globalSz % P.nProcs;
if (P.myProc < rem)
is = P.myProc * cmd.localSz;
else
is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);
double lSz = 1.0;
m_numvar = cmd.nvar;
num = cmd.localSz;
lSz = num;
count[0] = 1;
h5stride[0] = 1;
starts[0] = is;
sz[0] = num;
gsz[0] = cmd.globalSz;
m_totalSz = cmd.globalSz*m_numvar*sizeof(double);
int iTotalSz = m_totalSz/(1024*1024);
// Initialize data buffer
double xk = num*P.myProc;
double *data = new double[num];
for (int i = 0; i < num; ++i)
data[i] = xk++;
double t0, t1, t2;
// Delete old file
if (P.myProc == 0)
MPI_File_delete((char * )fn, MPI_INFO_NULL);
MPI_Barrier(P.comm);
// Build MPI info;
MPI_Info info = MPI_INFO_NULL;
MPI_Info infoF = MPI_INFO_NULL;
MPI_Info_create(&info);
MPI_Info_create(&infoF);
T3PIO_results_t results;
if (cmd.useT3PIO)
{
int ierr = t3pio_set_info(P.comm, info, "./",
T3PIO_GLOBAL_SIZE, iTotalSz,
T3PIO_STRIPE_COUNT, cmd.stripes,
T3PIO_STRIPE_SIZE_MB, cmd.stripeSz,
T3PIO_MAX_AGGREGATORS, cmd.maxWriters,
T3PIO_RESULTS, &results);
m_nIOUnits = results.numIO;
m_dne_stripes = results.S_dne;
m_auto_max_stripes = results.S_auto_max;
m_nStripesT3 = results.nStripesT3;
}
xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;
t0 = walltime();
plist_id = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_fapl_mpio(plist_id, P.comm, info);
// Create file collectively
file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);
MPI_File* pFH = NULL;
ierr = H5Fget_vfd_handle(file_id, H5P_DEFAULT, (void **) &pFH);
ierr = MPI_File_get_info(*pFH, &infoF);
t3pio_extract_key_values(infoF, &results);
m_aggregators = results.numIO;
m_nStripes = results.numStripes;
m_stripeSz = results.stripeSize;
H5Pclose(plist_id);
// Create Group
group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
std::string timeZ, timeL;
dateZ(timeZ);
add_attribute(group_id,"Zulu Time", timeZ.c_str());
dateL(timeL);
add_attribute(group_id,"Local Time", timeL.c_str());
for (int ivar = 0; ivar < m_numvar; ++ivar)
{
// Create the dataspace for the dataset
filespace = H5Screate_simple(1, &gsz[0], NULL);
memspace = H5Screate_simple(1, sz, NULL);
if (cmd.h5chunk)
{
plist_id = H5Pcreate(H5P_DATASET_CREATE);
H5Pset_chunk(plist_id,1, sz);
dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
H5P_DEFAULT, plist_id, H5P_DEFAULT);
H5Pclose(plist_id);
H5Sclose(filespace);
filespace = H5Dget_space(dset_id);
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
}
else if (cmd.h5slab)
{
// Create the dataset w/ default properties and close filespace
dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Sclose(filespace);
// Select hyperslab in the file.
filespace = H5Dget_space(dset_id);
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
}
plist_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(plist_id, xfer_mode);
add_attribute(dset_id, "Variable Description", varT[ivar].descript);
t1 = walltime();
herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
plist_id, data);
t2 = walltime();
m_t += (t2 - t1);
H5Dclose(dset_id);
H5Sclose(filespace);
H5Sclose(memspace);
H5Pclose(plist_id);
}
m_totalTime = walltime() - t0;
m_rate = m_totalSz /(m_totalTime * 1024.0 * 1024.0);
free(data);
H5Gclose(group_id);
H5Fclose(file_id);
MPI_Info_free(&info);
MPI_Info_free(&infoF);
}
void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
hid_t attr_id, aspace_id, atype_id;
hsize_t attrlen, num[1];
attrlen = strlen(value);
num[0] = 1;
atype_id = H5Tcopy(H5T_C_S1);
H5Tset_size(atype_id, attrlen);
aspace_id = H5Screate_simple(1,num, NULL);
attr_id = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr_id, atype_id, value);
H5Aclose(attr_id);
H5Sclose(aspace_id);
}
#endif
void ParallelIO::MPIIOwriter(CmdLineOptions& cmd)
{
MPI_File fh;
MPI_Offset is, rem, offset;
MPI_Datatype coreData, gblData, my_vector;
MPI_Status status;
int iTotalSz, ierr, nDim;
int sz[2], gsz[2], starts[2];
const char* fn = "UNSTRUCT.mpiio";
rem = cmd.globalSz % P.nProcs;
if (P.myProc < rem)
is = P.myProc * cmd.localSz;
else
is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);
m_numvar = 1;
m_totalSz = cmd.globalSz*m_numvar*sizeof(double);
iTotalSz = m_totalSz/(1024*1024);
int num = cmd.localSz;
double *data = new double[num];
double xk = is;
for (int i = 0; i < num; ++i)
data[i] = xk++;
double t0, t1, t2;
// Delete old file
if (P.myProc == 0)
MPI_File_delete((char * )fn, MPI_INFO_NULL);
MPI_Barrier(P.comm);
// Build MPI info;
MPI_Info info = MPI_INFO_NULL;
MPI_Info infoF = MPI_INFO_NULL;
MPI_Info_create(&info);
MPI_Info_create(&infoF);
T3PIO_results_t results;
if (cmd.useT3PIO)
{
int ierr = t3pio_set_info(P.comm, info, "./",
T3PIO_GLOBAL_SIZE, iTotalSz,
T3PIO_STRIPE_COUNT, cmd.stripes,
T3PIO_STRIPE_SIZE_MB, cmd.stripeSz,
T3PIO_MAX_AGGREGATORS, cmd.maxWriters,
T3PIO_RESULTS, &results);
m_nIOUnits = results.numIO;
}
//nDim = 1;
//offset = is*sizeof(double);
//ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);
//ierr = MPI_Type_commit(&my_vector);
//ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, "native", info);
offset = 0;
nDim = 2;
sz[0] = cmd.localSz/cmd.xwidth;
sz[1] = cmd.xwidth;
gsz[0] = cmd.globalSz/cmd.xwidth;
gsz[1] = cmd.xwidth;
starts[0] = 0;
starts[1] = 0;
ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
&coreData);
ierr = MPI_Type_commit(&coreData);
starts[0] = sz[0]*P.myProc;
ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
&gblData);
ierr = MPI_Type_commit(&gblData);
t0 = walltime();
ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);
if (ierr)
MPI_Abort(P.comm, -1);
ierr = MPI_File_get_info(fh, &infoF);
t3pio_extract_key_values(infoF, &results);
m_aggregators = results.numIO;
m_nStripes = results.numStripes;
m_stripeSz = results.stripeSize;
ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, "native", info);
ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);
ierr = MPI_File_close(&fh);
m_totalTime = walltime() - t0;
m_rate = m_totalSz/(m_totalTime * 1024.0 * 1024.0);
MPI_Info_free(&info);
MPI_Info_free(&infoF);
}
<commit_msg>yet another typo<commit_after>#include "h5test.h"
#include "parallel_io.h"
#include "comm.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"
struct Var_t
{
const char * name;
const char * descript;
};
Var_t varT[] =
{
{"T", "Temp in K"},
{"p", "Pressure in N/m^2"},
{"u", "X Velocity in m/s"},
{"v", "Y Velocity in m/s"},
{"w", "Z Velocity in m/s"},
{"a", "A Velocity in m/s"},
{"b", "B Velocity in m/s"},
{"c", "C Velocity in m/s"},
{"d", "D Velocity in m/s"},
{"e", "E Velocity in m/s"},
};
ParallelIO::ParallelIO()
: m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0),
m_dne_stripes(-1), m_auto_max_stripes(-1), m_nStripesT3(-1)
{}
#ifndef USE_HDF5
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
if (P.myProc == 0)
printf("This program requires HDF5 which is not available => quitting\n");
}
void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
}
#else
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
hid_t file_id; //file identifier
hid_t group_id; //group identifier
hid_t dset_id; //Dataset identifier
hid_t filespace; //Dataspace id in file
hid_t memspace; //Dataspace id in memory.
hid_t plist_id; //Property List id
hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;
hsize_t is, num;
int ierr;
MPI_Comm commF;
H5FD_mpio_xfer_t xfer_mode; // HDF5 transfer mode (indep or collective)
const char * fn = "UNSTRUCT.h5";
// compute size info
rem = cmd.globalSz % P.nProcs;
if (P.myProc < rem)
is = P.myProc * cmd.localSz;
else
is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);
double lSz = 1.0;
m_numvar = cmd.nvar;
num = cmd.localSz;
lSz = num;
count[0] = 1;
h5stride[0] = 1;
starts[0] = is;
sz[0] = num;
gsz[0] = cmd.globalSz;
m_totalSz = cmd.globalSz*m_numvar*sizeof(double);
int iTotalSz = m_totalSz/(1024*1024);
// Initialize data buffer
double xk = num*P.myProc;
double *data = new double[num];
for (int i = 0; i < num; ++i)
data[i] = xk++;
double t0, t1, t2;
// Delete old file
if (P.myProc == 0)
MPI_File_delete((char * )fn, MPI_INFO_NULL);
MPI_Barrier(P.comm);
// Build MPI info;
MPI_Info info = MPI_INFO_NULL;
MPI_Info infoF = MPI_INFO_NULL;
MPI_Info_create(&info);
MPI_Info_create(&infoF);
T3PIO_results_t results;
if (cmd.useT3PIO)
{
int ierr = t3pio_set_info(P.comm, info, "./",
T3PIO_GLOBAL_SIZE, iTotalSz,
T3PIO_STRIPE_COUNT, cmd.stripes,
T3PIO_STRIPE_SIZE_MB, cmd.stripeSz,
T3PIO_MAX_AGGREGATORS, cmd.maxWriters,
T3PIO_RESULTS, &results);
m_nIOUnits = results.numIO;
m_dne_stripes = results.S_dne;
m_auto_max_stripes = results.S_auto_max;
m_nStripesT3 = results.nStripesT3;
m_aggregators = results.numIO;
m_nStripes = results.numStripes;
m_stripeSz = results.stripeSize;
}
xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;
t0 = walltime();
plist_id = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_fapl_mpio(plist_id, P.comm, info);
// Create file collectively
file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);
H5Pclose(plist_id);
// Create Group
group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
std::string timeZ, timeL;
dateZ(timeZ);
add_attribute(group_id,"Zulu Time", timeZ.c_str());
dateL(timeL);
add_attribute(group_id,"Local Time", timeL.c_str());
for (int ivar = 0; ivar < m_numvar; ++ivar)
{
// Create the dataspace for the dataset
filespace = H5Screate_simple(1, &gsz[0], NULL);
memspace = H5Screate_simple(1, sz, NULL);
if (cmd.h5chunk)
{
plist_id = H5Pcreate(H5P_DATASET_CREATE);
H5Pset_chunk(plist_id,1, sz);
dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
H5P_DEFAULT, plist_id, H5P_DEFAULT);
H5Pclose(plist_id);
H5Sclose(filespace);
filespace = H5Dget_space(dset_id);
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
}
else if (cmd.h5slab)
{
// Create the dataset w/ default properties and close filespace
dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Sclose(filespace);
// Select hyperslab in the file.
filespace = H5Dget_space(dset_id);
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
}
plist_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(plist_id, xfer_mode);
add_attribute(dset_id, "Variable Description", varT[ivar].descript);
t1 = walltime();
herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
plist_id, data);
t2 = walltime();
m_t += (t2 - t1);
H5Dclose(dset_id);
H5Sclose(filespace);
H5Sclose(memspace);
H5Pclose(plist_id);
}
m_totalTime = walltime() - t0;
m_rate = m_totalSz /(m_totalTime * 1024.0 * 1024.0);
free(data);
H5Gclose(group_id);
H5Fclose(file_id);
MPI_Info_free(&info);
MPI_Info_free(&infoF);
}
void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
hid_t attr_id, aspace_id, atype_id;
hsize_t attrlen, num[1];
attrlen = strlen(value);
num[0] = 1;
atype_id = H5Tcopy(H5T_C_S1);
H5Tset_size(atype_id, attrlen);
aspace_id = H5Screate_simple(1,num, NULL);
attr_id = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr_id, atype_id, value);
H5Aclose(attr_id);
H5Sclose(aspace_id);
}
#endif
void ParallelIO::MPIIOwriter(CmdLineOptions& cmd)
{
MPI_File fh;
MPI_Offset is, rem, offset;
MPI_Datatype coreData, gblData, my_vector;
MPI_Status status;
int iTotalSz, ierr, nDim;
int sz[2], gsz[2], starts[2];
const char* fn = "UNSTRUCT.mpiio";
rem = cmd.globalSz % P.nProcs;
if (P.myProc < rem)
is = P.myProc * cmd.localSz;
else
is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);
m_numvar = 1;
m_totalSz = cmd.globalSz*m_numvar*sizeof(double);
iTotalSz = m_totalSz/(1024*1024);
int num = cmd.localSz;
double *data = new double[num];
double xk = is;
for (int i = 0; i < num; ++i)
data[i] = xk++;
double t0, t1, t2;
// Delete old file
if (P.myProc == 0)
MPI_File_delete((char * )fn, MPI_INFO_NULL);
MPI_Barrier(P.comm);
// Build MPI info;
MPI_Info info = MPI_INFO_NULL;
MPI_Info infoF = MPI_INFO_NULL;
MPI_Info_create(&info);
MPI_Info_create(&infoF);
T3PIO_results_t results;
if (cmd.useT3PIO)
{
int ierr = t3pio_set_info(P.comm, info, "./",
T3PIO_GLOBAL_SIZE, iTotalSz,
T3PIO_STRIPE_COUNT, cmd.stripes,
T3PIO_STRIPE_SIZE_MB, cmd.stripeSz,
T3PIO_MAX_AGGREGATORS, cmd.maxWriters,
T3PIO_RESULTS, &results);
m_nIOUnits = results.numIO;
m_aggregators = results.numIO;
m_nStripes = results.numStripes;
m_stripeSz = results.stripeSize;
}
//nDim = 1;
//offset = is*sizeof(double);
//ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);
//ierr = MPI_Type_commit(&my_vector);
//ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, "native", info);
offset = 0;
nDim = 2;
sz[0] = cmd.localSz/cmd.xwidth;
sz[1] = cmd.xwidth;
gsz[0] = cmd.globalSz/cmd.xwidth;
gsz[1] = cmd.xwidth;
starts[0] = 0;
starts[1] = 0;
ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
&coreData);
ierr = MPI_Type_commit(&coreData);
starts[0] = sz[0]*P.myProc;
ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
&gblData);
ierr = MPI_Type_commit(&gblData);
t0 = walltime();
ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);
if (ierr)
MPI_Abort(P.comm, -1);
ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, "native", info);
ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);
ierr = MPI_File_close(&fh);
m_totalTime = walltime() - t0;
m_rate = m_totalSz/(m_totalTime * 1024.0 * 1024.0);
MPI_Info_free(&info);
MPI_Info_free(&infoF);
}
<|endoftext|>
|
<commit_before>/*
* This file is part of yacas_kernel.
* Yacas is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesset General Public License as
* published by the Free Software Foundation, either version 2.1
* of the License, or (at your option) any later version.
*
* Yacas is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with yacas_kernel. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* File: yacas_kernel.cpp
* Author: mazur
*
* Created on November 6, 2015, 3:10 PM
*/
#include "yacas_kernel.hpp"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <iostream>
#include <fstream>
#include <string>
namespace {
std::string now()
{
using namespace boost::posix_time;
return to_iso_extended_string(microsec_clock::local_time());
}
}
YacasKernel::YacasKernel(const std::string& scripts_path, const Json::Value& config):
_uuid(_uuid_gen()),
_hb_socket(_ctx, zmqpp::socket_type::reply),
_iopub_socket(_ctx, zmqpp::socket_type::publish),
_control_socket(_ctx, zmqpp::socket_type::router),
_stdin_socket(_ctx, zmqpp::socket_type::router),
_shell_socket(_ctx, zmqpp::socket_type::router),
_engine_socket(_ctx, zmqpp::socket_type::pair),
_auth(config["key"].asString()),
_execution_count(1),
_yacas(new CYacas(_side_effects)),
_engine(scripts_path, _ctx, "inproc://engine")
{
const std::string transport = config["transport"].asString();
const std::string ip = config["ip"].asString();
_hb_socket.bind(transport + "://" + ip + ":" + config["hb_port"].asString());
_iopub_socket.bind(transport + "://" + ip + ":" + config["iopub_port"].asString());
_control_socket.bind(transport + "://" + ip + ":" + config["control_port"].asString());
_stdin_socket.bind(transport + "://" + ip + ":" + config["stdin_port"].asString());
_shell_socket.bind(transport + "://" + ip + ":" + config["shell_port"].asString());
_engine_socket.bind("inproc://engine");
}
void YacasKernel::run()
{
zmqpp::poller poller;
poller.add(_hb_socket);
poller.add(_control_socket);
poller.add(_stdin_socket);
poller.add(_shell_socket);
poller.add(_iopub_socket);
poller.add(_engine_socket);
for (;;) {
poller.poll();
if (poller.has_input(_hb_socket)) {
zmqpp::message msg;
_hb_socket.receive(msg);
_hb_socket.send(msg);
}
if (poller.has_input(_shell_socket)) {
zmqpp::message msg;
_shell_socket.receive(msg);
_handle_shell(std::move(msg));
}
if (poller.has_input(_engine_socket)) {
zmqpp::message msg;
_engine_socket.receive(msg);
_handle_engine(std::move(msg));
}
}
}
std::string YacasKernel::_signature(const zmqpp::message& msg)
{
std::string header_buf;
msg.get(header_buf, 3);
std::string parent_header_buf;
msg.get(parent_header_buf, 4);
std::string metadata_buf;
msg.get(metadata_buf, 5);
std::string content_buf;
msg.get(content_buf, 6);
HMAC_SHA256 auth(_auth);
auth.update(header_buf);
auth.update(parent_header_buf);
auth.update(metadata_buf);
auth.update(content_buf);
return auth.hexdigest();
}
void YacasKernel::_send(zmqpp::socket& socket, const std::string& msg_type,
const std::string& content_buf, const std::string& parent_header_buf,
const std::string& metadata_buf, const std::string& identities_buf)
{
Json::Value header;
header["username"] = "kernel";
header["version"] = "5.0";
header["session"] = boost::uuids::to_string(_uuid);
header["date"] = now();
header["msg_id"] = boost::uuids::to_string(_uuid_gen());
header["msg_type"] = msg_type;
Json::StreamWriterBuilder builder;
std::string header_buf = Json::writeString(builder, header);
HMAC_SHA256 auth(_auth);
auth.update(header_buf);
auth.update(parent_header_buf);
auth.update(metadata_buf);
auth.update(content_buf);
zmqpp::message msg;
msg.add(identities_buf);
msg.add("<IDS|MSG>");
msg.add(auth.hexdigest());
msg.add(header_buf);
msg.add(parent_header_buf);
msg.add(metadata_buf);
msg.add(content_buf);
socket.send(msg);
}
void YacasKernel::_handle_shell(zmqpp::message&& msg)
{
Json::StreamWriterBuilder builder;
std::string identities_buf;
msg.get(identities_buf, 0);
std::string signature_buf;
msg.get(signature_buf, 2);
std::string header_buf;
msg.get(header_buf, 3);
std::string parent_header_buf;
msg.get(parent_header_buf, 4);
std::string metadata_buf;
msg.get(metadata_buf, 5);
std::string content_buf;
msg.get(content_buf, 6);
if (_signature(msg) != signature_buf)
throw std::runtime_error("invalid signature");
Json::Reader reader;
Json::Value header;
reader.parse(header_buf, header);
Json::Value content;
reader.parse(content_buf, content);
if (header["msg_type"] == "kernel_info_request") {
Json::Value language_info;
language_info["name"] = "yacas";
language_info["version"] = "1.3.6";
language_info["mimetype"] = "text/x-yacas";
language_info["file_extension"] = ".ys";
Json::Value reply_content;
reply_content["protocol_version"] = "5.0";
reply_content["implementation"] = "yacas_kernel";
reply_content["implementation_version"] = "0.1";
reply_content["language_info"] = language_info;
reply_content["banner"] = "yacas_kernel 0.1";
_send(_shell_socket, "kernel_info_reply", Json::writeString(builder, reply_content), header_buf, "{}", identities_buf);
}
if (header["msg_type"] == "execute_request") {
_execute_requests.insert(std::make_pair(_execution_count, std::move(msg)));
_engine.submit(_execution_count, content["code"].asString());
_execution_count += 1;
}
}
void YacasKernel::_handle_engine(const zmqpp::message& msg)
{
std::string task_info_buf;
msg.get(task_info_buf, 0);
Json::Value task_info;
Json::Reader().parse(task_info_buf, task_info);
const zmqpp::message& execute_request = _execute_requests[task_info["id"].asUInt64()];
std::string identities_buf;
execute_request.get(identities_buf, 0);
std::string header_buf;
execute_request.get(header_buf, 3);
std::string content_buf;
execute_request.get(content_buf, 6);
Json::StreamWriterBuilder builder;
if (task_info.isMember("error")) {
Json::Value reply_content;
reply_content["status"] = "error";
reply_content["execution_count"] = task_info["id"];
reply_content["ename"] = Json::Value();
reply_content["evalue"] = Json::Value();
reply_content["traceback"].append(task_info["error"]);
_send(_shell_socket, "execute_reply", Json::writeString(builder, reply_content), header_buf, "{}", identities_buf);
Json::Value error_content;
error_content["execution_count"] = task_info["id"];
error_content["ename"] = Json::Value();
error_content["evalue"] = Json::Value();
error_content["traceback"].append(task_info["error"]);
_send(_iopub_socket, "error", Json::writeString(builder, error_content), header_buf, "{}", identities_buf);
} else {
Json::Value content_data;
content_data["text/plain"] = task_info["result"];
Json::Value reply_content;
reply_content["status"] = "ok";
reply_content["execution_count"] = task_info["id"];
reply_content["data"] = content_data;
_send(_shell_socket, "execute_result", Json::writeString(builder, reply_content), header_buf, "{}", identities_buf);
Json::Value result_content;
result_content["execution_count"] = task_info["id"];
result_content["data"] = content_data;
result_content["metadata"] = "{}";
_send(_iopub_socket, "execute_result", Json::writeString(builder, result_content), header_buf, "{}", identities_buf);
}
}
<commit_msg>display side-effects of calculations<commit_after>/*
* This file is part of yacas_kernel.
* Yacas is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesset General Public License as
* published by the Free Software Foundation, either version 2.1
* of the License, or (at your option) any later version.
*
* Yacas is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with yacas_kernel. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* File: yacas_kernel.cpp
* Author: mazur
*
* Created on November 6, 2015, 3:10 PM
*/
#include "yacas_kernel.hpp"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <iostream>
#include <fstream>
#include <string>
namespace {
std::string now()
{
using namespace boost::posix_time;
return to_iso_extended_string(microsec_clock::local_time());
}
}
YacasKernel::YacasKernel(const std::string& scripts_path, const Json::Value& config):
_uuid(_uuid_gen()),
_hb_socket(_ctx, zmqpp::socket_type::reply),
_iopub_socket(_ctx, zmqpp::socket_type::publish),
_control_socket(_ctx, zmqpp::socket_type::router),
_stdin_socket(_ctx, zmqpp::socket_type::router),
_shell_socket(_ctx, zmqpp::socket_type::router),
_engine_socket(_ctx, zmqpp::socket_type::pair),
_auth(config["key"].asString()),
_execution_count(1),
_yacas(new CYacas(_side_effects)),
_engine(scripts_path, _ctx, "inproc://engine")
{
const std::string transport = config["transport"].asString();
const std::string ip = config["ip"].asString();
_hb_socket.bind(transport + "://" + ip + ":" + config["hb_port"].asString());
_iopub_socket.bind(transport + "://" + ip + ":" + config["iopub_port"].asString());
_control_socket.bind(transport + "://" + ip + ":" + config["control_port"].asString());
_stdin_socket.bind(transport + "://" + ip + ":" + config["stdin_port"].asString());
_shell_socket.bind(transport + "://" + ip + ":" + config["shell_port"].asString());
_engine_socket.bind("inproc://engine");
}
void YacasKernel::run()
{
zmqpp::poller poller;
poller.add(_hb_socket);
poller.add(_control_socket);
poller.add(_stdin_socket);
poller.add(_shell_socket);
poller.add(_iopub_socket);
poller.add(_engine_socket);
for (;;) {
poller.poll();
if (poller.has_input(_hb_socket)) {
zmqpp::message msg;
_hb_socket.receive(msg);
_hb_socket.send(msg);
}
if (poller.has_input(_shell_socket)) {
zmqpp::message msg;
_shell_socket.receive(msg);
_handle_shell(std::move(msg));
}
if (poller.has_input(_engine_socket)) {
zmqpp::message msg;
_engine_socket.receive(msg);
_handle_engine(std::move(msg));
}
}
}
std::string YacasKernel::_signature(const zmqpp::message& msg)
{
std::string header_buf;
msg.get(header_buf, 3);
std::string parent_header_buf;
msg.get(parent_header_buf, 4);
std::string metadata_buf;
msg.get(metadata_buf, 5);
std::string content_buf;
msg.get(content_buf, 6);
HMAC_SHA256 auth(_auth);
auth.update(header_buf);
auth.update(parent_header_buf);
auth.update(metadata_buf);
auth.update(content_buf);
return auth.hexdigest();
}
void YacasKernel::_send(zmqpp::socket& socket, const std::string& msg_type,
const std::string& content_buf, const std::string& parent_header_buf,
const std::string& metadata_buf, const std::string& identities_buf)
{
Json::Value header;
header["username"] = "kernel";
header["version"] = "5.0";
header["session"] = boost::uuids::to_string(_uuid);
header["date"] = now();
header["msg_id"] = boost::uuids::to_string(_uuid_gen());
header["msg_type"] = msg_type;
Json::StreamWriterBuilder builder;
std::string header_buf = Json::writeString(builder, header);
HMAC_SHA256 auth(_auth);
auth.update(header_buf);
auth.update(parent_header_buf);
auth.update(metadata_buf);
auth.update(content_buf);
zmqpp::message msg;
msg.add(identities_buf);
msg.add("<IDS|MSG>");
msg.add(auth.hexdigest());
msg.add(header_buf);
msg.add(parent_header_buf);
msg.add(metadata_buf);
msg.add(content_buf);
socket.send(msg);
}
void YacasKernel::_handle_shell(zmqpp::message&& msg)
{
Json::StreamWriterBuilder builder;
std::string identities_buf;
msg.get(identities_buf, 0);
std::string signature_buf;
msg.get(signature_buf, 2);
std::string header_buf;
msg.get(header_buf, 3);
std::string parent_header_buf;
msg.get(parent_header_buf, 4);
std::string metadata_buf;
msg.get(metadata_buf, 5);
std::string content_buf;
msg.get(content_buf, 6);
if (_signature(msg) != signature_buf)
throw std::runtime_error("invalid signature");
Json::Reader reader;
Json::Value header;
reader.parse(header_buf, header);
Json::Value content;
reader.parse(content_buf, content);
if (header["msg_type"] == "kernel_info_request") {
Json::Value language_info;
language_info["name"] = "yacas";
language_info["version"] = "1.3.6";
language_info["mimetype"] = "text/x-yacas";
language_info["file_extension"] = ".ys";
Json::Value reply_content;
reply_content["protocol_version"] = "5.0";
reply_content["implementation"] = "yacas_kernel";
reply_content["implementation_version"] = "0.1";
reply_content["language_info"] = language_info;
reply_content["banner"] = "yacas_kernel 0.1";
_send(_shell_socket, "kernel_info_reply", Json::writeString(builder, reply_content), header_buf, "{}", identities_buf);
}
if (header["msg_type"] == "execute_request") {
_execute_requests.insert(std::make_pair(_execution_count, std::move(msg)));
_engine.submit(_execution_count, content["code"].asString());
_execution_count += 1;
}
}
void YacasKernel::_handle_engine(const zmqpp::message& msg)
{
std::string task_info_buf;
msg.get(task_info_buf, 0);
Json::Value task_info;
Json::Reader().parse(task_info_buf, task_info);
const zmqpp::message& execute_request = _execute_requests[task_info["id"].asUInt64()];
std::string identities_buf;
execute_request.get(identities_buf, 0);
std::string header_buf;
execute_request.get(header_buf, 3);
std::string content_buf;
execute_request.get(content_buf, 6);
Json::StreamWriterBuilder builder;
if (task_info.isMember("side_effects")) {
Json::Value stream_content;
stream_content["name"] = "stdout";
stream_content["text"] = task_info["side_effects"];
_send(_iopub_socket, "stream", Json::writeString(builder, stream_content), header_buf, "{}", identities_buf);
}
if (task_info.isMember("error")) {
Json::Value reply_content;
reply_content["status"] = "error";
reply_content["execution_count"] = task_info["id"];
reply_content["ename"] = Json::Value();
reply_content["evalue"] = Json::Value();
reply_content["traceback"].append(task_info["error"]);
_send(_shell_socket, "execute_reply", Json::writeString(builder, reply_content), header_buf, "{}", identities_buf);
Json::Value error_content;
error_content["execution_count"] = task_info["id"];
error_content["ename"] = Json::Value();
error_content["evalue"] = Json::Value();
error_content["traceback"].append(task_info["error"]);
_send(_iopub_socket, "error", Json::writeString(builder, error_content), header_buf, "{}", identities_buf);
} else {
Json::Value content_data;
content_data["text/plain"] = task_info["result"];
Json::Value reply_content;
reply_content["status"] = "ok";
reply_content["execution_count"] = task_info["id"];
reply_content["data"] = content_data;
_send(_shell_socket, "execute_result", Json::writeString(builder, reply_content), header_buf, "{}", identities_buf);
Json::Value result_content;
result_content["execution_count"] = task_info["id"];
result_content["data"] = content_data;
result_content["metadata"] = "{}";
_send(_iopub_socket, "execute_result", Json::writeString(builder, result_content), header_buf, "{}", identities_buf);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2014 The Crashpad 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 "util/file/file_io.h"
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/posix/eintr_wrapper.h"
namespace crashpad {
namespace {
FileHandle OpenFileForOutput(int rdwr_or_wronly,
const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
int flags = O_NOCTTY | O_CLOEXEC;
DCHECK(rdwr_or_wronly & (O_RDWR | O_WRONLY));
DCHECK_EQ(rdwr_or_wronly & ~(O_RDWR | O_WRONLY), 0);
flags |= rdwr_or_wronly;
switch (mode) {
case FileWriteMode::kReuseOrFail:
break;
case FileWriteMode::kReuseOrCreate:
flags |= O_CREAT;
break;
case FileWriteMode::kTruncateOrCreate:
flags |= O_CREAT | O_TRUNC;
break;
case FileWriteMode::kCreateOrFail:
flags |= O_CREAT | O_EXCL;
break;
}
return HANDLE_EINTR(
open(path.value().c_str(),
flags,
permissions == FilePermissions::kWorldReadable ? 0644 : 0600));
}
} // namespace
const char kNativeReadFunctionName[] = "read";
const char kNativeWriteFunctionName[] = "write";
// TODO(mark): Handle > ssize_t-sized reads and writes if necessary. The
// standard leaves this implementation-defined. Some systems return EINVAL in
// this case. ReadFile() and WriteFile() could enforce this behavior.
FileOperationResult ReadFile(FileHandle file, void* buffer, size_t size) {
FileOperationResult bytes = HANDLE_EINTR(read(file, buffer, size));
if (bytes < 0) {
return -1;
}
DCHECK_LE(static_cast<size_t>(bytes), size);
return bytes;
}
FileOperationResult WriteFile(FileHandle file,
const void* buffer,
size_t size) {
const char* buffer_c = static_cast<const char*>(buffer);
FileOperationResult total_bytes = 0;
while (size > 0) {
FileOperationResult bytes = HANDLE_EINTR(write(file, buffer_c, size));
if (bytes < 0) {
return -1;
}
DCHECK_NE(bytes, 0);
DCHECK_LE(static_cast<size_t>(bytes), size);
buffer_c += bytes;
size -= bytes;
total_bytes += bytes;
}
return total_bytes;
}
FileHandle OpenFileForRead(const base::FilePath& path) {
return HANDLE_EINTR(
open(path.value().c_str(), O_RDONLY | O_NOCTTY | O_CLOEXEC));
}
FileHandle OpenFileForWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
return OpenFileForOutput(O_WRONLY, path, mode, permissions);
}
FileHandle OpenFileForReadAndWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
return OpenFileForOutput(O_RDWR, path, mode, permissions);
}
FileHandle LoggingOpenFileForRead(const base::FilePath& path) {
FileHandle fd = OpenFileForRead(path);
PLOG_IF(ERROR, fd < 0) << "open " << path.value();
return fd;
}
FileHandle LoggingOpenFileForWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
FileHandle fd = OpenFileForWrite(path, mode, permissions);
PLOG_IF(ERROR, fd < 0) << "open " << path.value();
return fd;
}
FileHandle LoggingOpenFileForReadAndWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
FileHandle fd = OpenFileForReadAndWrite(path, mode, permissions);
PLOG_IF(ERROR, fd < 0) << "open " << path.value();
return fd;
}
bool LoggingLockFile(FileHandle file, FileLocking locking) {
int operation = (locking == FileLocking::kShared) ? LOCK_SH : LOCK_EX;
int rv = HANDLE_EINTR(flock(file, operation));
PLOG_IF(ERROR, rv != 0) << "flock";
return rv == 0;
}
bool LoggingUnlockFile(FileHandle file) {
int rv = flock(file, LOCK_UN);
PLOG_IF(ERROR, rv != 0) << "flock";
return rv == 0;
}
FileOffset LoggingSeekFile(FileHandle file, FileOffset offset, int whence) {
off_t rv = lseek(file, offset, whence);
PLOG_IF(ERROR, rv < 0) << "lseek";
return rv;
}
bool LoggingTruncateFile(FileHandle file) {
if (HANDLE_EINTR(ftruncate(file, 0)) != 0) {
PLOG(ERROR) << "ftruncate";
return false;
}
return true;
}
bool LoggingCloseFile(FileHandle file) {
int rv = IGNORE_EINTR(close(file));
PLOG_IF(ERROR, rv != 0) << "close";
return rv == 0;
}
FileOffset LoggingFileSizeByHandle(FileHandle file) {
struct stat st;
if (fstat(file, &st) != 0) {
PLOG(ERROR) << "fstat";
return -1;
}
return st.st_size;
}
FileHandle StdioFileHandle(StdioStream stdio_stream) {
switch (stdio_stream) {
case StdioStream::kStandardInput:
return STDIN_FILENO;
case StdioStream::kStandardOutput:
return STDOUT_FILENO;
case StdioStream::kStandardError:
return STDERR_FILENO;
}
}
} // namespace crashpad
<commit_msg>posix: Fix StdioFileHandle() for GCC<commit_after>// Copyright 2014 The Crashpad 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 "util/file/file_io.h"
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/posix/eintr_wrapper.h"
namespace crashpad {
namespace {
FileHandle OpenFileForOutput(int rdwr_or_wronly,
const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
int flags = O_NOCTTY | O_CLOEXEC;
DCHECK(rdwr_or_wronly & (O_RDWR | O_WRONLY));
DCHECK_EQ(rdwr_or_wronly & ~(O_RDWR | O_WRONLY), 0);
flags |= rdwr_or_wronly;
switch (mode) {
case FileWriteMode::kReuseOrFail:
break;
case FileWriteMode::kReuseOrCreate:
flags |= O_CREAT;
break;
case FileWriteMode::kTruncateOrCreate:
flags |= O_CREAT | O_TRUNC;
break;
case FileWriteMode::kCreateOrFail:
flags |= O_CREAT | O_EXCL;
break;
}
return HANDLE_EINTR(
open(path.value().c_str(),
flags,
permissions == FilePermissions::kWorldReadable ? 0644 : 0600));
}
} // namespace
const char kNativeReadFunctionName[] = "read";
const char kNativeWriteFunctionName[] = "write";
// TODO(mark): Handle > ssize_t-sized reads and writes if necessary. The
// standard leaves this implementation-defined. Some systems return EINVAL in
// this case. ReadFile() and WriteFile() could enforce this behavior.
FileOperationResult ReadFile(FileHandle file, void* buffer, size_t size) {
FileOperationResult bytes = HANDLE_EINTR(read(file, buffer, size));
if (bytes < 0) {
return -1;
}
DCHECK_LE(static_cast<size_t>(bytes), size);
return bytes;
}
FileOperationResult WriteFile(FileHandle file,
const void* buffer,
size_t size) {
const char* buffer_c = static_cast<const char*>(buffer);
FileOperationResult total_bytes = 0;
while (size > 0) {
FileOperationResult bytes = HANDLE_EINTR(write(file, buffer_c, size));
if (bytes < 0) {
return -1;
}
DCHECK_NE(bytes, 0);
DCHECK_LE(static_cast<size_t>(bytes), size);
buffer_c += bytes;
size -= bytes;
total_bytes += bytes;
}
return total_bytes;
}
FileHandle OpenFileForRead(const base::FilePath& path) {
return HANDLE_EINTR(
open(path.value().c_str(), O_RDONLY | O_NOCTTY | O_CLOEXEC));
}
FileHandle OpenFileForWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
return OpenFileForOutput(O_WRONLY, path, mode, permissions);
}
FileHandle OpenFileForReadAndWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
return OpenFileForOutput(O_RDWR, path, mode, permissions);
}
FileHandle LoggingOpenFileForRead(const base::FilePath& path) {
FileHandle fd = OpenFileForRead(path);
PLOG_IF(ERROR, fd < 0) << "open " << path.value();
return fd;
}
FileHandle LoggingOpenFileForWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
FileHandle fd = OpenFileForWrite(path, mode, permissions);
PLOG_IF(ERROR, fd < 0) << "open " << path.value();
return fd;
}
FileHandle LoggingOpenFileForReadAndWrite(const base::FilePath& path,
FileWriteMode mode,
FilePermissions permissions) {
FileHandle fd = OpenFileForReadAndWrite(path, mode, permissions);
PLOG_IF(ERROR, fd < 0) << "open " << path.value();
return fd;
}
bool LoggingLockFile(FileHandle file, FileLocking locking) {
int operation = (locking == FileLocking::kShared) ? LOCK_SH : LOCK_EX;
int rv = HANDLE_EINTR(flock(file, operation));
PLOG_IF(ERROR, rv != 0) << "flock";
return rv == 0;
}
bool LoggingUnlockFile(FileHandle file) {
int rv = flock(file, LOCK_UN);
PLOG_IF(ERROR, rv != 0) << "flock";
return rv == 0;
}
FileOffset LoggingSeekFile(FileHandle file, FileOffset offset, int whence) {
off_t rv = lseek(file, offset, whence);
PLOG_IF(ERROR, rv < 0) << "lseek";
return rv;
}
bool LoggingTruncateFile(FileHandle file) {
if (HANDLE_EINTR(ftruncate(file, 0)) != 0) {
PLOG(ERROR) << "ftruncate";
return false;
}
return true;
}
bool LoggingCloseFile(FileHandle file) {
int rv = IGNORE_EINTR(close(file));
PLOG_IF(ERROR, rv != 0) << "close";
return rv == 0;
}
FileOffset LoggingFileSizeByHandle(FileHandle file) {
struct stat st;
if (fstat(file, &st) != 0) {
PLOG(ERROR) << "fstat";
return -1;
}
return st.st_size;
}
FileHandle StdioFileHandle(StdioStream stdio_stream) {
switch (stdio_stream) {
case StdioStream::kStandardInput:
return STDIN_FILENO;
case StdioStream::kStandardOutput:
return STDOUT_FILENO;
case StdioStream::kStandardError:
return STDERR_FILENO;
}
NOTREACHED();
return kInvalidFileHandle;
}
} // namespace crashpad
<|endoftext|>
|
<commit_before>#ifndef SLICE_HPP
#define SLICE_HPP
#include "iterator_range.hpp"
#include "wrap_iter.hpp"
#include <iterator>
#include <cassert>
namespace iter {
template <typename Container>
auto slice(
Container && container,
typename std::iterator_traits<decltype(std::begin(container))>::difference_type begin,
typename std::iterator_traits<decltype(std::begin(container))>::difference_type end,
typename std::iterator_traits<decltype(std::begin(container))>::difference_type step = 1
) -> iterator_range<wrap_iter<decltype(std::begin(container))>>
{
//it seems like you can handle negative and positive ranges the same
//kept both checks to make checking for invalid slice more readable
if (begin > end && step < 0) {
typename std::iterator_traits<decltype(std::begin(container))>::difference_type new_end = end - ((end - begin) % step);
auto begin_iter = std::begin(container);
std::advance(begin_iter,begin);
auto end_iter = std::begin(container);
std::advance(end_iter,new_end);
return iterator_range<wrap_iter<decltype(std::begin(container))>>(
make_wrap_iter(begin_iter,step),
make_wrap_iter(end_iter,step));
}
else if (begin <= end && step > 0) {
typename std::iterator_traits<decltype(std::begin(container))>::difference_type new_end = end - ((end - begin) % step);
auto begin_iter = std::begin(container);
std::advance(begin_iter,begin);
auto end_iter = std::begin(container);
std::advance(end_iter,new_end);
return iterator_range<wrap_iter<decltype(std::begin(container))>>(
make_wrap_iter(begin_iter,step),
make_wrap_iter(end_iter,step));
}
else {//return an empty range for invalid slice
auto empty = std::begin(container);
std::advance(empty,begin);
return iterator_range<wrap_iter<decltype(std::begin(container))>>(
make_wrap_iter(empty,step),
make_wrap_iter(empty,step));
}
}
//only give the end as an arg and assume step is 1 and begin is 0
template <typename Container>
auto slice(
Container && container,
typename std::iterator_traits<decltype(std::begin(container))>::difference_type end
) -> iterator_range<wrap_iter<decltype(std::begin(container))>>
{
return slice(std::forward<Container>(container),0,end);
}
}
#endif //SLICE_HPP
<commit_msg>Changes difference type to a template Argument<commit_after>#ifndef SLICE_HPP
#define SLICE_HPP
#include "iterator_range.hpp"
#include "wrap_iter.hpp"
#include <iterator>
#include <cassert>
namespace iter {
template <typename Container, typename DifferenceType>
auto slice( Container && container,
DifferenceType begin,
DifferenceType end,
DifferenceType step = 1
) -> iterator_range<wrap_iter<decltype(std::begin(container))>>
{
//it seems like you can handle negative and positive ranges the same
//kept both checks to make checking for invalid slice more readable
if (begin > end && step < 0) {
DifferenceType new_end = end - ((end - begin) % step);
auto begin_iter = std::begin(container);
std::advance(begin_iter,begin);
auto end_iter = std::begin(container);
std::advance(end_iter,new_end);
return iterator_range<wrap_iter<decltype(std::begin(container))>>(
make_wrap_iter(begin_iter,step),
make_wrap_iter(end_iter,step));
}
else if (begin <= end && step > 0) {
DifferenceType new_end = end - ((end - begin) % step);
auto begin_iter = std::begin(container);
std::advance(begin_iter,begin);
auto end_iter = std::begin(container);
std::advance(end_iter,new_end);
return iterator_range<wrap_iter<decltype(std::begin(container))>>(
make_wrap_iter(begin_iter,step),
make_wrap_iter(end_iter,step));
}
else {//return an empty range for invalid slice
auto empty = std::begin(container);
std::advance(empty,begin);
return iterator_range<wrap_iter<decltype(std::begin(container))>>(
make_wrap_iter(empty,step),
make_wrap_iter(empty,step));
}
}
//only give the end as an arg and assume step is 1 and begin is 0
template <typename Container, typename DifferenceType>
auto slice(
Container && container,
DifferenceType end
) -> iterator_range<wrap_iter<decltype(std::begin(container))>>
{
return slice(std::forward<Container>(container),0,end);
}
}
#endif //SLICE_HPP
<|endoftext|>
|
<commit_before>/* Chipdisk demo -- generate 8-bit PWM procedurally generated music
*
* Hook up a speaker or headphones between pins 0 and 1 -- this uses a bridge drive (push/pull) topology
*
* Touch pin 4 for "Previous Song"
* Touch pin 5 for "Next Song"
*/
#include "Arduino.h"
#include "ChibiOS.h"
#include "kl02.h"
#include "memio.h"
// The system is running off of a 32.768 kHz crystal going through
// a 1464x FLL multiplier, giving a system frequency of
// 47.972352 MHz.
// The number of ticks that the sound system has gone through.
// Overflows after about three days, at 14 kHz.
volatile uint32_t global_tick_counter;
// The next sample to be played, nominally between -128 and 127
static volatile int32_t next_sample;
// Nonzero if a sample has been queued, zero if the sample buffer is empty.
static volatile uint8_t sample_queued;
struct song
{
uint8_t (*generator)(uint32_t t);
uint8_t delay_loops;
};
// mu6k http://www.youtube.com/watch?v=tCRPUv8V22o 32.0 kHz
static uint8_t mu6k_generator(uint32_t t)
{
uint32_t y = 0;
uint32_t x = 0;
return (((int)(3e3 / (y = t & 16383)) & 1) * 35) +
(x = t * ("6689"[t >> 16 & 3] & 15) / 24 & 127) * y / 4e4 +
(((t >> 8 ^ t >> 10) | t >> 14 | x) & 63);
}
// kb 2011-10-04 http://pouet.net/topic.php?which=8357&page=8 44kHz
static uint8_t kb1_generator(uint32_t t)
{
return ((t / 2 * (15 & (0x234568a0 >> (t >> 8 & 28)))) | t / 2 >> (t >> 11) ^ t >> 12) + (t / 16 & t & 24);
}
// stephth 2011-10-03 http://news.ycombinator.com/item?id=3063359
static uint8_t stephth_generator(uint32_t t)
{
return (t * 9 & t >> 4 | t * 5 & t >> 7 | t * 3 & t / 1024) - 1;
}
// ryg 2011-10-10 http://www.youtube.com/watch?v=tCRPUv8V22o 44.1 kHz
static uint8_t ryg_generator(uint32_t t)
{
return ((t * ("36364689"[t >> 13 & 7] & 15)) / 12 & 128) + (((((t >> 12) ^ (t >> 12) - 2) % 11 * t) / 4 | t >> 13) & 127);
}
// xpansive 2011-09-29 http://pouet.net/topic.php?which=8357&page=2 "Lost in Space"
static uint8_t xpansive_generator(uint32_t t)
{
return ((t * (t >> 8 | t >> 9) & 46 & t >> 8)) ^ (t & t >> 13 | t >> 6);
}
// rez 2011-10-05 http://pouet.net/topic.php?which=8357&page=11 js-only optimized by ryg
static uint8_t rez_generator(uint32_t t)
{
return t * (1 + "4451"[t >> 13 & 3] / 10) & t >> 9 + ((int)(t * 0.003) & 3);
}
// visy 2011-10-06 http://pouet.net/topic.php?which=8357&page=13
static uint8_t visy_generator(uint32_t t)
{
return (t % 25 - (t >> 2 | t * 15 | t % 227) - t >> 3) | ((t >> 5) & (t << 5) * 1663 | (t >> 3) % 1544) / (t % 17 | t % 2048);
}
// bear @ celephais
static uint8_t bear_gen(uint32_t t)
{
return t >> 6 ^ t & 37 | t + (t ^ t >> 11) - t * ((t % 24 ? 2 : 6) & t >> 11) ^ t << 1 & (t & 598 ? t >> 4 : t >> 10);
}
static struct song songs[] = {
{
.generator = mu6k_generator,
.delay_loops = 3,
},
{
.generator = kb1_generator,
.delay_loops = 1,
},
{
.generator = stephth_generator,
.delay_loops = 14,
},
{
.generator = ryg_generator,
.delay_loops = 1,
},
{
.generator = xpansive_generator,
.delay_loops = 13,
},
{
.generator = rez_generator,
.delay_loops = 13,
},
{
.generator = visy_generator,
.delay_loops = 13,
},
{
.generator = bear_gen,
.delay_loops = 13,
}};
static struct song *current_song = &songs[0];
static uint32_t current_song_idx = 0;
static int pwm0_stable_timer(void)
{
static int loops = 0;
/* Reset the timer IRQ, to allow us to fire again next time */
writel(TPM0_STATUS_CH1F | TPM0_STATUS_CH0F | TPM0_STATUS_TOF, TPM0_STATUS);
if (loops++ > current_song->delay_loops)
{
int32_t scaled_sample = next_sample + 130;
if (scaled_sample > 255)
scaled_sample = 255;
if (scaled_sample <= 0)
scaled_sample = 1;
writel(scaled_sample, TPM0_C1V);
writel(scaled_sample, TPM0_C0V);
loops = 0;
sample_queued = 0;
global_tick_counter++;
}
return 0;
}
static void prepare_pwm()
{
// Write dummy values out, to configure PWM mux
pinMode(0, OUTPUT);
analogWrite(0, 63);
pinMode(1, OUTPUT);
analogWrite(1, 63);
// Disable TPM0, allowing us to configure it
writel(0, TPM0_SC);
// Also disable both channels, which are running from the
// calls to analogWrite() above
writel(0, TPM0_C0SC);
writel(0, TPM0_C1SC);
// Configure the TPM to use the MCGFLLCLK (~32 MHz?)
writel(readl(SIM_SOPT2) | (1 << 24), SIM_SOPT2);
// We've picked pin 0, which is on TPM0_CH1
writel(255, TPM0_MOD);
writel(0, TPM0_CNT);
writel(TPM0_C0SC_MSB | TPM0_C0SC_ELSB, TPM0_C0SC);
writel(TPM0_C1SC_MSB | TPM0_C1SC_ELSA, TPM0_C1SC);
writel(100, TPM0_C1V);
writel(100, TPM0_C0V);
writel(TPM0_SC_TOF | TPM0_SC_TOIE | TPM0_SC_CMOD(1) | TPM0_SC_PS(0), TPM0_SC); // Enable TPM0
/* Enable the IRQ in the system-wide interrupt table */
attachFastInterrupt(PWM0_IRQ, pwm0_stable_timer);
}
static void touch_thread(void *ignored)
{
uint32_t start_time;
const uint32_t next_pin = 5, prev_pin = 4;
static uint8_t last_state;
while (1)
{
// Set pin 1 high.
pinMode(next_pin, OUTPUT);
pinMode(prev_pin, OUTPUT);
digitalWrite(next_pin, HIGH);
digitalWrite(prev_pin, HIGH);
// Wait a moment for it to charge.
delay(2);
// Set the pin back to an input and wait for it to change.
start_time = micros();
pinMode(next_pin, INPUT);
pinMode(prev_pin, INPUT);
uint32_t end_time_next = 0;
uint32_t end_time_prev = 0;
uint8_t next_val, prev_val;
do
{
next_val = digitalRead(next_pin);
prev_val = digitalRead(prev_pin);
if (end_time_next == 0 && !next_val)
{
end_time_next = micros();
}
if (end_time_prev == 0 && !prev_val)
end_time_prev = micros();
} while (next_val || prev_val);
if ((end_time_next - start_time) > 100)
{
if (last_state != 1)
{
current_song_idx++;
if (current_song_idx >= (sizeof(songs) / sizeof(*songs)))
current_song_idx = 0;
current_song = &songs[current_song_idx];
global_tick_counter = 0;
}
last_state = 1;
}
else if ((end_time_prev - start_time) > 100)
{
if (last_state != 1)
{
if (current_song_idx == 0)
current_song_idx = (sizeof(songs) / sizeof(*songs)) - 1;
else
current_song_idx--;
current_song = &songs[current_song_idx];
global_tick_counter = 0;
}
last_state = 1;
}
else
last_state = 0;
delay(50);
}
}
void setup(void)
{
prepare_pwm();
enableInterrupt(PWM0_IRQ);
createThreadFromHeap(64, 120, touch_thread, NULL);
}
void loop(void)
{
// If a sample is still in the buffer, don't do anything.
if (sample_queued)
return;
next_sample = (current_song->generator(global_tick_counter) & 0xff) - 128;
sample_queued = 1;
}
<commit_msg>remove .cpp version, oops<commit_after><|endoftext|>
|
<commit_before>/////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
// Profile system
// Created 13/8/02
// Jason Boettcher
#include <assert.h>
#include "LieroX.h"
#include "ProfileSystem.h"
#include "EndianSwap.h"
#include "GfxPrimitives.h"
#include "FindFile.h"
#include "StringUtils.h"
#include "FileUtils.h"
profile_t *tProfiles = NULL;
profile_t* FindFirstHumanProfile() {
for(profile_t *p = tProfiles; p; p = p->tNext) {
if(p->iType == PRF_HUMAN->toInt())
return p;
}
return NULL;
}
std::string FindFirstHumanProfileName() {
profile_t* p = FindFirstHumanProfile();
if(p) return p->sName;
return "";
}
///////////////////
// Load the profiles
int LoadProfiles()
{
int i;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","rb");
if(fp == NULL) {
// Add the default players
AddDefaultPlayers();
return false;
}
//
// Header
//
// Check ID
std::string id;
fread_fixedwidthstr<32>(id, fp);
if(id != "lx:profile") {
errors << "Could not load profiles: \"" << id << "\" is not equal to \"lx:profile\"" << endl;
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Check version
int ver = 0;
fread_compat(ver, sizeof(int), 1, fp);
EndianSwap(ver);
if(ver != PROFILE_VERSION) {
std::string tmp = "Could not load profiles: \""+itoa(ver)+"\" is not equal to \""+itoa(PROFILE_VERSION)+"\"";
errors << tmp << endl;
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Get number of profiles
int num = 0;
fread_compat(num, sizeof(int), 1, fp);
EndianSwap(num);
// Safety check
if(num < 0) {
// Just leave
fclose(fp);
// Add the default players
AddDefaultPlayers();
return true;
}
// Load the profiles
for(i=0; i<num; i++)
LoadProfile(fp, i);
fclose(fp);
if(FindFirstHumanProfile())
// we must do this because most code which access the profile system expects that there is at least one human profile
AddDefaultPlayers();
return true;
}
///////////////////
// Add the default players to the list
void AddDefaultPlayers()
{
short i;
std::string buf;
// Pre-set cpu colours
Uint32 cpuColours[] = { 255,0,0, 0,255,0, 0,0,255, 255,0,255, 0,255,255, 128,128,128,
128,255,0, 0,128,255, 0,128,0 };
// Pre-set cpu difficulties
int Diff[] = {AI_EASY, AI_MEDIUM, AI_MEDIUM, AI_HARD, AI_XTREME, AI_MEDIUM, AI_EASY};
// Add the default worm
AddProfile("worm", "default.png", "", "", 100,100,255, PRF_HUMAN->toInt(),0);
// Add 7 ai players
for(i=0; i<7; i++) {
buf = "CPU "+itoa(i+1);
AddProfile(buf, "default.png", "", "", cpuColours[i*3], cpuColours[i*3+1], cpuColours[i*3+2], PRF_COMPUTER->toInt(), Diff[i]);
}
}
///////////////////
// Save the profiles
void SaveProfiles()
{
profile_t *p = tProfiles;
profile_t *pf;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
errors << "Could not open cfg/players.dat for writing" << endl;
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite_endian_compat((ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite_endian_compat((Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
}
}
///////////////////
// Shutdown & save the profiles
void ShutdownProfiles()
{
if (!tProfiles) // Profiles not loaded, don't write and empty file (and delete all user's prifiles!)
return;
profile_t *p = tProfiles;
profile_t *pf = NULL;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
errors << "Could not open cfg/players.dat for writing" << endl;
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite_endian_compat((ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite_endian_compat((Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
// Free the actual profile
assert(p);
delete p;
}
fclose(fp);
tProfiles = NULL;
}
///////////////////
// Load a profile
void LoadProfile(FILE *fp, int id)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
p->iID = id;
p->tNext = NULL;
// Name
p->sName = freadfixedcstr(fp, 32);
p->cSkin.Change(freadfixedcstr(fp, 128));
fread_compat(p->iType, sizeof(int), 1, fp);
EndianSwap(p->iType);
fread_compat(p->nDifficulty,sizeof(int), 1, fp);
EndianSwap(p->nDifficulty);
if (p->iType == PRF_COMPUTER->toInt())
p->cSkin.setBotIcon(p->nDifficulty);
// Multiplayer
p->sUsername = freadfixedcstr(fp,16);
p->sPassword = freadfixedcstr(fp,16);
// Colour
fread_compat(p->R, sizeof(Uint8), 1, fp);
EndianSwap(p->R);
fread_compat(p->G, sizeof(Uint8), 1, fp);
EndianSwap(p->G);
fread_compat(p->B, sizeof(Uint8), 1, fp);
EndianSwap(p->B);
p->cSkin.setDefaultColor(Color(p->R, p->G, p->B));
p->cSkin.Colorize(p->cSkin.getDefaultColor());
// Weapons
for(int i=0; i<5; i++)
p->sWeaponSlots[i] = freadfixedcstr(fp,64);
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
for(;pf;pf = pf->tNext) {
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
}
}
else
tProfiles = p;
}
///////////////////
// Save a profile
void SaveProfile(FILE *fp, profile_t *p)
{
// Name & Type
fwrite(p->sName, 32, fp);
fwrite(p->cSkin.getFileName(), 128,fp);
fwrite_endian_compat((p->iType), sizeof(int), 1, fp);
fwrite_endian_compat((p->nDifficulty),sizeof(int), 1, fp);
// Multiplayer
fwrite(p->sUsername, 16, fp);
fwrite(p->sPassword, 16, fp);
// Colour
fwrite(&p->R, 1, 1, fp);
fwrite(&p->G, 1, 1, fp);
fwrite(&p->B, 1, 1, fp);
// Weapons
for(int i=0; i<5; i++)
fwrite(p->sWeaponSlots[i], 64, fp);
}
///////////////////
// Delete a profile
void DeleteProfile(int id)
{
profile_t *prv = NULL;
profile_t *p = tProfiles;
// Find it's previous
for(; p; p=p->tNext) {
if(p->iID == id) {
// Set the previous profiles next to my next one
// Thus removing me from the list
if(prv)
prv->tNext = p->tNext;
else
tProfiles = p->tNext;
// Free me
delete p;
break;
}
prv = p;
}
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Add a profile to the list
void AddProfile(const std::string& name, const std::string& skin, const std::string& username, const std::string& password, int R, int G, int B, int type, int difficulty)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
// Find a free id
int id = FindProfileID();
p->iID = id;
p->iType = type;
p->nDifficulty = difficulty;
p->tNext = NULL;
p->sName = name;
p->cSkin.Change(skin);
p->R = R;
p->G = G;
p->B = B;
p->cSkin.Colorize(Color(R, G, B));
p->sUsername = username;
p->sPassword = password;
// Default weapons
p->sWeaponSlots[0] = "minigun";
p->sWeaponSlots[1] = "super shotgun";
p->sWeaponSlots[2] = "blaster";
p->sWeaponSlots[3] = "gauss gun";
p->sWeaponSlots[4] = "big nuke";
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
profile_t *prv = NULL;
for(;pf;pf = pf->tNext) {
// If we are human, we need to insert ourselves into the list before the ai players
if(p->iType == PRF_HUMAN->toInt()) {
if(pf->iType == PRF_COMPUTER->toInt()) {
p->tNext = pf;
if(prv)
prv->tNext = p;
else
// Must be first one
tProfiles = p;
break;
}
}
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
prv = pf;
}
}
else
tProfiles = p;
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Find a free profile id
int FindProfileID()
{
profile_t *p = tProfiles;
int id = -1;
for(; p; p=p->tNext)
id = p->iID;
return id+1;
}
///////////////////
// Get the profiles
profile_t *GetProfiles()
{
return tProfiles;
}
///////////////////
// Find a profile based on id
profile_t *FindProfile(int id)
{
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->iID == id)
return p;
}
return NULL;
}
profile_t *FindProfile(const std::string& name) {
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->sName == name)
return p;
}
return NULL;
}
std::string FindFirstCPUProfileName() {
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->iType == PRF_COMPUTER->toInt())
return p->sName;
}
return "";
}
<commit_msg>small fix<commit_after>/////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
// Profile system
// Created 13/8/02
// Jason Boettcher
#include <assert.h>
#include "LieroX.h"
#include "ProfileSystem.h"
#include "EndianSwap.h"
#include "GfxPrimitives.h"
#include "FindFile.h"
#include "StringUtils.h"
#include "FileUtils.h"
profile_t *tProfiles = NULL;
profile_t* FindFirstHumanProfile() {
for(profile_t *p = tProfiles; p; p = p->tNext) {
if(p->iType == PRF_HUMAN->toInt())
return p;
}
return NULL;
}
std::string FindFirstHumanProfileName() {
profile_t* p = FindFirstHumanProfile();
if(p) return p->sName;
return "";
}
///////////////////
// Load the profiles
int LoadProfiles()
{
int i;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","rb");
if(fp == NULL) {
// Add the default players
AddDefaultPlayers();
return false;
}
//
// Header
//
// Check ID
std::string id;
fread_fixedwidthstr<32>(id, fp);
if(id != "lx:profile") {
errors << "Could not load profiles: \"" << id << "\" is not equal to \"lx:profile\"" << endl;
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Check version
int ver = 0;
fread_compat(ver, sizeof(int), 1, fp);
EndianSwap(ver);
if(ver != PROFILE_VERSION) {
std::string tmp = "Could not load profiles: \""+itoa(ver)+"\" is not equal to \""+itoa(PROFILE_VERSION)+"\"";
errors << tmp << endl;
// Add the default players
AddDefaultPlayers();
fclose(fp);
return false;
}
// Get number of profiles
int num = 0;
fread_compat(num, sizeof(int), 1, fp);
EndianSwap(num);
// Safety check
if(num < 0) {
// Just leave
fclose(fp);
// Add the default players
AddDefaultPlayers();
return true;
}
// Load the profiles
for(i=0; i<num; i++)
LoadProfile(fp, i);
fclose(fp);
if(!FindFirstHumanProfile())
// we must do this because most code which access the profile system expects that there is at least one human profile
AddDefaultPlayers();
return true;
}
///////////////////
// Add the default players to the list
void AddDefaultPlayers()
{
short i;
std::string buf;
// Pre-set cpu colours
Uint32 cpuColours[] = { 255,0,0, 0,255,0, 0,0,255, 255,0,255, 0,255,255, 128,128,128,
128,255,0, 0,128,255, 0,128,0 };
// Pre-set cpu difficulties
int Diff[] = {AI_EASY, AI_MEDIUM, AI_MEDIUM, AI_HARD, AI_XTREME, AI_MEDIUM, AI_EASY};
// Add the default worm
AddProfile("worm", "default.png", "", "", 100,100,255, PRF_HUMAN->toInt(),0);
// Add 7 ai players
for(i=0; i<7; i++) {
buf = "CPU "+itoa(i+1);
AddProfile(buf, "default.png", "", "", cpuColours[i*3], cpuColours[i*3+1], cpuColours[i*3+2], PRF_COMPUTER->toInt(), Diff[i]);
}
}
///////////////////
// Save the profiles
void SaveProfiles()
{
profile_t *p = tProfiles;
profile_t *pf;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
errors << "Could not open cfg/players.dat for writing" << endl;
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite_endian_compat((ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite_endian_compat((Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
}
}
///////////////////
// Shutdown & save the profiles
void ShutdownProfiles()
{
if (!tProfiles) // Profiles not loaded, don't write and empty file (and delete all user's prifiles!)
return;
profile_t *p = tProfiles;
profile_t *pf = NULL;
//
// Open the file
//
FILE *fp = OpenGameFile("cfg/players.dat","wb");
if(fp == NULL) {
errors << "Could not open cfg/players.dat for writing" << endl;
return;
}
// ID & Version
fwrite("lx:profile", 32, fp);
int ver = PROFILE_VERSION;
fwrite_endian_compat((ver), sizeof(int), 1, fp);
// Count how many profiles we have
int Num=0;
for(;p;p=p->tNext)
Num++;
fwrite_endian_compat((Num), sizeof(int), 1, fp);
p = tProfiles;
for(; p; p = pf) {
pf = p->tNext;
// Save the profile
SaveProfile(fp, p);
// Free the actual profile
assert(p);
delete p;
}
fclose(fp);
tProfiles = NULL;
}
///////////////////
// Load a profile
void LoadProfile(FILE *fp, int id)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
p->iID = id;
p->tNext = NULL;
// Name
p->sName = freadfixedcstr(fp, 32);
p->cSkin.Change(freadfixedcstr(fp, 128));
fread_compat(p->iType, sizeof(int), 1, fp);
EndianSwap(p->iType);
fread_compat(p->nDifficulty,sizeof(int), 1, fp);
EndianSwap(p->nDifficulty);
if (p->iType == PRF_COMPUTER->toInt())
p->cSkin.setBotIcon(p->nDifficulty);
// Multiplayer
p->sUsername = freadfixedcstr(fp,16);
p->sPassword = freadfixedcstr(fp,16);
// Colour
fread_compat(p->R, sizeof(Uint8), 1, fp);
EndianSwap(p->R);
fread_compat(p->G, sizeof(Uint8), 1, fp);
EndianSwap(p->G);
fread_compat(p->B, sizeof(Uint8), 1, fp);
EndianSwap(p->B);
p->cSkin.setDefaultColor(Color(p->R, p->G, p->B));
p->cSkin.Colorize(p->cSkin.getDefaultColor());
// Weapons
for(int i=0; i<5; i++)
p->sWeaponSlots[i] = freadfixedcstr(fp,64);
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
for(;pf;pf = pf->tNext) {
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
}
}
else
tProfiles = p;
}
///////////////////
// Save a profile
void SaveProfile(FILE *fp, profile_t *p)
{
// Name & Type
fwrite(p->sName, 32, fp);
fwrite(p->cSkin.getFileName(), 128,fp);
fwrite_endian_compat((p->iType), sizeof(int), 1, fp);
fwrite_endian_compat((p->nDifficulty),sizeof(int), 1, fp);
// Multiplayer
fwrite(p->sUsername, 16, fp);
fwrite(p->sPassword, 16, fp);
// Colour
fwrite(&p->R, 1, 1, fp);
fwrite(&p->G, 1, 1, fp);
fwrite(&p->B, 1, 1, fp);
// Weapons
for(int i=0; i<5; i++)
fwrite(p->sWeaponSlots[i], 64, fp);
}
///////////////////
// Delete a profile
void DeleteProfile(int id)
{
profile_t *prv = NULL;
profile_t *p = tProfiles;
// Find it's previous
for(; p; p=p->tNext) {
if(p->iID == id) {
// Set the previous profiles next to my next one
// Thus removing me from the list
if(prv)
prv->tNext = p->tNext;
else
tProfiles = p->tNext;
// Free me
delete p;
break;
}
prv = p;
}
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Add a profile to the list
void AddProfile(const std::string& name, const std::string& skin, const std::string& username, const std::string& password, int R, int G, int B, int type, int difficulty)
{
profile_t *p;
p = new profile_t();
if(p == NULL)
return;
// Find a free id
int id = FindProfileID();
p->iID = id;
p->iType = type;
p->nDifficulty = difficulty;
p->tNext = NULL;
p->sName = name;
p->cSkin.Change(skin);
p->R = R;
p->G = G;
p->B = B;
p->cSkin.Colorize(Color(R, G, B));
p->sUsername = username;
p->sPassword = password;
// Default weapons
p->sWeaponSlots[0] = "minigun";
p->sWeaponSlots[1] = "super shotgun";
p->sWeaponSlots[2] = "blaster";
p->sWeaponSlots[3] = "gauss gun";
p->sWeaponSlots[4] = "big nuke";
// Add the profile onto the list
if(tProfiles) {
profile_t *pf = tProfiles;
profile_t *prv = NULL;
for(;pf;pf = pf->tNext) {
// If we are human, we need to insert ourselves into the list before the ai players
if(p->iType == PRF_HUMAN->toInt()) {
if(pf->iType == PRF_COMPUTER->toInt()) {
p->tNext = pf;
if(prv)
prv->tNext = p;
else
// Must be first one
tProfiles = p;
break;
}
}
if(pf->tNext == NULL) {
pf->tNext = p;
break;
}
prv = pf;
}
}
else
tProfiles = p;
// Reset the id's
p = tProfiles;
int i=0;
for(;p;p = p->tNext)
p->iID = i++;
}
///////////////////
// Find a free profile id
int FindProfileID()
{
profile_t *p = tProfiles;
int id = -1;
for(; p; p=p->tNext)
id = p->iID;
return id+1;
}
///////////////////
// Get the profiles
profile_t *GetProfiles()
{
return tProfiles;
}
///////////////////
// Find a profile based on id
profile_t *FindProfile(int id)
{
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->iID == id)
return p;
}
return NULL;
}
profile_t *FindProfile(const std::string& name) {
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->sName == name)
return p;
}
return NULL;
}
std::string FindFirstCPUProfileName() {
profile_t *p = tProfiles;
for(;p;p=p->tNext) {
if(p->iType == PRF_COMPUTER->toInt())
return p->sName;
}
return "";
}
<|endoftext|>
|
<commit_before>#ifndef ORIGEN_HPP_INCLUDED
#define ORIGEN_HPP_INCLUDED
#define ORIGEN_VERSION "0.2.0"
#ifndef debugger
#define debugger __asm__("int $3");
#endif
#include "origen/utils.hpp"
#include "origen/helpers.hpp"
namespace Origen {
Utils::Version version();
}
#endif
<commit_msg>Wrote new version in C++ code<commit_after>#ifndef ORIGEN_HPP_INCLUDED
#define ORIGEN_HPP_INCLUDED
#define ORIGEN_VERSION "0.3.0"
#ifndef debugger
#define debugger __asm__("int $3");
#endif
#include "origen/utils.hpp"
#include "origen/helpers.hpp"
namespace Origen {
Utils::Version version();
}
#endif
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "sal/config.h"
#include <boost/scoped_ptr.hpp>
#include <cppuhelper/compbase1.hxx>
#include <tools/debug.hxx>
#include <vcl/svapp.hxx>
#include <svdata.hxx>
#include <salinst.hxx>
#include <salsession.hxx>
#include <com/sun/star/frame/XSessionManagerClient.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/frame/XSessionManagerListener2.hpp>
#include <list>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
SalSession::~SalSession()
{
}
class VCLSession:
private osl::Mutex,
public cppu::WeakComponentImplHelper1 < XSessionManagerClient >
{
struct Listener
{
css::uno::Reference< XSessionManagerListener > m_xListener;
bool m_bInteractionRequested;
bool m_bInteractionDone;
bool m_bSaveDone;
Listener( const css::uno::Reference< XSessionManagerListener >& xListener )
: m_xListener( xListener ),
m_bInteractionRequested( false ),
m_bInteractionDone( false ),
m_bSaveDone( false )
{}
};
std::list< Listener > m_aListeners;
boost::scoped_ptr< SalSession > m_pSession;
bool m_bInteractionRequested;
bool m_bInteractionGranted;
bool m_bInteractionDone;
bool m_bSaveDone;
static void SalSessionEventProc( void* pData, SalSessionEvent* pEvent );
virtual ~VCLSession() {}
virtual void SAL_CALL addSessionManagerListener( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL removeSessionManagerListener( const css::uno::Reference< XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL queryInteraction( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL interactionDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL saveDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual sal_Bool SAL_CALL cancelShutdown() throw( RuntimeException, std::exception );
void callSaveRequested( bool bShutdown, bool bCancelable );
void callShutdownCancelled();
void callInteractionGranted( bool bGranted );
void callQuit();
public:
VCLSession();
};
VCLSession::VCLSession()
: cppu::WeakComponentImplHelper1< XSessionManagerClient >( *static_cast< osl::Mutex * >(this) ),
m_pSession( ImplGetSVData()->mpDefInst->CreateSalSession() ),
m_bInteractionRequested( false ),
m_bInteractionGranted( false ),
m_bInteractionDone( false ),
m_bSaveDone( false )
{
if( m_pSession )
m_pSession->SetCallback( SalSessionEventProc, this );
}
void VCLSession::callSaveRequested( bool bShutdown, bool bCancelable )
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( *this );
// reset listener states
for( std::list< Listener >::iterator it = m_aListeners.begin();
it != m_aListeners.end(); ++it )
{
it->m_bSaveDone = it->m_bInteractionRequested = it->m_bInteractionDone = false;
}
// copy listener list since calling a listener may remove it.
aListeners = m_aListeners;
// set back interaction state
m_bSaveDone = false;
m_bInteractionDone = false;
// without session we assume UI is always possible,
// so it was reqeusted and granted
m_bInteractionRequested = m_bInteractionGranted = !m_pSession;
// answer the session manager even if no listeners available anymore
DBG_ASSERT( ! aListeners.empty(), "saveRequested but no listeners !" );
if( aListeners.empty() )
{
if( m_pSession )
m_pSession->saveDone();
return;
}
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
it->m_xListener->doSave( bShutdown, bCancelable );
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::callInteractionGranted( bool bInteractionGranted )
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( *this );
// copy listener list since calling a listener may remove it.
for( std::list< Listener >::const_iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it )
if( it->m_bInteractionRequested )
aListeners.push_back( *it );
m_bInteractionGranted = bInteractionGranted;
// answer the session manager even if no listeners available anymore
DBG_ASSERT( ! aListeners.empty(), "interactionGranted but no listeners !" );
if( aListeners.empty() )
{
if( m_pSession )
m_pSession->interactionDone();
return;
}
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
it->m_xListener->approveInteraction( bInteractionGranted );
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::callShutdownCancelled()
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( *this );
// copy listener list since calling a listener may remove it.
aListeners = m_aListeners;
// set back interaction state
m_bInteractionRequested = m_bInteractionDone = m_bInteractionGranted = false;
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
it->m_xListener->shutdownCanceled();
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::callQuit()
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( *this );
// copy listener list since calling a listener may remove it.
aListeners = m_aListeners;
// set back interaction state
m_bInteractionRequested = m_bInteractionDone = m_bInteractionGranted = false;
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
{
css::uno::Reference< XSessionManagerListener2 > xListener2( it->m_xListener, UNO_QUERY );
if( xListener2.is() )
xListener2->doQuit();
}
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::SalSessionEventProc( void* pData, SalSessionEvent* pEvent )
{
VCLSession * pThis = static_cast< VCLSession * >( pData );
switch( pEvent->m_eType )
{
case Interaction:
{
SalSessionInteractionEvent* pIEv = static_cast<SalSessionInteractionEvent*>(pEvent);
pThis->callInteractionGranted( pIEv->m_bInteractionGranted );
}
break;
case SaveRequest:
{
SalSessionSaveRequestEvent* pSEv = static_cast<SalSessionSaveRequestEvent*>(pEvent);
pThis->callSaveRequested( pSEv->m_bShutdown, pSEv->m_bCancelable );
}
break;
case ShutdownCancel:
pThis->callShutdownCancelled();
break;
case Quit:
pThis->callQuit();
break;
}
}
void SAL_CALL VCLSession::addSessionManagerListener( const css::uno::Reference<XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( *this );
m_aListeners.push_back( Listener( xListener ) );
}
void SAL_CALL VCLSession::removeSessionManagerListener( const css::uno::Reference<XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( *this );
std::list< Listener >::iterator it = m_aListeners.begin();
while( it != m_aListeners.end() )
{
if( it->m_xListener == xListener )
{
it = m_aListeners.erase(it);
}
else
++it;
}
}
void SAL_CALL VCLSession::queryInteraction( const css::uno::Reference<XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception )
{
if( m_bInteractionGranted )
{
if( m_bInteractionDone )
xListener->approveInteraction( false );
else
xListener->approveInteraction( true );
return;
}
osl::MutexGuard aGuard( *this );
if( ! m_bInteractionRequested )
{
m_pSession->queryInteraction();
m_bInteractionRequested = true;
}
for( std::list< Listener >::iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it )
{
if( it->m_xListener == xListener )
{
it->m_bInteractionRequested = true;
it->m_bInteractionDone = false;
}
}
}
void SAL_CALL VCLSession::interactionDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( *this );
int nRequested = 0, nDone = 0;
for( std::list< Listener >::iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it )
{
if( it->m_bInteractionRequested )
{
nRequested++;
if( xListener == it->m_xListener )
it->m_bInteractionDone = true;
}
if( it->m_bInteractionDone )
nDone++;
}
if( nDone == nRequested && nDone > 0 )
{
m_bInteractionDone = true;
if( m_pSession )
m_pSession->interactionDone();
}
}
void SAL_CALL VCLSession::saveDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( *this );
bool bSaveDone = true;
for( std::list< Listener >::iterator it = m_aListeners.begin();
it != m_aListeners.end(); ++it )
{
if( it->m_xListener == xListener )
it->m_bSaveDone = true;
if( ! it->m_bSaveDone )
bSaveDone = false;
}
if( bSaveDone )
{
m_bSaveDone = true;
if( m_pSession )
m_pSession->saveDone();
}
}
sal_Bool SAL_CALL VCLSession::cancelShutdown() throw( RuntimeException, std::exception )
{
return m_pSession && m_pSession->cancelShutdown();
}
// service implementation
OUString SAL_CALL vcl_session_getImplementationName()
{
return OUString( "com.sun.star.frame.VCLSessionManagerClient" );
}
Sequence< OUString > SAL_CALL vcl_session_getSupportedServiceNames()
{
Sequence< OUString > aRet(1);
aRet[0] = "com.sun.star.frame.SessionManagerClient";
return aRet;
}
css::uno::Reference< XInterface > SAL_CALL vcl_session_createInstance( SAL_UNUSED_PARAMETER const css::uno::Reference< XMultiServiceFactory > & )
{
return static_cast< cppu::OWeakObject * >(new VCLSession);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Use cppu::BaseMutex instead of plain osl::Mutex as base<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
#include "sal/config.h"
#include <boost/scoped_ptr.hpp>
#include <cppuhelper/basemutex.hxx>
#include <cppuhelper/compbase1.hxx>
#include <tools/debug.hxx>
#include <vcl/svapp.hxx>
#include <svdata.hxx>
#include <salinst.hxx>
#include <salsession.hxx>
#include <com/sun/star/frame/XSessionManagerClient.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/frame/XSessionManagerListener2.hpp>
#include <list>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
SalSession::~SalSession()
{
}
class VCLSession:
private cppu::BaseMutex,
public cppu::WeakComponentImplHelper1 < XSessionManagerClient >
{
struct Listener
{
css::uno::Reference< XSessionManagerListener > m_xListener;
bool m_bInteractionRequested;
bool m_bInteractionDone;
bool m_bSaveDone;
Listener( const css::uno::Reference< XSessionManagerListener >& xListener )
: m_xListener( xListener ),
m_bInteractionRequested( false ),
m_bInteractionDone( false ),
m_bSaveDone( false )
{}
};
std::list< Listener > m_aListeners;
boost::scoped_ptr< SalSession > m_pSession;
bool m_bInteractionRequested;
bool m_bInteractionGranted;
bool m_bInteractionDone;
bool m_bSaveDone;
static void SalSessionEventProc( void* pData, SalSessionEvent* pEvent );
virtual ~VCLSession() {}
virtual void SAL_CALL addSessionManagerListener( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL removeSessionManagerListener( const css::uno::Reference< XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL queryInteraction( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL interactionDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual void SAL_CALL saveDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception );
virtual sal_Bool SAL_CALL cancelShutdown() throw( RuntimeException, std::exception );
void callSaveRequested( bool bShutdown, bool bCancelable );
void callShutdownCancelled();
void callInteractionGranted( bool bGranted );
void callQuit();
public:
VCLSession();
};
VCLSession::VCLSession()
: cppu::WeakComponentImplHelper1< XSessionManagerClient >( m_aMutex ),
m_pSession( ImplGetSVData()->mpDefInst->CreateSalSession() ),
m_bInteractionRequested( false ),
m_bInteractionGranted( false ),
m_bInteractionDone( false ),
m_bSaveDone( false )
{
if( m_pSession )
m_pSession->SetCallback( SalSessionEventProc, this );
}
void VCLSession::callSaveRequested( bool bShutdown, bool bCancelable )
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( m_aMutex );
// reset listener states
for( std::list< Listener >::iterator it = m_aListeners.begin();
it != m_aListeners.end(); ++it )
{
it->m_bSaveDone = it->m_bInteractionRequested = it->m_bInteractionDone = false;
}
// copy listener list since calling a listener may remove it.
aListeners = m_aListeners;
// set back interaction state
m_bSaveDone = false;
m_bInteractionDone = false;
// without session we assume UI is always possible,
// so it was reqeusted and granted
m_bInteractionRequested = m_bInteractionGranted = !m_pSession;
// answer the session manager even if no listeners available anymore
DBG_ASSERT( ! aListeners.empty(), "saveRequested but no listeners !" );
if( aListeners.empty() )
{
if( m_pSession )
m_pSession->saveDone();
return;
}
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
it->m_xListener->doSave( bShutdown, bCancelable );
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::callInteractionGranted( bool bInteractionGranted )
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( m_aMutex );
// copy listener list since calling a listener may remove it.
for( std::list< Listener >::const_iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it )
if( it->m_bInteractionRequested )
aListeners.push_back( *it );
m_bInteractionGranted = bInteractionGranted;
// answer the session manager even if no listeners available anymore
DBG_ASSERT( ! aListeners.empty(), "interactionGranted but no listeners !" );
if( aListeners.empty() )
{
if( m_pSession )
m_pSession->interactionDone();
return;
}
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
it->m_xListener->approveInteraction( bInteractionGranted );
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::callShutdownCancelled()
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( m_aMutex );
// copy listener list since calling a listener may remove it.
aListeners = m_aListeners;
// set back interaction state
m_bInteractionRequested = m_bInteractionDone = m_bInteractionGranted = false;
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
it->m_xListener->shutdownCanceled();
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::callQuit()
{
std::list< Listener > aListeners;
{
osl::MutexGuard aGuard( m_aMutex );
// copy listener list since calling a listener may remove it.
aListeners = m_aListeners;
// set back interaction state
m_bInteractionRequested = m_bInteractionDone = m_bInteractionGranted = false;
}
sal_uLong nAcquireCount = Application::ReleaseSolarMutex();
for( std::list< Listener >::const_iterator it = aListeners.begin(); it != aListeners.end(); ++it )
{
css::uno::Reference< XSessionManagerListener2 > xListener2( it->m_xListener, UNO_QUERY );
if( xListener2.is() )
xListener2->doQuit();
}
Application::AcquireSolarMutex( nAcquireCount );
}
void VCLSession::SalSessionEventProc( void* pData, SalSessionEvent* pEvent )
{
VCLSession * pThis = static_cast< VCLSession * >( pData );
switch( pEvent->m_eType )
{
case Interaction:
{
SalSessionInteractionEvent* pIEv = static_cast<SalSessionInteractionEvent*>(pEvent);
pThis->callInteractionGranted( pIEv->m_bInteractionGranted );
}
break;
case SaveRequest:
{
SalSessionSaveRequestEvent* pSEv = static_cast<SalSessionSaveRequestEvent*>(pEvent);
pThis->callSaveRequested( pSEv->m_bShutdown, pSEv->m_bCancelable );
}
break;
case ShutdownCancel:
pThis->callShutdownCancelled();
break;
case Quit:
pThis->callQuit();
break;
}
}
void SAL_CALL VCLSession::addSessionManagerListener( const css::uno::Reference<XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( m_aMutex );
m_aListeners.push_back( Listener( xListener ) );
}
void SAL_CALL VCLSession::removeSessionManagerListener( const css::uno::Reference<XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( m_aMutex );
std::list< Listener >::iterator it = m_aListeners.begin();
while( it != m_aListeners.end() )
{
if( it->m_xListener == xListener )
{
it = m_aListeners.erase(it);
}
else
++it;
}
}
void SAL_CALL VCLSession::queryInteraction( const css::uno::Reference<XSessionManagerListener>& xListener ) throw( RuntimeException, std::exception )
{
if( m_bInteractionGranted )
{
if( m_bInteractionDone )
xListener->approveInteraction( false );
else
xListener->approveInteraction( true );
return;
}
osl::MutexGuard aGuard( m_aMutex );
if( ! m_bInteractionRequested )
{
m_pSession->queryInteraction();
m_bInteractionRequested = true;
}
for( std::list< Listener >::iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it )
{
if( it->m_xListener == xListener )
{
it->m_bInteractionRequested = true;
it->m_bInteractionDone = false;
}
}
}
void SAL_CALL VCLSession::interactionDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( m_aMutex );
int nRequested = 0, nDone = 0;
for( std::list< Listener >::iterator it = m_aListeners.begin(); it != m_aListeners.end(); ++it )
{
if( it->m_bInteractionRequested )
{
nRequested++;
if( xListener == it->m_xListener )
it->m_bInteractionDone = true;
}
if( it->m_bInteractionDone )
nDone++;
}
if( nDone == nRequested && nDone > 0 )
{
m_bInteractionDone = true;
if( m_pSession )
m_pSession->interactionDone();
}
}
void SAL_CALL VCLSession::saveDone( const css::uno::Reference< XSessionManagerListener >& xListener ) throw( RuntimeException, std::exception )
{
osl::MutexGuard aGuard( m_aMutex );
bool bSaveDone = true;
for( std::list< Listener >::iterator it = m_aListeners.begin();
it != m_aListeners.end(); ++it )
{
if( it->m_xListener == xListener )
it->m_bSaveDone = true;
if( ! it->m_bSaveDone )
bSaveDone = false;
}
if( bSaveDone )
{
m_bSaveDone = true;
if( m_pSession )
m_pSession->saveDone();
}
}
sal_Bool SAL_CALL VCLSession::cancelShutdown() throw( RuntimeException, std::exception )
{
return m_pSession && m_pSession->cancelShutdown();
}
// service implementation
OUString SAL_CALL vcl_session_getImplementationName()
{
return OUString( "com.sun.star.frame.VCLSessionManagerClient" );
}
Sequence< OUString > SAL_CALL vcl_session_getSupportedServiceNames()
{
Sequence< OUString > aRet(1);
aRet[0] = "com.sun.star.frame.SessionManagerClient";
return aRet;
}
css::uno::Reference< XInterface > SAL_CALL vcl_session_createInstance( SAL_UNUSED_PARAMETER const css::uno::Reference< XMultiServiceFactory > & )
{
return static_cast< cppu::OWeakObject * >(new VCLSession);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Scott MacDonald
*
* 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 "common/platform.h"
#include "common/utils.h"
#include "version.h"
#include <string>
#include <sstream>
#include <iostream>
#include <stdlib.h>
namespace App {
/**
* Generates a assertion reporting dialog (or console output) to show to the
* player, before exiting the application
*
* \param message An accompanying assertion description (if provided)
* \param expression String containing the expression text
* \param filename Name of the file that generated the assertion
* \param lineNumber Line that generated the assertion
*/
EAssertionStatus reportAssertion( const std::string& message,
const std::string& expression,
const std::string& filename,
unsigned int lineNumber )
{
std::cerr
<< "---------- ASSERTION FAILED! ---------- " << std::endl
<< "MESSAGE : " << message << std::endl
<< "EXPRESSION: " << expression << std::endl
<< "FILENAME : " << filename << std::endl
<< "LINE : " << lineNumber << std::endl
<< "---------------------------------------" << std::endl
<< std::endl;
// Now return and let the caller know that they should abort
return EAssertion_Default;
}
/**
* Platform specific error reporting utility. This method is called by the
* game engine whenever there is an error (or warning) to be reported. The
* method is responsible for providing this information to the user and
* allowing the player to take appropriate action based on it.
*
* \param message A terse description of the error that occurred
* \param details Optional contextual details of the error
* \param type What type of error is this
* \param lineNumber Line number that this error occurred on
* \param functionName Name of the function where error occurred
*/
void reportSoftwareError( const std::string& message,
const std::string& details,
EErrorType type,
unsigned int lineNumber,
const char * filename,
const char * functionName )
{
// Error header
std::cerr
<< "=================================================================="
<< std::endl
<< "A " << getNameForError( type ) << " has occurred. Details follow. "
<< std::endl
<< std::endl;
// Print the message body
std::cerr << "MESSAGE: " << message << std::endl;
if ( filename != NULL )
{
std::cerr << " FILE: " << filename << std::endl;
}
if ( lineNumber > 0 )
{
std::cerr << " LINE: " << lineNumber << std::endl;
}
if ( functionName != NULL )
{
std::cerr << " FUNC: " << functionName << std::endl;
}
// If there were extra details, print them at the bottom of the error
// output
if (! details.empty() )
{
std::cerr << "DETAILS: " << std::endl
<< "-------- " << std::endl
<< details << std::endl;
}
// Message bottom
std::cerr
<< "============================================================="
<< std::endl
<< std::endl;
}
/**
* Performs UNIX specific start up tasks
*/
void startup()
{
}
/**
* Quit the program with the requested status and reason
*/
void quit( EProgramStatus programStatus, const std::string& message )
{
if (! message.empty() )
{
std::cerr << "EXITING: " << message << std::endl;
}
exit( programStatus );
}
/**
* Returns a string describing the conditions under which the game was
* built. Useful for troubleshooting, and that's about it
*/
std::string getBuildString()
{
std::ostringstream ss;
// All the settings we'll need to discover
std::string releaseMode = "_?release?_";
std::string processor = "_?cpu?_";
std::string platform = "_?platform?_";
std::string sse = "_?sse?_";
std::string compiler = "_?compiler?_";
// need to implement this
// Properly format the build string according to the compiler
ss << Version::VERSION_S << " "
<< sse << " "
<< platform << " "
<< __DATE__ << " "
<< __TIME__ << " "
;
// Return the build string
return ss.str();
}
}
<commit_msg>improved error formatting<commit_after>/*
* Copyright 2012 Scott MacDonald
*
* 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 "common/platform.h"
#include "common/utils.h"
#include "version.h"
#include <string>
#include <sstream>
#include <iostream>
#include <stdlib.h>
namespace App {
/**
* Generates a assertion reporting dialog (or console output) to show to the
* player, before exiting the application
*
* \param message An accompanying assertion description (if provided)
* \param expression String containing the expression text
* \param filename Name of the file that generated the assertion
* \param lineNumber Line that generated the assertion
*/
EAssertionStatus reportAssertion( const std::string& message,
const std::string& expression,
const std::string& filename,
unsigned int lineNumber )
{
std::cerr
<< "---------- ASSERTION FAILED! ---------- " << std::endl
<< "MESSAGE : " << message << std::endl
<< "EXPRESSION: " << expression << std::endl
<< "FILENAME : " << filename << std::endl
<< "LINE : " << lineNumber << std::endl
<< "---------------------------------------" << std::endl
<< std::endl;
// Now return and let the caller know that they should abort
return EAssertion_Default;
}
/**
* Platform specific error reporting utility. This method is called by the
* game engine whenever there is an error (or warning) to be reported. The
* method is responsible for providing this information to the user and
* allowing the player to take appropriate action based on it.
*
* \param message A terse description of the error that occurred
* \param details Optional contextual details of the error
* \param type What type of error is this
* \param lineNumber Line number that this error occurred on
* \param functionName Name of the function where error occurred
*/
void reportSoftwareError( const std::string& message,
const std::string& details,
EErrorType type,
unsigned int lineNumber,
const char * filename,
const char * functionName )
{
// Error header
std::cerr
<< std::endl
<< "########################################################################"
<< std::endl
<< "# A(n) " << getNameForError( type ) << " has occurred. Details follow. "
<< std::endl
<< "#"
<< std::endl;
// Print the message body
std::cerr << "# MESSAGE: " << message << std::endl;
if ( filename != NULL )
{
std::cerr << "# FILE: " << filename << std::endl;
}
if ( lineNumber > 0 )
{
std::cerr << "# LINE: " << lineNumber << std::endl;
}
if ( functionName != NULL )
{
std::cerr << "# FUNC: " << functionName << std::endl;
}
// If there were extra details, print them at the bottom of the error
// output
if (! details.empty() )
{
std::cerr << "# DETAILS: " << std::endl
<< "# -------- " << std::endl
<< "# " << details << std::endl;
}
// Message bottom
std::cerr
<< "########################################################################"
<< std::endl
<< std::endl;
}
/**
* Performs UNIX specific start up tasks
*/
void startup()
{
}
/**
* Quit the program with the requested status and reason
*/
void quit( EProgramStatus programStatus, const std::string& message )
{
if (! message.empty() )
{
std::cerr << "EXITING: " << message << std::endl;
}
exit( programStatus );
}
/**
* Returns a string describing the conditions under which the game was
* built. Useful for troubleshooting, and that's about it
*/
std::string getBuildString()
{
std::ostringstream ss;
// All the settings we'll need to discover
std::string releaseMode = "_?release?_";
std::string processor = "_?cpu?_";
std::string platform = "_?platform?_";
std::string sse = "_?sse?_";
std::string compiler = "_?compiler?_";
// need to implement this
// Properly format the build string according to the compiler
ss << Version::VERSION_S << " "
<< sse << " "
<< platform << " "
<< __DATE__ << " "
<< __TIME__ << " "
;
// Return the build string
return ss.str();
}
}
<|endoftext|>
|
<commit_before>#include "concurrency/semaphore.hpp"
#include "arch/runtime/runtime.hpp"
#include "concurrency/cond_var.hpp"
void semaphore_t::lock(semaphore_available_callback_t *cb, int count) {
rassert(!in_callback);
rassert(count <= capacity || capacity == SEMAPHORE_NO_LIMIT);
if (current + count <= capacity || capacity == SEMAPHORE_NO_LIMIT) {
current += count;
DEBUG_ONLY_CODE(in_callback = true);
cb->on_semaphore_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
} else {
lock_request_t *r = new lock_request_t;
r->count = count;
r->cb = cb;
waiters.push_back(r);
}
}
void semaphore_t::co_lock(int count) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public one_waiter_cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, count);
cb.wait_eagerly_deprecated();
// TODO: Remove the need for in_callback checks.
coro_t::yield();
}
void semaphore_t::co_lock_interruptible(signal_t *interruptor) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, 1);
wait_interruptible(&cb, interruptor);
}
void semaphore_t::unlock(int count) {
rassert(!in_callback);
rassert(current >= count);
current -= count;
while (lock_request_t *h = waiters.head()) {
if (current + h->count <= capacity) {
waiters.remove(h);
current += h->count;
rassert(!in_callback);
DEBUG_ONLY_CODE(in_callback = true);
h->on_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
} else {
break;
}
}
}
void semaphore_t::lock_now(int count) {
rassert(!in_callback);
rassert(current + count <= capacity || capacity == SEMAPHORE_NO_LIMIT);
current += count;
}
void adjustable_semaphore_t::lock(semaphore_available_callback_t *cb, int count) {
rassert(!in_callback);
rassert(count <= capacity || capacity == SEMAPHORE_NO_LIMIT);
if (try_lock(count)) {
rassert(!in_callback);
DEBUG_ONLY_CODE(in_callback = true);
cb->on_semaphore_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
} else {
lock_request_t *r = new lock_request_t;
r->count = count;
r->cb = cb;
waiters.push_back(r);
}
}
void adjustable_semaphore_t::co_lock(int count) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public one_waiter_cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, count);
cb.wait_eagerly_deprecated();
// TODO: remove need for in_callback checks
coro_t::yield();
}
void adjustable_semaphore_t::co_lock_interruptible(signal_t *interruptor) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, 1);
wait_interruptible(&cb, interruptor);
}
void adjustable_semaphore_t::unlock(int count) {
rassert(!in_callback);
rassert(current >= count);
current -= count;
if (current > capacity && capacity != SEMAPHORE_NO_LIMIT) {
trickle_points += trickle_fraction * count;
}
pump();
}
void adjustable_semaphore_t::lock_now(int count) {
rassert(!in_callback);
if (!try_lock(count)) {
crash("lock_now() can't lock now.\n");
}
}
void adjustable_semaphore_t::force_lock(int count) {
current += count;
}
void adjustable_semaphore_t::set_capacity(int new_capacity) {
rassert(!in_callback);
capacity = new_capacity;
rassert(capacity >= 0 || capacity == SEMAPHORE_NO_LIMIT);
pump();
}
bool adjustable_semaphore_t::try_lock(int count) {
if (current + count > capacity && capacity != SEMAPHORE_NO_LIMIT) {
if (trickle_points >= count) {
trickle_points -= count;
} else {
return false;
}
}
current += count;
return true;
}
void adjustable_semaphore_t::pump() {
rassert(!in_callback);
lock_request_t *h;
while ((h = waiters.head()) && try_lock(h->count)) {
waiters.remove(h);
rassert(!in_callback);
DEBUG_ONLY_CODE(in_callback = true);
h->on_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
}
}
<commit_msg>fixing potential crash and memory corruption when a semaphore co_lock_interruptible is interrupted<commit_after>#include "concurrency/semaphore.hpp"
#include "arch/runtime/runtime.hpp"
#include "concurrency/cond_var.hpp"
void semaphore_t::lock(semaphore_available_callback_t *cb, int count) {
rassert(!in_callback);
rassert(count <= capacity || capacity == SEMAPHORE_NO_LIMIT);
if (current + count <= capacity || capacity == SEMAPHORE_NO_LIMIT) {
current += count;
DEBUG_ONLY_CODE(in_callback = true);
cb->on_semaphore_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
} else {
lock_request_t *r = new lock_request_t;
r->count = count;
r->cb = cb;
waiters.push_back(r);
}
}
void semaphore_t::co_lock(int count) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public one_waiter_cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, count);
cb.wait_eagerly_deprecated();
// TODO: Remove the need for in_callback checks.
coro_t::yield();
}
void semaphore_t::co_lock_interruptible(signal_t *interruptor) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, 1);
try {
wait_interruptible(&cb, interruptor);
} catch (interrupted_exc_t &ex) {
// Remove our lock request from the queue
for (lock_request_t *request = waiters.head(); request != NULL; request = waiters.next(request)) {
if (request->cb == &cb) {
waiters.remove(request);
delete request;
break;
}
}
throw;
}
}
void semaphore_t::unlock(int count) {
rassert(!in_callback);
rassert(current >= count);
current -= count;
while (lock_request_t *h = waiters.head()) {
if (current + h->count <= capacity) {
waiters.remove(h);
current += h->count;
rassert(!in_callback);
DEBUG_ONLY_CODE(in_callback = true);
h->on_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
} else {
break;
}
}
}
void semaphore_t::lock_now(int count) {
rassert(!in_callback);
rassert(current + count <= capacity || capacity == SEMAPHORE_NO_LIMIT);
current += count;
}
void adjustable_semaphore_t::lock(semaphore_available_callback_t *cb, int count) {
rassert(!in_callback);
rassert(count <= capacity || capacity == SEMAPHORE_NO_LIMIT);
if (try_lock(count)) {
rassert(!in_callback);
DEBUG_ONLY_CODE(in_callback = true);
cb->on_semaphore_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
} else {
lock_request_t *r = new lock_request_t;
r->count = count;
r->cb = cb;
waiters.push_back(r);
}
}
void adjustable_semaphore_t::co_lock(int count) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public one_waiter_cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, count);
cb.wait_eagerly_deprecated();
// TODO: remove need for in_callback checks
coro_t::yield();
}
void adjustable_semaphore_t::co_lock_interruptible(signal_t *interruptor) {
rassert(!in_callback);
struct : public semaphore_available_callback_t, public cond_t {
void on_semaphore_available() { pulse(); }
} cb;
lock(&cb, 1);
try {
wait_interruptible(&cb, interruptor);
} catch (interrupted_exc_t& ex) {
// Remove our lock request from the queue
for (lock_request_t *request = waiters.head(); request != NULL; request = waiters.next(request)) {
if (request->cb == &cb) {
waiters.remove(request);
delete request;
break;
}
}
throw;
}
}
void adjustable_semaphore_t::unlock(int count) {
rassert(!in_callback);
rassert(current >= count);
current -= count;
if (current > capacity && capacity != SEMAPHORE_NO_LIMIT) {
trickle_points += trickle_fraction * count;
}
pump();
}
void adjustable_semaphore_t::lock_now(int count) {
rassert(!in_callback);
if (!try_lock(count)) {
crash("lock_now() can't lock now.\n");
}
}
void adjustable_semaphore_t::force_lock(int count) {
current += count;
}
void adjustable_semaphore_t::set_capacity(int new_capacity) {
rassert(!in_callback);
capacity = new_capacity;
rassert(capacity >= 0 || capacity == SEMAPHORE_NO_LIMIT);
pump();
}
bool adjustable_semaphore_t::try_lock(int count) {
if (current + count > capacity && capacity != SEMAPHORE_NO_LIMIT) {
if (trickle_points >= count) {
trickle_points -= count;
} else {
return false;
}
}
current += count;
return true;
}
void adjustable_semaphore_t::pump() {
rassert(!in_callback);
lock_request_t *h;
while ((h = waiters.head()) && try_lock(h->count)) {
waiters.remove(h);
rassert(!in_callback);
DEBUG_ONLY_CODE(in_callback = true);
h->on_available();
rassert(in_callback);
DEBUG_ONLY_CODE(in_callback = false);
}
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "classad_hashtable.h"
#include "setenv.h"
extern DLL_IMPORT_MAGIC char **environ;
// Under unix, we maintain a hash-table of all environment variables that
// have been inserted using SetEnv() below. If they are overwritten by
// another call to SetEnv() or removed by UnsetEnv(), we delete the
// allocated memory. Windows does its own memory management for environment
// variables, so this hash-table is unnecessary there.
#define HASH_TABLE_SIZE 50
#ifndef WIN32
template class HashTable<HashKey, char *>;
template class HashBucket<HashKey, char *>;
HashTable <HashKey, char *> EnvVars( HASH_TABLE_SIZE, hashFunction );
#endif
int SetEnv( const char *key, const char *value)
{
assert(key);
assert(value);
#ifdef WIN32
if ( !SetEnvironmentVariable(key, value) ) {
dprintf(D_ALWAYS,
"SetEnvironmentVariable failed, errno=%d\n",
GetLastError());
return FALSE;
}
#else
char *buf;
buf = new char[strlen(key) + strlen(value) + 2];
sprintf(buf, "%s=%s", key, value);
if( putenv(buf) != 0 )
{
dprintf(D_ALWAYS, "putenv failed: %s (errno=%d)\n",
strerror(errno), errno);
delete[] buf;
return FALSE;
}
char *hashed_var;
if ( EnvVars.lookup( HashKey( key ), hashed_var ) == 0 ) {
// found old one
// remove old one
EnvVars.remove( HashKey( key ) );
// delete old one
delete [] hashed_var;
// insert new one
EnvVars.insert( HashKey( key ), buf );
} else {
// no old one
// add new one
EnvVars.insert( HashKey( key ), buf );
}
#endif
return TRUE;
}
int SetEnv( const char *env_var )
{
// this function used if you've already got a name=value type
// of string, and want to put it into the environment. env_var
// must therefore contain an '='.
if ( !env_var ) {
dprintf (D_ALWAYS, "SetEnv, env_var = NULL!\n" );
return FALSE;
}
// Assume this type of string passes thru with no problem...
if ( env_var[0] == 0 ) {
return TRUE;
}
char *equalpos = NULL;
if ( ! (equalpos = strchr( env_var, '=' )) ) {
dprintf (D_ALWAYS, "SetEnv, env_var has no '='\n" );
dprintf (D_ALWAYS, "env_var = \"%s\"\n", env_var );
return FALSE;
}
// hack up string and pass to other SetEnv version.
size_t namelen = equalpos - env_var;
int valuelen = strlen(env_var) - namelen - 1;
char *name = new char[namelen+1];
char *value = new char[valuelen+1];
strncpy ( name, env_var, namelen );
strncpy ( value, equalpos+1, valuelen );
name[namelen] = '\0';
value[valuelen] = '\0';
int retval = SetEnv ( name, value );
delete [] name;
delete [] value;
return retval;
}
int UnsetEnv( const char *env_var )
{
assert( env_var );
#ifdef WIN32
if ( !SetEnvironmentVariable(env_var, NULL) ) {
dprintf(D_ALWAYS,
"SetEnvironmentVariable failed, errno=%d\n",
GetLastError());
return FALSE;
}
#else
for ( int i = 0 ; environ[i] != NULL; i++ ) {
if ( strncmp( environ[i], env_var, strlen(env_var) ) == 0 ) {
for ( ; environ[i] != NULL; i++ ) {
environ[i] = environ[i+1];
}
break;
}
}
char *hashed_var;
if ( EnvVars.lookup( HashKey( env_var ), hashed_var ) == 0 ) {
// found it
// remove it
EnvVars.remove( HashKey( env_var ) );
// delete it
delete [] hashed_var;
}
#endif
return TRUE;
}
const char *GetEnv( const char *env_var )
{
assert( env_var );
#ifdef WIN32
static MyString result;
return GetEnv( env_var, result );
#else
return getenv( env_var );
#endif
}
const char *GetEnv( const char *env_var, MyString &result )
{
assert( env_var );
#ifdef WIN32
DWORD rc;
int value_size = 0;
char *value = NULL;
value_size = 1024;
value = (char *)malloc( value_size );
rc = GetEnvironmentVariable( env_var, value, value_size );
if ( rc > value_size - 1 ) {
// environment variable value is too large,
// reallocate our string and try again
free( value );
value_size = rc;
value = (char *)malloc( value_size );
rc = GetEnvironmentVariable( env_var, value, value_size );
}
if ( rc > value_size - 1 ) {
dprintf( D_ALWAYS, "GetEnv(): environment variable still too large: %d\n", rc );
free( value );
return NULL;
} else if ( rc == 0 ) {
DWORD error = GetLastError();
if ( error != ERROR_ENVVAR_NOT_FOUND ) {
dprintf( D_ALWAYS,
"GetEnv(): GetEnvironmentVariable() failed, error=%d\n",
error );
}
free( value );
return NULL;
} else {
result = value;
free( value );
}
#else
result = getenv( env_var );
return result.Value();
#endif
}
<commit_msg>Fix for windows version of GetEnv() broken by my recent (unreleased) patch for POSIX_PATH_MAX.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "classad_hashtable.h"
#include "setenv.h"
extern DLL_IMPORT_MAGIC char **environ;
// Under unix, we maintain a hash-table of all environment variables that
// have been inserted using SetEnv() below. If they are overwritten by
// another call to SetEnv() or removed by UnsetEnv(), we delete the
// allocated memory. Windows does its own memory management for environment
// variables, so this hash-table is unnecessary there.
#define HASH_TABLE_SIZE 50
#ifndef WIN32
template class HashTable<HashKey, char *>;
template class HashBucket<HashKey, char *>;
HashTable <HashKey, char *> EnvVars( HASH_TABLE_SIZE, hashFunction );
#endif
int SetEnv( const char *key, const char *value)
{
assert(key);
assert(value);
#ifdef WIN32
if ( !SetEnvironmentVariable(key, value) ) {
dprintf(D_ALWAYS,
"SetEnvironmentVariable failed, errno=%d\n",
GetLastError());
return FALSE;
}
#else
char *buf;
buf = new char[strlen(key) + strlen(value) + 2];
sprintf(buf, "%s=%s", key, value);
if( putenv(buf) != 0 )
{
dprintf(D_ALWAYS, "putenv failed: %s (errno=%d)\n",
strerror(errno), errno);
delete[] buf;
return FALSE;
}
char *hashed_var;
if ( EnvVars.lookup( HashKey( key ), hashed_var ) == 0 ) {
// found old one
// remove old one
EnvVars.remove( HashKey( key ) );
// delete old one
delete [] hashed_var;
// insert new one
EnvVars.insert( HashKey( key ), buf );
} else {
// no old one
// add new one
EnvVars.insert( HashKey( key ), buf );
}
#endif
return TRUE;
}
int SetEnv( const char *env_var )
{
// this function used if you've already got a name=value type
// of string, and want to put it into the environment. env_var
// must therefore contain an '='.
if ( !env_var ) {
dprintf (D_ALWAYS, "SetEnv, env_var = NULL!\n" );
return FALSE;
}
// Assume this type of string passes thru with no problem...
if ( env_var[0] == 0 ) {
return TRUE;
}
char *equalpos = NULL;
if ( ! (equalpos = strchr( env_var, '=' )) ) {
dprintf (D_ALWAYS, "SetEnv, env_var has no '='\n" );
dprintf (D_ALWAYS, "env_var = \"%s\"\n", env_var );
return FALSE;
}
// hack up string and pass to other SetEnv version.
size_t namelen = equalpos - env_var;
int valuelen = strlen(env_var) - namelen - 1;
char *name = new char[namelen+1];
char *value = new char[valuelen+1];
strncpy ( name, env_var, namelen );
strncpy ( value, equalpos+1, valuelen );
name[namelen] = '\0';
value[valuelen] = '\0';
int retval = SetEnv ( name, value );
delete [] name;
delete [] value;
return retval;
}
int UnsetEnv( const char *env_var )
{
assert( env_var );
#ifdef WIN32
if ( !SetEnvironmentVariable(env_var, NULL) ) {
dprintf(D_ALWAYS,
"SetEnvironmentVariable failed, errno=%d\n",
GetLastError());
return FALSE;
}
#else
for ( int i = 0 ; environ[i] != NULL; i++ ) {
if ( strncmp( environ[i], env_var, strlen(env_var) ) == 0 ) {
for ( ; environ[i] != NULL; i++ ) {
environ[i] = environ[i+1];
}
break;
}
}
char *hashed_var;
if ( EnvVars.lookup( HashKey( env_var ), hashed_var ) == 0 ) {
// found it
// remove it
EnvVars.remove( HashKey( env_var ) );
// delete it
delete [] hashed_var;
}
#endif
return TRUE;
}
const char *GetEnv( const char *env_var )
{
assert( env_var );
#ifdef WIN32
static MyString result;
return GetEnv( env_var, result );
#else
return getenv( env_var );
#endif
}
const char *GetEnv( const char *env_var, MyString &result )
{
assert( env_var );
#ifdef WIN32
DWORD rc;
int value_size = 0;
char *value = NULL;
value_size = 1024;
value = (char *)malloc( value_size );
rc = GetEnvironmentVariable( env_var, value, value_size );
if ( rc > value_size - 1 ) {
// environment variable value is too large,
// reallocate our string and try again
free( value );
value_size = rc;
value = (char *)malloc( value_size );
rc = GetEnvironmentVariable( env_var, value, value_size );
}
if ( rc > value_size - 1 ) {
dprintf( D_ALWAYS, "GetEnv(): environment variable still too large: %d\n", rc );
free( value );
return NULL;
} else if ( rc == 0 ) {
DWORD error = GetLastError();
if ( error != ERROR_ENVVAR_NOT_FOUND ) {
dprintf( D_ALWAYS,
"GetEnv(): GetEnvironmentVariable() failed, error=%d\n",
error );
}
free( value );
return NULL;
} else {
result = value;
free( value );
}
#else
result = getenv( env_var );
#endif
return result.Value();
}
<|endoftext|>
|
<commit_before>//******************************************************************************
// AttrList.C
//
// Implementation of AttrList classes and AttrListList classes.
//
//******************************************************************************
# include <std.h>
# include <ctype.h>
# include <assert.h>
# include <string.h>
# include "except.h"
# include "condor_ast.h"
# include "condor_registration.h"
# include "condor_expressions.h"
# include "condor_attrlist.h"
# include "condor_classad.h"
# include "condor_parser.h"
static Registration regi; // this is the registration for
// the AttrList type names. It
// should be defined in the calling
// procedure.
static char *_FileName_ = __FILE__; // Used by EXCEPT (see except.h)
extern "C" int _EXCEPT_(char*, ...);
extern "C" int xdr_mywrapstring (XDR *, char **);
//
// AdType Constructor.
//
AdType::AdType(char *tempName)
{
if(tempName == NULL)
{ // if empty.
name = new char[strlen("") + 1];
if(!name)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
strcpy(name, "");
number = -1;
}
else
{
name = new char[strlen(tempName) + 1];
if(!name)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
strcpy(name, tempName);
number = regi.RegisterType(tempName);
}
}
//
// AdType Destructor.
//
AdType::~AdType()
{
if(name)
{
delete []name;
}
}
//
// ClassAd constructors
//
ClassAd::ClassAd() : AttrList()
{
myType = NULL;
targetType = NULL;
}
ClassAd::ClassAd(class ProcObj* procObj) : AttrList(procObj)
{
myType = NULL;
targetType = NULL;
}
ClassAd::ClassAd(const CONTEXT* context) : AttrList((CONTEXT *) context)
{
myType = NULL;
targetType = NULL;
}
ClassAd::ClassAd(FILE* f, char* d, int& i) : AttrList(f, d, i)
{
ExprTree *tree;
EvalResult *val;
myType = NULL;
targetType = NULL;
val = new EvalResult;
tree = Lookup("MyType");
if(!tree)
{
myType = new AdType(); // undefined type.
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
tree->EvalTree(this, val);
myType = new AdType(val->s);
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
if(!(tree = Lookup("TargetType")))
{
targetType = new AdType(); // undefined type.
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
tree->EvalTree(this, val);
targetType = new AdType(val->s);
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
if(val)
{
delete val;
}
Delete("MyType"); // eliminate redundant storage.
Delete("TargetType");
}
ClassAd::ClassAd(char* s, char d) : AttrList(s, d)
{
ExprTree *tree;
EvalResult *val;
myType = NULL;
targetType = NULL;
val = new EvalResult;
if(val == NULL)
{
cerr << "Warning : you ran out of space -- quitting !" << endl;
exit(1);
}
Parse("MyType", tree); // set myType field by evaluation
tree->EvalTree(this, val); // over itself.
if(!val || val->type!=LX_STRING)
{
myType = new AdType(); // undefined type.
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
myType = new AdType(val->s);
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
delete tree;
Parse("TargetType", tree); // set targetType field by
// evaluation over itself.
tree->EvalTree(this, val);
if(!val || val->type!=LX_STRING)
{
targetType = new AdType(); // undefined type.
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
targetType = new AdType(val->s);
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
delete tree;
if(val)
{
delete val;
}
Delete("MyType"); // eliminate redundant storage.
Delete("TargetType");
}
ClassAd::ClassAd(const ClassAd& old) : AttrList((AttrList&) old)
{
myType = NULL;
targetType = NULL;
if(old.myType)
{
this->myType = new AdType(old.myType->name);
if(this->myType == NULL)
{
EXCEPT("Warning : you ran out of meomory");
}
}
if(old.targetType)
{
this->targetType = new AdType(old.targetType->name);
if(this->targetType == NULL)
{
EXCEPT("Warning : you ran out of meomory");
}
}
}
ClassAd::~ClassAd()
{
AttrListElem* tmp;
for(tmp = exprList; tmp; tmp = exprList)
{
exprList = exprList->next;
delete tmp;
}
if(associatedList)
{
associatedList->associatedAttrLists->Delete(this);
}
if(myType)
{
delete myType;
}
if(targetType)
{
delete targetType;
}
}
//
// This member function of class AttrList sets myType name.
//
void ClassAd::SetMyTypeName(char *tempName)
{
if(myType)
{
delete myType;
}
myType = new AdType(tempName);
if(!myType)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
}
//
// This member function of class AttrList returns myType name.
//
char *ClassAd::GetMyTypeName()
{
if(!myType)
{
char *temp = ""; // undefined type.
return temp;
}
else
{
return myType->name;
}
}
//
// This member function of class AttrList sets targetType name.
//
void ClassAd::SetTargetTypeName(char *tempName)
{
if(targetType)
{
delete targetType;
}
targetType = new AdType(tempName);
if(!targetType)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
}
//
// This member function of class AttrList returns targetType name.
//
char *ClassAd::GetTargetTypeName()
{
if(!targetType)
{
char *temp = ""; // undefined.
return temp;
}
else
{
return targetType->name;
}
}
//
// This member function of class AttrList returns myType number.
//
int ClassAd::GetMyTypeNumber()
{
if(!myType)
{
return -1; // undefined type.
}
else
{
return myType->number;
}
}
//
// This member function of class AttrList returns targetType number.
//
int ClassAd::GetTargetTypeNumber()
{
if(!targetType)
{
return -1; // undefined type.
}
else
{
return targetType->number;
}
}
//
// This member function tests whether two ClassAds match mutually.
//
int ClassAd::IsAMatch(ClassAd* temp)
{
ExprTree *tree;
EvalResult *val;
if(!temp)
{
return 0;
}
if((GetMyTypeNumber() != temp->GetTargetTypeNumber()) ||
(GetTargetTypeNumber() != temp->GetMyTypeNumber()))
{
return 0; // types don't match.
}
val = new EvalResult;
if(val == NULL)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
Parse("MY.Requirement", tree); // convention.
tree->EvalTree(this, temp, val); // match in one direction.
if(!val || val->type != LX_BOOL)
{
delete tree;
delete val;
return 0;
}
else
{
if(!val->b)
{
delete tree;
delete val;
return 0;
}
}
tree->EvalTree(temp, this, val); // match in the other direction.
if(!val || val->type != LX_BOOL)
{
delete tree;
delete val;
return 0;
}
else
{
if(!val->b)
{
delete tree;
delete val;
return 0;
}
}
delete tree;
delete val;
return 1;
}
bool operator== (ClassAd &lhs, ClassAd &rhs)
{
return (lhs >= rhs && rhs >= lhs);
}
bool operator<= (ClassAd &lhs, ClassAd &rhs)
{
return (rhs >= lhs);
}
bool operator>= (ClassAd &lhs, ClassAd &rhs)
{
ExprTree *tree;
EvalResult *val;
if (lhs.GetMyTypeNumber() != rhs.GetTargetTypeNumber())
return false;
if ((val = new EvalResult) == NULL)
{
cerr << "Out of memory -- quitting" << endl;
exit (1);
}
Parse ("MY.Requirement", tree);
tree -> EvalTree (&rhs, &lhs, val);
if (!val || val->type != LX_BOOL)
{
delete tree;
delete val;
return false;
}
else
if (!val->b)
{
delete tree;
delete val;
return false;
}
delete tree;
delete val;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// print the whole ClassAd into a file. The expressions are in infix notation.
// Returns FALSE if the file pointer is NULL; TRUE otherwise.
////////////////////////////////////////////////////////////////////////////////
int ClassAd::fPrint(FILE* f)
{
if(!f)
{
return FALSE;
}
fprintf(f, "MyType = ");
fprintf(f, "%c", '"');
if(GetMyTypeName())
{
fprintf(f, "%s", GetMyTypeName());
}
fprintf(f, "%c\n", '"');
fprintf(f, "TargetType = ");
fprintf(f, "%c", '"');
if(GetMyTypeName())
{
fprintf(f, "%s", GetTargetTypeName());
}
fprintf(f, "%c\n", '"');
return AttrList::fPrint(f);
}
// shipping functions for ClassAd -- added by Lei Cao
int ClassAd::put(Stream& s)
{
AttrListElem* elem;
char* line;
int numExprs = 0;
//get the number of expressions
for(elem = exprList; elem; elem = elem->next)
numExprs++;
s.encode();
if(!s.code(numExprs))
return 0;
line = new char[200];
for(elem = exprList; elem; elem = elem->next) {
strcpy(line, "");
elem->tree->PrintToStr(line);
if(!s.code(line)) {
delete [] line;
return 0;
}
}
delete [] line;
if(!s.code(myType->name))
return 0;
if(!s.code(targetType->name))
return 0;
return 1;
}
int ClassAd::get(Stream& s)
{
ExprTree* tree;
char* name;
char* line;
int numExprs;
exprList = NULL;
associatedList = NULL;
tail = NULL;
ptrExpr = NULL;
ptrName = NULL;
myType = NULL;
targetType = NULL;
s.decode();
if(!s.code(numExprs))
return 0;
line = new char[200];
for(int i = 0; i < numExprs; i++) {
if(!s.code(line)) {
delete [] line;
return 0;
}
if(!Parse(line, tree)) {
if(tree->MyType() == LX_ERROR) {
cerr << "Parse error in the incomming stream -- quitting !"
<< endl;
delete [] line;
exit(1);
}
}
else {
cerr << "Parse error in the incomming stream -- quitting !" << endl;
delete [] line;
exit(1);
}
Insert(tree);
strcpy(line, "");
delete tree;
}
delete [] line;
name = new char[50];
if(!s.code(name)) {
delete [] name;
return 0;
}
SetMyTypeName(name);
delete [] name;
name = new char[50];
if(!s.code(name)) {
delete [] name;
return 0;
}
SetTargetTypeName(name);
delete [] name;
return 1;
}
int ClassAd::code(Stream& s)
{
if(s.is_encode())
return put(s);
else
return get(s);
}
int ClassAd::put (XDR *xdrs)
{
xdrs->x_op = XDR_ENCODE;
if (!AttrList::put (xdrs))
return 0;
if (!xdr_mywrapstring (xdrs, &myType->name))
return 0;
if (!xdr_mywrapstring (xdrs, &targetType->name))
return 0;
return 1;
}
int ClassAd::get (XDR *xdrs)
{
char buf[100];
char *line = buf;
if (!line) return 0;
xdrs->x_op = XDR_DECODE;
if (!AttrList::get (xdrs))
return 0;
if (!xdr_mywrapstring (xdrs, &line))
return 0;
SetMyTypeName (line);
if (!xdr_mywrapstring (xdrs, &line))
return 0;
SetTargetTypeName (line);
return 1;
}
void ClassAd::
ExchangeExpressions (ClassAd *ad)
{
AttrListElem *tmp1;
AttrListList *tmp2;
int tmp3;
// exchange variables which maintain the attribute list
// see condor_attrlist.h --RR
# define SWAP(a,b,t) {t=a; a=b; b=t;}
SWAP(associatedList, ad->associatedList, tmp2); // this is AttrListList*
SWAP(exprList, ad->exprList, tmp1); // these are AttrListElem*
SWAP(tail, ad->tail, tmp1);
SWAP(ptrExpr, ad->ptrExpr, tmp1);
SWAP(ptrName, ad->ptrName, tmp1);
SWAP (seq, ad->seq, tmp3); // this is an int
// undefine macro to decrease name-space pollution
# undef SWAP
return;
}
<commit_msg>checking for null pointers<commit_after>//******************************************************************************
// AttrList.C
//
// Implementation of AttrList classes and AttrListList classes.
//
//******************************************************************************
# include <std.h>
# include <ctype.h>
# include <assert.h>
# include <string.h>
# include "except.h"
# include "condor_ast.h"
# include "condor_registration.h"
# include "condor_expressions.h"
# include "condor_attrlist.h"
# include "condor_classad.h"
# include "condor_parser.h"
static Registration regi; // this is the registration for
// the AttrList type names. It
// should be defined in the calling
// procedure.
static char *_FileName_ = __FILE__; // Used by EXCEPT (see except.h)
extern "C" int _EXCEPT_(char*, ...);
extern "C" int xdr_mywrapstring (XDR *, char **);
//
// AdType Constructor.
//
AdType::AdType(char *tempName)
{
if(tempName == NULL)
{ // if empty.
name = new char[strlen("") + 1];
if(!name)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
strcpy(name, "");
number = -1;
}
else
{
name = new char[strlen(tempName) + 1];
if(!name)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
strcpy(name, tempName);
number = regi.RegisterType(tempName);
}
}
//
// AdType Destructor.
//
AdType::~AdType()
{
if(name)
{
delete []name;
}
}
//
// ClassAd constructors
//
ClassAd::ClassAd() : AttrList()
{
myType = NULL;
targetType = NULL;
}
ClassAd::ClassAd(class ProcObj* procObj) : AttrList(procObj)
{
myType = NULL;
targetType = NULL;
}
ClassAd::ClassAd(const CONTEXT* context) : AttrList((CONTEXT *) context)
{
myType = NULL;
targetType = NULL;
}
ClassAd::ClassAd(FILE* f, char* d, int& i) : AttrList(f, d, i)
{
ExprTree *tree;
EvalResult *val;
myType = NULL;
targetType = NULL;
val = new EvalResult;
tree = Lookup("MyType");
if(!tree)
{
myType = new AdType(); // undefined type.
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
tree->EvalTree(this, val);
myType = new AdType(val->s);
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
if(!(tree = Lookup("TargetType")))
{
targetType = new AdType(); // undefined type.
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
tree->EvalTree(this, val);
targetType = new AdType(val->s);
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
if(val)
{
delete val;
}
Delete("MyType"); // eliminate redundant storage.
Delete("TargetType");
}
ClassAd::ClassAd(char* s, char d) : AttrList(s, d)
{
ExprTree *tree;
EvalResult *val;
myType = NULL;
targetType = NULL;
val = new EvalResult;
if(val == NULL)
{
cerr << "Warning : you ran out of space -- quitting !" << endl;
exit(1);
}
Parse("MyType", tree); // set myType field by evaluation
tree->EvalTree(this, val); // over itself.
if(!val || val->type!=LX_STRING)
{
myType = new AdType(); // undefined type.
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
myType = new AdType(val->s);
if(myType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
delete tree;
Parse("TargetType", tree); // set targetType field by
// evaluation over itself.
tree->EvalTree(this, val);
if(!val || val->type!=LX_STRING)
{
targetType = new AdType(); // undefined type.
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
else
{
targetType = new AdType(val->s);
if(targetType == NULL)
{
EXCEPT("Warning : you ran out of space");
}
}
delete tree;
if(val)
{
delete val;
}
Delete("MyType"); // eliminate redundant storage.
Delete("TargetType");
}
ClassAd::ClassAd(const ClassAd& old) : AttrList((AttrList&) old)
{
myType = NULL;
targetType = NULL;
if(old.myType)
{
this->myType = new AdType(old.myType->name);
if(this->myType == NULL)
{
EXCEPT("Warning : you ran out of meomory");
}
}
if(old.targetType)
{
this->targetType = new AdType(old.targetType->name);
if(this->targetType == NULL)
{
EXCEPT("Warning : you ran out of meomory");
}
}
}
ClassAd::~ClassAd()
{
AttrListElem* tmp;
for(tmp = exprList; tmp; tmp = exprList)
{
exprList = exprList->next;
delete tmp;
}
if(associatedList)
{
associatedList->associatedAttrLists->Delete(this);
}
if(myType)
{
delete myType;
}
if(targetType)
{
delete targetType;
}
}
//
// This member function of class AttrList sets myType name.
//
void ClassAd::SetMyTypeName(char *tempName)
{
if(!tempName)
{
if(myType)
{
delete myType;
}
myType = NULL;
return;
}
if(myType)
{
delete myType;
}
myType = new AdType(tempName);
if(!myType)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
}
//
// This member function of class AttrList returns myType name.
//
char *ClassAd::GetMyTypeName()
{
if(!myType)
{
char *temp = ""; // undefined type.
return temp;
}
else
{
return myType->name;
}
}
//
// This member function of class AttrList sets targetType name.
//
void ClassAd::SetTargetTypeName(char *tempName)
{
if(!tempName)
{
if(targetType)
{
delete targetType;
}
targetType = NULL;
return;
}
if(targetType)
{
delete targetType;
}
targetType = new AdType(tempName);
if(!targetType)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
}
//
// This member function of class AttrList returns targetType name.
//
char *ClassAd::GetTargetTypeName()
{
if(!targetType)
{
char *temp = ""; // undefined.
return temp;
}
else
{
return targetType->name;
}
}
//
// This member function of class AttrList returns myType number.
//
int ClassAd::GetMyTypeNumber()
{
if(!myType)
{
return -1; // undefined type.
}
else
{
return myType->number;
}
}
//
// This member function of class AttrList returns targetType number.
//
int ClassAd::GetTargetTypeNumber()
{
if(!targetType)
{
return -1; // undefined type.
}
else
{
return targetType->number;
}
}
//
// This member function tests whether two ClassAds match mutually.
//
int ClassAd::IsAMatch(ClassAd* temp)
{
ExprTree *tree;
EvalResult *val;
if(!temp)
{
return 0;
}
if((GetMyTypeNumber() != temp->GetTargetTypeNumber()) ||
(GetTargetTypeNumber() != temp->GetMyTypeNumber()))
{
return 0; // types don't match.
}
val = new EvalResult;
if(val == NULL)
{
cerr << "Warning : you ran out of memory -- quitting !" << endl;
exit(1);
}
Parse("MY.Requirement", tree); // convention.
tree->EvalTree(this, temp, val); // match in one direction.
if(!val || val->type != LX_BOOL)
{
delete tree;
delete val;
return 0;
}
else
{
if(!val->b)
{
delete tree;
delete val;
return 0;
}
}
tree->EvalTree(temp, this, val); // match in the other direction.
if(!val || val->type != LX_BOOL)
{
delete tree;
delete val;
return 0;
}
else
{
if(!val->b)
{
delete tree;
delete val;
return 0;
}
}
delete tree;
delete val;
return 1;
}
bool operator== (ClassAd &lhs, ClassAd &rhs)
{
return (lhs >= rhs && rhs >= lhs);
}
bool operator<= (ClassAd &lhs, ClassAd &rhs)
{
return (rhs >= lhs);
}
bool operator>= (ClassAd &lhs, ClassAd &rhs)
{
ExprTree *tree;
EvalResult *val;
if (lhs.GetMyTypeNumber() != rhs.GetTargetTypeNumber())
return false;
if ((val = new EvalResult) == NULL)
{
cerr << "Out of memory -- quitting" << endl;
exit (1);
}
Parse ("MY.Requirement", tree);
tree -> EvalTree (&rhs, &lhs, val);
if (!val || val->type != LX_BOOL)
{
delete tree;
delete val;
return false;
}
else
if (!val->b)
{
delete tree;
delete val;
return false;
}
delete tree;
delete val;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// print the whole ClassAd into a file. The expressions are in infix notation.
// Returns FALSE if the file pointer is NULL; TRUE otherwise.
////////////////////////////////////////////////////////////////////////////////
int ClassAd::fPrint(FILE* f)
{
if(!f)
{
return FALSE;
}
fprintf(f, "MyType = ");
fprintf(f, "%c", '"');
if(GetMyTypeName())
{
fprintf(f, "%s", GetMyTypeName());
}
fprintf(f, "%c\n", '"');
fprintf(f, "TargetType = ");
fprintf(f, "%c", '"');
if(GetMyTypeName())
{
fprintf(f, "%s", GetTargetTypeName());
}
fprintf(f, "%c\n", '"');
return AttrList::fPrint(f);
}
// shipping functions for ClassAd -- added by Lei Cao
int ClassAd::put(Stream& s)
{
AttrListElem* elem;
char* line;
int numExprs = 0;
//get the number of expressions
for(elem = exprList; elem; elem = elem->next)
numExprs++;
s.encode();
if(!s.code(numExprs))
return 0;
line = new char[200];
for(elem = exprList; elem; elem = elem->next) {
strcpy(line, "");
elem->tree->PrintToStr(line);
if(!s.code(line)) {
delete [] line;
return 0;
}
}
delete [] line;
if(!s.code(myType->name))
return 0;
if(!s.code(targetType->name))
return 0;
return 1;
}
int ClassAd::get(Stream& s)
{
ExprTree* tree;
char* name;
char* line;
int numExprs;
exprList = NULL;
associatedList = NULL;
tail = NULL;
ptrExpr = NULL;
ptrName = NULL;
myType = NULL;
targetType = NULL;
s.decode();
if(!s.code(numExprs))
return 0;
line = new char[200];
for(int i = 0; i < numExprs; i++) {
if(!s.code(line)) {
delete [] line;
return 0;
}
if(!Parse(line, tree)) {
if(tree->MyType() == LX_ERROR) {
cerr << "Parse error in the incomming stream -- quitting !"
<< endl;
delete [] line;
exit(1);
}
}
else {
cerr << "Parse error in the incomming stream -- quitting !" << endl;
delete [] line;
exit(1);
}
Insert(tree);
strcpy(line, "");
delete tree;
}
delete [] line;
name = new char[50];
if(!s.code(name)) {
delete [] name;
return 0;
}
SetMyTypeName(name);
delete [] name;
name = new char[50];
if(!s.code(name)) {
delete [] name;
return 0;
}
SetTargetTypeName(name);
delete [] name;
return 1;
}
int ClassAd::code(Stream& s)
{
if(s.is_encode())
return put(s);
else
return get(s);
}
int ClassAd::put (XDR *xdrs)
{
char* tmp = NULL;
xdrs->x_op = XDR_ENCODE;
if (!AttrList::put (xdrs))
return 0;
if(myType)
{
if (!xdr_mywrapstring (xdrs, &myType->name))
return 0;
}
else
{
if (!xdr_mywrapstring (xdrs, &tmp))
return 0;
}
if(targetType)
{
if (!xdr_mywrapstring (xdrs, &targetType->name))
return 0;
}
else
{
if (!xdr_mywrapstring (xdrs, &tmp))
return 0;
}
return 1;
}
int ClassAd::get (XDR *xdrs)
{
char buf[100];
char *line = buf;
if (!line) return 0;
xdrs->x_op = XDR_DECODE;
if (!AttrList::get (xdrs))
return 0;
if (!xdr_mywrapstring (xdrs, &line))
return 0;
SetMyTypeName (line);
if (!xdr_mywrapstring (xdrs, &line))
return 0;
SetTargetTypeName (line);
return 1;
}
void ClassAd::
ExchangeExpressions (ClassAd *ad)
{
AttrListElem *tmp1;
AttrListList *tmp2;
int tmp3;
// exchange variables which maintain the attribute list
// see condor_attrlist.h --RR
# define SWAP(a,b,t) {t=a; a=b; b=t;}
SWAP(associatedList, ad->associatedList, tmp2); // this is AttrListList*
SWAP(exprList, ad->exprList, tmp1); // these are AttrListElem*
SWAP(tail, ad->tail, tmp1);
SWAP(ptrExpr, ad->ptrExpr, tmp1);
SWAP(ptrName, ad->ptrName, tmp1);
SWAP (seq, ad->seq, tmp3); // this is an int
// undefine macro to decrease name-space pollution
# undef SWAP
return;
}
<|endoftext|>
|
<commit_before>#include "BuildGraph.hpp"
#include "Graph.hpp"
#include "PropertyMap.hpp"
#include "error.hpp"
#include <boost/assert.hpp>
#include <unordered_map>
#include <map>
namespace configure {
struct BuildGraph::Impl
{
public:
typedef boost::property_map<Graph, boost::vertex_index_t>::type IndexMap;
typedef std::unordered_map<Node::index_type, NodePtr> NodeMap;
typedef std::map<DependencyLink::index_type, DependencyLink> LinkMap;
public:
Graph graph;
IndexMap index_map;
NodeMap node_map;
LinkMap link_map;
FileProperties& properties;
public:
Impl(FileProperties& properties)
: graph()
, index_map(boost::get(boost::vertex_index, graph))
, node_map()
, link_map()
, properties(properties)
{}
};
BuildGraph::BuildGraph(FileProperties& properties)
: _this{new Impl(properties)}
{}
BuildGraph::~BuildGraph()
{}
Graph const& BuildGraph::graph() const
{ return _this->graph; }
DependencyLink& BuildGraph::link(Node const& source, Node const& target)
{
auto ret = boost::edge(source.index, target.index, _this->graph);
if (ret.second)
return _this->link_map.at(ret.first);
DependencyLink::index_type index = _add_edge(source, target);
auto res = _this->link_map.insert(
Impl::LinkMap::value_type(index, DependencyLink(*this, index))
);
if (!res.second)
{
// XXX revert all the things
throw std::runtime_error("Couldn't create the link");
}
return res.first->second;
}
bool BuildGraph::has_link(Node const& source, Node const& target) const
{ return boost::edge(source.index, target.index, _this->graph).second; }
NodePtr const& BuildGraph::node(Node::index_type idx) const
{ return _this->node_map.at(idx); }
DependencyLink const& BuildGraph::link(DependencyLink::index_type idx) const
{ return _this->link_map.at(idx); }
Node::index_type BuildGraph::_add_vertex()
{ return boost::add_vertex(_this->graph); }
DependencyLink::index_type BuildGraph::_add_edge(Node const& source, Node const& target)
{
auto res = boost::add_edge(
source.index,
target.index,
_this->graph
);
if (!res.second)
throw std::runtime_error("Couldn't create the edge");
return res.first;
}
PropertyMap& BuildGraph::properties(Node const& node) const
{
if (!node.is_file())
CONFIGURE_THROW(
error::InvalidNode("Only file node have properties")
<< error::node(_this->node_map[node.index])
);
return _this->properties[node.path()];
}
void BuildGraph::_save(NodePtr& node)
{
BOOST_ASSERT(_this->node_map.find(node->index) == _this->node_map.end());
_this->node_map[node->index] = node;
}
}
<commit_msg>Allow properties on every node kind<commit_after>#include "BuildGraph.hpp"
#include "Graph.hpp"
#include "PropertyMap.hpp"
#include "error.hpp"
#include <boost/assert.hpp>
#include <unordered_map>
#include <map>
namespace configure {
struct BuildGraph::Impl
{
public:
typedef boost::property_map<Graph, boost::vertex_index_t>::type IndexMap;
typedef std::unordered_map<Node::index_type, NodePtr> NodeMap;
typedef std::map<DependencyLink::index_type, DependencyLink> LinkMap;
public:
Graph graph;
IndexMap index_map;
NodeMap node_map;
LinkMap link_map;
FileProperties& properties;
public:
Impl(FileProperties& properties)
: graph()
, index_map(boost::get(boost::vertex_index, graph))
, node_map()
, link_map()
, properties(properties)
{}
};
BuildGraph::BuildGraph(FileProperties& properties)
: _this{new Impl(properties)}
{}
BuildGraph::~BuildGraph()
{}
Graph const& BuildGraph::graph() const
{ return _this->graph; }
DependencyLink& BuildGraph::link(Node const& source, Node const& target)
{
auto ret = boost::edge(source.index, target.index, _this->graph);
if (ret.second)
return _this->link_map.at(ret.first);
DependencyLink::index_type index = _add_edge(source, target);
auto res = _this->link_map.insert(
Impl::LinkMap::value_type(index, DependencyLink(*this, index))
);
if (!res.second)
{
// XXX revert all the things
throw std::runtime_error("Couldn't create the link");
}
return res.first->second;
}
bool BuildGraph::has_link(Node const& source, Node const& target) const
{ return boost::edge(source.index, target.index, _this->graph).second; }
NodePtr const& BuildGraph::node(Node::index_type idx) const
{ return _this->node_map.at(idx); }
DependencyLink const& BuildGraph::link(DependencyLink::index_type idx) const
{ return _this->link_map.at(idx); }
Node::index_type BuildGraph::_add_vertex()
{ return boost::add_vertex(_this->graph); }
DependencyLink::index_type BuildGraph::_add_edge(Node const& source, Node const& target)
{
auto res = boost::add_edge(
source.index,
target.index,
_this->graph
);
if (!res.second)
throw std::runtime_error("Couldn't create the edge");
return res.first;
}
PropertyMap& BuildGraph::properties(Node const& node) const
{
//if (!node.is_file())
// CONFIGURE_THROW(
// error::InvalidNode("Only file node have properties")
// << error::node(_this->node_map[node.index])
// );
return _this->properties[node.path()];
}
void BuildGraph::_save(NodePtr& node)
{
BOOST_ASSERT(_this->node_map.find(node->index) == _this->node_map.end());
_this->node_map[node->index] = node;
}
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2014, 2015, 2016, 2017, 2018 CNRS
// Authors: Florent Lamiraux, Joseph Mirabel, Diane Bury
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/core/continuous-validation.hh>
#include <limits>
#include <pinocchio/multibody/geometry.hpp>
#include <hpp/util/debug.hh>
#include <hpp/core/collision-path-validation-report.hh>
#include <hpp/core/straight-path.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/continuous-validation/initializer.hh>
#include <hpp/core/continuous-validation/solid-solid-collision.hh>
#include <iterator>
namespace hpp {
namespace core {
using continuousValidation::BodyPairCollisions_t;
using continuousValidation::SolidSolidCollision;
/// Validate interval centered on a path parameter
/// \param bodyPairCollisions a reference to the pair with smallest interval.
/// \param config Configuration at abscissa tmin on the path.
/// \param t parameter value in the path interval of definition
/// \retval interval interval validated for all validation elements
/// \retval report reason why the interval is not valid,
/// \return true if the configuration is collision free for this parameter
/// value, false otherwise.
bool ContinuousValidation::validateConfiguration(BodyPairCollisions_t& bodyPairCollisions,
const Configuration_t &config, const value_type &t,
interval_t &interval, PathValidationReportPtr_t &report)
{
interval.first = -std::numeric_limits <value_type>::infinity ();
interval.second = std::numeric_limits <value_type>::infinity ();
robot_->currentConfiguration (config);
robot_->computeFramesForwardKinematics ();
robot_->updateGeometryPlacements ();
hpp::pinocchio::DeviceSync robot (robot_);
robot.currentConfiguration (config);
robot.computeForwardKinematics();
robot.updateGeometryPlacements();
BodyPairCollisions_t::iterator smallestInterval = bodyPairCollisions.begin();
if (!validateIntervals<BodyPairCollisions_t, CollisionValidationReportPtr_t>
(bodyPairCollisions, t, interval, report,
smallestInterval, robot.d()))
return false;
// Put the smallest interval first so that, at next iteration,
// collision pairs with large interval are not computed.
if (bodyPairCollisions.size() > 1 && smallestInterval != bodyPairCollisions.begin())
std::iter_swap (bodyPairCollisions.begin(), smallestInterval);
return true;
}
bool ContinuousValidation::validate(const PathPtr_t &path, bool reverse, PathPtr_t &validPart,
PathValidationReportPtr_t &report)
{
if (PathVectorPtr_t pv = HPP_DYNAMIC_PTR_CAST(PathVector, path))
{
PathVectorPtr_t validPathVector = PathVector::create(path->outputSize(), path->outputDerivativeSize());
validPart = validPathVector;
PathPtr_t localValidPart;
if (reverse)
{
value_type param = path->length();
std::deque<PathPtr_t> paths;
for (std::size_t i = pv->numberPaths() + 1; i != 0; --i)
{
PathPtr_t localPath(pv->pathAtRank(i - 1));
if (validate(localPath, reverse, localValidPart, report))
{
paths.push_front(localPath->copy());
param -= localPath->length();
}
else
{
report->parameter += param - localPath->length();
paths.push_front(localValidPart->copy());
for (std::deque<PathPtr_t>::const_iterator it = paths.begin();
it != paths.end(); ++it)
{
validPathVector->appendPath(*it);
}
return false;
}
}
return true;
}
else
{
value_type param = 0;
for (std::size_t i = 0; i < pv->numberPaths(); ++i)
{
PathPtr_t localPath(pv->pathAtRank(i));
if (validate(localPath, reverse, localValidPart, report))
{
validPathVector->appendPath(localPath->copy());
param += localPath->length();
}
else
{
report->parameter += param;
validPathVector->appendPath(localValidPart->copy());
return false;
}
}
return true;
}
}
BodyPairCollisions_t* bpc;
if (!bodyPairCollisionPool_.available()) {
// Add an element
bpc = new BodyPairCollisions_t(bodyPairCollisions_.size());
for (std::size_t i = 0; i < bpc->size(); ++i)
(*bpc)[i] = bodyPairCollisions_[i]->copy();
bodyPairCollisionPool_.push_back (bpc);
}
bpc = bodyPairCollisionPool_.acquire();
bool ret = validateStraightPath(*bpc, path, reverse, validPart, report);
bodyPairCollisionPool_.release (bpc);
return ret;
}
void ContinuousValidation::addObstacle(const CollisionObjectConstPtr_t &object)
{
for (size_type idx = 0; idx < robot_->nbJoints(); ++idx) {
JointPtr_t joint = robot_->jointAt (idx);
BodyPtr_t body = joint->linkedBody ();
if (body)
{
ConstObjectStdVector_t objects;
objects.push_back(object);
bodyPairCollisions_.push_back(SolidSolidCollision::create (joint, objects, tolerance_));
bodyPairCollisionPool_.clear();
}
}
}
void ContinuousValidation::setPath(BodyPairCollisions_t& bodyPairCollisions,
const PathPtr_t &path, bool reverse)
{
for (BodyPairCollisions_t::iterator itPair = bodyPairCollisions.begin ();
itPair != bodyPairCollisions.end (); ++itPair) {
(*itPair)->path (path, reverse);
}
}
void ContinuousValidation::removeObstacleFromJoint(const JointPtr_t &joint, const CollisionObjectConstPtr_t &obstacle)
{
assert (joint);
bool removed = false;
for (BodyPairCollisions_t::iterator itPair = bodyPairCollisions_.begin();
itPair != bodyPairCollisions_.end(); ++itPair)
{
// If jointA == joint and jointB is the root joint.
if ((*itPair)->indexJointA() == (size_type)joint->index()
&& (*itPair)->indexJointB() == 0)
{
if ((*itPair)->removeObjectTo_b(obstacle))
{
removed = true;
if ((*itPair)->pairs().empty())
{
bodyPairCollisions_.erase(itPair);
bodyPairCollisionPool_.clear();
}
}
}
}
if (!removed)
{
std::ostringstream oss;
oss << "ContinuousValidation::removeObstacleFromJoint: obstacle \""
<< obstacle->name() << "\" is not registered as obstacle for joint \"" << joint->name()
<< "\".";
throw std::runtime_error(oss.str());
}
}
void ContinuousValidation::filterCollisionPairs(const RelativeMotion::matrix_type &relMotion)
{
// Loop over collision pairs and remove disabled ones.
size_type ia, ib;
for (BodyPairCollisions_t::iterator _colPair = bodyPairCollisions_.begin();
_colPair != bodyPairCollisions_.end();)
{
ia = (*_colPair)->indexJointA ();
ib = (*_colPair)->indexJointB ();
if (ia < 0 || ib < 0) {
++_colPair;
continue;}
switch (relMotion(ia, ib))
{
case RelativeMotion::Parameterized:
hppDout(info, "Parameterized collision pairs treated as Constrained");
case RelativeMotion::Constrained:
hppDout(info, "Disabling collision pair " << **_colPair);
disabledBodyPairCollisions_.push_back(*_colPair);
_colPair = bodyPairCollisions_.erase(_colPair);
break;
case RelativeMotion::Unconstrained:
++_colPair;
break;
default:
hppDout(warning, "RelativeMotionType not understood");
++_colPair;
break;
}
}
bodyPairCollisionPool_.clear();
}
void ContinuousValidation::init (ContinuousValidationWkPtr_t weak)
{
weak_ = weak;
initializer_->initContinuousValidation(weak_);
}
void ContinuousValidation::changeInitializer (continuousValidation::InitializerPtr_t initializer)
{
initializer_ = initializer;
initializer_->initContinuousValidation(weak_);
initializer_->reset();
initializer_->initialize();
}
ContinuousValidation::~ContinuousValidation()
{
}
ContinuousValidation::ContinuousValidation(const DevicePtr_t &robot, const value_type &tolerance):
robot_(robot), tolerance_(tolerance), bodyPairCollisions_(),
weak_()
{
initializer_ = continuousValidation::Initializer::create();
if (tolerance < 0) {
throw std::runtime_error ("tolerance should be non-negative.");
}
}
} // namespace core
} // namespace hpp
<commit_msg>[Minor] Add missing linebreak<commit_after>//
// Copyright (c) 2014, 2015, 2016, 2017, 2018 CNRS
// Authors: Florent Lamiraux, Joseph Mirabel, Diane Bury
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/core/continuous-validation.hh>
#include <limits>
#include <pinocchio/multibody/geometry.hpp>
#include <hpp/util/debug.hh>
#include <hpp/core/collision-path-validation-report.hh>
#include <hpp/core/straight-path.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/continuous-validation/initializer.hh>
#include <hpp/core/continuous-validation/solid-solid-collision.hh>
#include <iterator>
namespace hpp {
namespace core {
using continuousValidation::BodyPairCollisions_t;
using continuousValidation::SolidSolidCollision;
/// Validate interval centered on a path parameter
/// \param bodyPairCollisions a reference to the pair with smallest interval.
/// \param config Configuration at abscissa tmin on the path.
/// \param t parameter value in the path interval of definition
/// \retval interval interval validated for all validation elements
/// \retval report reason why the interval is not valid,
/// \return true if the configuration is collision free for this parameter
/// value, false otherwise.
bool ContinuousValidation::validateConfiguration(BodyPairCollisions_t& bodyPairCollisions,
const Configuration_t &config, const value_type &t,
interval_t &interval, PathValidationReportPtr_t &report)
{
interval.first = -std::numeric_limits <value_type>::infinity ();
interval.second = std::numeric_limits <value_type>::infinity ();
robot_->currentConfiguration (config);
robot_->computeFramesForwardKinematics ();
robot_->updateGeometryPlacements ();
hpp::pinocchio::DeviceSync robot (robot_);
robot.currentConfiguration (config);
robot.computeForwardKinematics();
robot.updateGeometryPlacements();
BodyPairCollisions_t::iterator smallestInterval = bodyPairCollisions.begin();
if (!validateIntervals<BodyPairCollisions_t, CollisionValidationReportPtr_t>
(bodyPairCollisions, t, interval, report,
smallestInterval, robot.d()))
return false;
// Put the smallest interval first so that, at next iteration,
// collision pairs with large interval are not computed.
if (bodyPairCollisions.size() > 1 && smallestInterval != bodyPairCollisions.begin())
std::iter_swap (bodyPairCollisions.begin(), smallestInterval);
return true;
}
bool ContinuousValidation::validate(const PathPtr_t &path, bool reverse, PathPtr_t &validPart,
PathValidationReportPtr_t &report)
{
if (PathVectorPtr_t pv = HPP_DYNAMIC_PTR_CAST(PathVector, path))
{
PathVectorPtr_t validPathVector = PathVector::create(path->outputSize(), path->outputDerivativeSize());
validPart = validPathVector;
PathPtr_t localValidPart;
if (reverse)
{
value_type param = path->length();
std::deque<PathPtr_t> paths;
for (std::size_t i = pv->numberPaths() + 1; i != 0; --i)
{
PathPtr_t localPath(pv->pathAtRank(i - 1));
if (validate(localPath, reverse, localValidPart, report))
{
paths.push_front(localPath->copy());
param -= localPath->length();
}
else
{
report->parameter += param - localPath->length();
paths.push_front(localValidPart->copy());
for (std::deque<PathPtr_t>::const_iterator it = paths.begin();
it != paths.end(); ++it)
{
validPathVector->appendPath(*it);
}
return false;
}
}
return true;
}
else
{
value_type param = 0;
for (std::size_t i = 0; i < pv->numberPaths(); ++i)
{
PathPtr_t localPath(pv->pathAtRank(i));
if (validate(localPath, reverse, localValidPart, report))
{
validPathVector->appendPath(localPath->copy());
param += localPath->length();
}
else
{
report->parameter += param;
validPathVector->appendPath(localValidPart->copy());
return false;
}
}
return true;
}
}
BodyPairCollisions_t* bpc;
if (!bodyPairCollisionPool_.available()) {
// Add an element
bpc = new BodyPairCollisions_t(bodyPairCollisions_.size());
for (std::size_t i = 0; i < bpc->size(); ++i)
(*bpc)[i] = bodyPairCollisions_[i]->copy();
bodyPairCollisionPool_.push_back (bpc);
}
bpc = bodyPairCollisionPool_.acquire();
bool ret = validateStraightPath(*bpc, path, reverse, validPart, report);
bodyPairCollisionPool_.release (bpc);
return ret;
}
void ContinuousValidation::addObstacle(const CollisionObjectConstPtr_t &object)
{
for (size_type idx = 0; idx < robot_->nbJoints(); ++idx) {
JointPtr_t joint = robot_->jointAt (idx);
BodyPtr_t body = joint->linkedBody ();
if (body)
{
ConstObjectStdVector_t objects;
objects.push_back(object);
bodyPairCollisions_.push_back(SolidSolidCollision::create (joint, objects, tolerance_));
bodyPairCollisionPool_.clear();
}
}
}
void ContinuousValidation::setPath(BodyPairCollisions_t& bodyPairCollisions,
const PathPtr_t &path, bool reverse)
{
for (BodyPairCollisions_t::iterator itPair = bodyPairCollisions.begin ();
itPair != bodyPairCollisions.end (); ++itPair) {
(*itPair)->path (path, reverse);
}
}
void ContinuousValidation::removeObstacleFromJoint(const JointPtr_t &joint, const CollisionObjectConstPtr_t &obstacle)
{
assert (joint);
bool removed = false;
for (BodyPairCollisions_t::iterator itPair = bodyPairCollisions_.begin();
itPair != bodyPairCollisions_.end(); ++itPair)
{
// If jointA == joint and jointB is the root joint.
if ((*itPair)->indexJointA() == (size_type)joint->index()
&& (*itPair)->indexJointB() == 0)
{
if ((*itPair)->removeObjectTo_b(obstacle))
{
removed = true;
if ((*itPair)->pairs().empty())
{
bodyPairCollisions_.erase(itPair);
bodyPairCollisionPool_.clear();
}
}
}
}
if (!removed)
{
std::ostringstream oss;
oss << "ContinuousValidation::removeObstacleFromJoint: obstacle \""
<< obstacle->name() << "\" is not registered as obstacle for joint \"" << joint->name()
<< "\".";
throw std::runtime_error(oss.str());
}
}
void ContinuousValidation::filterCollisionPairs(const RelativeMotion::matrix_type &relMotion)
{
// Loop over collision pairs and remove disabled ones.
size_type ia, ib;
for (BodyPairCollisions_t::iterator _colPair = bodyPairCollisions_.begin();
_colPair != bodyPairCollisions_.end();)
{
ia = (*_colPair)->indexJointA ();
ib = (*_colPair)->indexJointB ();
if (ia < 0 || ib < 0) {
++_colPair;
continue;
}
switch (relMotion(ia, ib))
{
case RelativeMotion::Parameterized:
hppDout(info, "Parameterized collision pairs treated as Constrained");
case RelativeMotion::Constrained:
hppDout(info, "Disabling collision pair " << **_colPair);
disabledBodyPairCollisions_.push_back(*_colPair);
_colPair = bodyPairCollisions_.erase(_colPair);
break;
case RelativeMotion::Unconstrained:
++_colPair;
break;
default:
hppDout(warning, "RelativeMotionType not understood");
++_colPair;
break;
}
}
bodyPairCollisionPool_.clear();
}
void ContinuousValidation::init (ContinuousValidationWkPtr_t weak)
{
weak_ = weak;
initializer_->initContinuousValidation(weak_);
}
void ContinuousValidation::changeInitializer (continuousValidation::InitializerPtr_t initializer)
{
initializer_ = initializer;
initializer_->initContinuousValidation(weak_);
initializer_->reset();
initializer_->initialize();
}
ContinuousValidation::~ContinuousValidation()
{
}
ContinuousValidation::ContinuousValidation(const DevicePtr_t &robot, const value_type &tolerance):
robot_(robot), tolerance_(tolerance), bodyPairCollisions_(),
weak_()
{
initializer_ = continuousValidation::Initializer::create();
if (tolerance < 0) {
throw std::runtime_error ("tolerance should be non-negative.");
}
}
} // namespace core
} // namespace hpp
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC 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 <grpc++/channel.h>
#include <memory>
#include <grpc++/client_context.h>
#include <grpc++/completion_queue.h>
#include <grpc++/impl/call.h>
#include <grpc++/impl/codegen/completion_queue_tag.h>
#include <grpc++/impl/grpc_library.h>
#include <grpc++/impl/rpc_method.h>
#include <grpc++/security/credentials.h>
#include <grpc++/support/channel_arguments.h>
#include <grpc++/support/config.h>
#include <grpc++/support/status.h>
#include <grpc++/support/time.h>
#include <grpc/grpc.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
#include <grpc/support/useful.h>
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/support/env.h"
#include "src/core/lib/support/string.h"
namespace grpc {
namespace {
int kConnectivityCheckIntervalMsec = 500;
void WatchStateChange(void* arg);
void InitConnectivityWatcherOnce();
class TagSaver final : public CompletionQueueTag {
public:
explicit TagSaver(void* tag) : tag_(tag) {}
~TagSaver() override {}
bool FinalizeResult(void** tag, bool* status) override {
*tag = tag_;
delete this;
return true;
}
private:
void* tag_;
};
// Constantly watches channel connectivity status to reconnect a transiently
// disconnected channel. This is a temporary work-around before we have retry
// support.
class ChannelConnectivityWatcher {
public:
ChannelConnectivityWatcher() : thd_id_(0) {
char* env = gpr_getenv("GRPC_DISABLE_CHANNEL_CONNECTIVITY_WATCHER");
bool disabled = false;
if (env != nullptr) {
static const char* truthy[] = {"yes", "true", "1"};
for (size_t i = 0; i < GPR_ARRAY_SIZE(truthy); i++) {
if (0 == gpr_stricmp(env, truthy[i])) {
disabled = true;
break;
}
}
}
gpr_free(env);
if (!disabled) {
gpr_ref_init(&ref_, 0);
gpr_thd_options options = gpr_thd_options_default();
gpr_thd_options_set_detached(&options);
gpr_thd_new(&thd_id_, &WatchStateChange, this, &options);
}
}
void WatchStateChangeImpl() {
bool ok = false;
void* tag = NULL;
CompletionQueue::NextStatus status = CompletionQueue::GOT_EVENT;
while (true) {
status = cq_.AsyncNext(&tag, &ok, gpr_inf_past(GPR_CLOCK_REALTIME));
// Make sure we've seen 2 TIMEOUTs before going to sleep
if (status == CompletionQueue::TIMEOUT) {
status = cq_.AsyncNext(&tag, &ok, gpr_inf_past(GPR_CLOCK_REALTIME));
if (status == CompletionQueue::TIMEOUT) {
gpr_sleep_until(
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(kConnectivityCheckIntervalMsec,
GPR_TIMESPAN)));
continue;
}
}
ChannelState* channel_state = static_cast<ChannelState*>(tag);
channel_state->state =
grpc_channel_check_connectivity_state(channel_state->channel, false);
if (channel_state->state == GRPC_CHANNEL_SHUTDOWN) {
void* shutdown_tag = NULL;
channel_state->shutdown_cq.Next(&shutdown_tag, &ok);
delete channel_state;
if (gpr_unref(&ref_)) {
gpr_mu_lock(&g_watcher_mu_);
delete g_watcher_;
g_watcher_ = nullptr;
gpr_mu_unlock(&g_watcher_mu_);
break;
}
} else {
TagSaver* tag_saver = new TagSaver(channel_state);
grpc_channel_watch_connectivity_state(
channel_state->channel, channel_state->state,
gpr_inf_future(GPR_CLOCK_REALTIME), cq_.cq(), tag_saver);
}
}
}
static void StartWatching(grpc_channel* channel) {
gpr_once_init(&g_connectivity_watcher_once_, InitConnectivityWatcherOnce);
gpr_mu_lock(&g_watcher_mu_);
if (g_watcher_ == nullptr) {
g_watcher_ = new ChannelConnectivityWatcher();
}
g_watcher_->StartWatchingLocked(channel);
gpr_mu_unlock(&g_watcher_mu_);
}
static void InitOnce() { gpr_mu_init(&g_watcher_mu_); }
private:
void StartWatchingLocked(grpc_channel* channel) {
if (thd_id_ != 0) {
gpr_ref(&ref_);
ChannelState* channel_state = new ChannelState(channel);
// The first grpc_channel_watch_connectivity_state() is not used to
// monitor the channel state change, but to hold a reference of the
// c channel. So that WatchStateChangeImpl() can observe state ==
// GRPC_CHANNEL_SHUTDOWN before the channel gets destroyed.
grpc_channel_watch_connectivity_state(
channel_state->channel, channel_state->state,
gpr_inf_future(GPR_CLOCK_REALTIME), channel_state->shutdown_cq.cq(),
new TagSaver(nullptr));
grpc_channel_watch_connectivity_state(
channel_state->channel, channel_state->state,
gpr_inf_future(GPR_CLOCK_REALTIME), cq_.cq(),
new TagSaver(channel_state));
}
}
struct ChannelState {
explicit ChannelState(grpc_channel* channel)
: channel(channel), state(GRPC_CHANNEL_IDLE){};
grpc_channel* channel;
grpc_connectivity_state state;
CompletionQueue shutdown_cq;
};
gpr_thd_id thd_id_;
CompletionQueue cq_;
gpr_refcount ref_;
static gpr_once g_connectivity_watcher_once_;
static gpr_mu g_watcher_mu_;
static ChannelConnectivityWatcher* g_watcher_;
};
gpr_once ChannelConnectivityWatcher::g_connectivity_watcher_once_ =
GPR_ONCE_INIT;
gpr_mu ChannelConnectivityWatcher::g_watcher_mu_;
ChannelConnectivityWatcher* ChannelConnectivityWatcher::g_watcher_ = nullptr;
void WatchStateChange(void* arg) {
ChannelConnectivityWatcher* watcher =
static_cast<ChannelConnectivityWatcher*>(arg);
watcher->WatchStateChangeImpl();
}
void InitConnectivityWatcherOnce() { ChannelConnectivityWatcher::InitOnce(); };
ChannelConnectivityWatcher channel_connectivity_watcher;
} // namespace
static internal::GrpcLibraryInitializer g_gli_initializer;
Channel::Channel(const grpc::string& host, grpc_channel* channel)
: host_(host), c_channel_(channel) {
g_gli_initializer.summon();
if (grpc_channel_support_connectivity_watcher(channel)) {
ChannelConnectivityWatcher::StartWatching(channel);
}
}
Channel::~Channel() {
grpc_channel_destroy(c_channel_);
}
namespace {
grpc::string GetChannelInfoField(grpc_channel* channel,
grpc_channel_info* channel_info,
char*** channel_info_field) {
char* value = NULL;
memset(channel_info, 0, sizeof(*channel_info));
*channel_info_field = &value;
grpc_channel_get_info(channel, channel_info);
if (value == NULL) return "";
grpc::string result = value;
gpr_free(value);
return result;
}
} // namespace
grpc::string Channel::GetLoadBalancingPolicyName() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.lb_policy_name);
}
grpc::string Channel::GetServiceConfigJSON() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.service_config_json);
}
Call Channel::CreateCall(const RpcMethod& method, ClientContext* context,
CompletionQueue* cq) {
const bool kRegistered = method.channel_tag() && context->authority().empty();
grpc_call* c_call = NULL;
if (kRegistered) {
c_call = grpc_channel_create_registered_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(),
method.channel_tag(), context->raw_deadline(), nullptr);
} else {
const char* host_str = NULL;
if (!context->authority().empty()) {
host_str = context->authority_.c_str();
} else if (!host_.empty()) {
host_str = host_.c_str();
}
grpc_slice method_slice = SliceFromCopiedString(method.name());
grpc_slice host_slice;
if (host_str != nullptr) {
host_slice = SliceFromCopiedString(host_str);
}
c_call = grpc_channel_create_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
nullptr);
grpc_slice_unref(method_slice);
if (host_str != nullptr) {
grpc_slice_unref(host_slice);
}
}
grpc_census_call_set_context(c_call, context->census_context());
context->set_call(c_call, shared_from_this());
return Call(c_call, this, cq);
}
void Channel::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) {
static const size_t MAX_OPS = 8;
size_t nops = 0;
grpc_op cops[MAX_OPS];
ops->FillOps(call->call(), cops, &nops);
GPR_ASSERT(GRPC_CALL_OK ==
grpc_call_start_batch(call->call(), cops, nops, ops, nullptr));
}
void* Channel::RegisterMethod(const char* method) {
return grpc_channel_register_call(
c_channel_, method, host_.empty() ? NULL : host_.c_str(), nullptr);
}
grpc_connectivity_state Channel::GetState(bool try_to_connect) {
return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
}
void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline,
CompletionQueue* cq, void* tag) {
TagSaver* tag_saver = new TagSaver(tag);
grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
cq->cq(), tag_saver);
}
bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) {
CompletionQueue cq;
bool ok = false;
void* tag = NULL;
NotifyOnStateChangeImpl(last_observed, deadline, &cq, NULL);
cq.Next(&tag, &ok);
GPR_ASSERT(tag == NULL);
return ok;
}
} // namespace grpc
<commit_msg>Privatize ChannelConnectivityWatcher members<commit_after>/*
*
* Copyright 2015 gRPC 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 <grpc++/channel.h>
#include <memory>
#include <grpc++/client_context.h>
#include <grpc++/completion_queue.h>
#include <grpc++/impl/call.h>
#include <grpc++/impl/codegen/completion_queue_tag.h>
#include <grpc++/impl/grpc_library.h>
#include <grpc++/impl/rpc_method.h>
#include <grpc++/security/credentials.h>
#include <grpc++/support/channel_arguments.h>
#include <grpc++/support/config.h>
#include <grpc++/support/status.h>
#include <grpc++/support/time.h>
#include <grpc/grpc.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
#include <grpc/support/useful.h>
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/support/env.h"
#include "src/core/lib/support/string.h"
namespace grpc {
namespace {
int kConnectivityCheckIntervalMsec = 500;
void WatchStateChange(void* arg);
void InitConnectivityWatcherOnce();
class TagSaver final : public CompletionQueueTag {
public:
explicit TagSaver(void* tag) : tag_(tag) {}
~TagSaver() override {}
bool FinalizeResult(void** tag, bool* status) override {
*tag = tag_;
delete this;
return true;
}
private:
void* tag_;
};
// Constantly watches channel connectivity status to reconnect a transiently
// disconnected channel. This is a temporary work-around before we have retry
// support.
class ChannelConnectivityWatcher {
public:
static void StartWatching(grpc_channel* channel) {
char* env = gpr_getenv("GRPC_DISABLE_CHANNEL_CONNECTIVITY_WATCHER");
bool disabled = false;
if (env != nullptr) {
static const char* truthy[] = {"yes", "true", "1"};
for (size_t i = 0; i < GPR_ARRAY_SIZE(truthy); i++) {
if (0 == gpr_stricmp(env, truthy[i])) {
disabled = true;
break;
}
}
}
gpr_free(env);
if (!disabled) {
gpr_once_init(&g_connectivity_watcher_once_, InitConnectivityWatcherOnce);
gpr_mu_lock(&g_watcher_mu_);
if (g_watcher_ == nullptr) {
g_watcher_ = new ChannelConnectivityWatcher();
}
g_watcher_->StartWatchingLocked(channel);
gpr_mu_unlock(&g_watcher_mu_);
}
}
private:
ChannelConnectivityWatcher() {
gpr_ref_init(&ref_, 0);
gpr_thd_options options = gpr_thd_options_default();
gpr_thd_options_set_detached(&options);
gpr_thd_new(&thd_id_, &WatchStateChange, this, &options);
}
void WatchStateChangeImpl() {
bool ok = false;
void* tag = NULL;
CompletionQueue::NextStatus status = CompletionQueue::GOT_EVENT;
while (true) {
status = cq_.AsyncNext(&tag, &ok, gpr_inf_past(GPR_CLOCK_REALTIME));
// Make sure we've seen 2 TIMEOUTs before going to sleep
if (status == CompletionQueue::TIMEOUT) {
status = cq_.AsyncNext(&tag, &ok, gpr_inf_past(GPR_CLOCK_REALTIME));
if (status == CompletionQueue::TIMEOUT) {
gpr_sleep_until(
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(kConnectivityCheckIntervalMsec,
GPR_TIMESPAN)));
continue;
}
}
ChannelState* channel_state = static_cast<ChannelState*>(tag);
channel_state->state =
grpc_channel_check_connectivity_state(channel_state->channel, false);
if (channel_state->state == GRPC_CHANNEL_SHUTDOWN) {
void* shutdown_tag = NULL;
channel_state->shutdown_cq.Next(&shutdown_tag, &ok);
delete channel_state;
if (gpr_unref(&ref_)) {
gpr_mu_lock(&g_watcher_mu_);
delete g_watcher_;
g_watcher_ = nullptr;
gpr_mu_unlock(&g_watcher_mu_);
break;
}
} else {
TagSaver* tag_saver = new TagSaver(channel_state);
grpc_channel_watch_connectivity_state(
channel_state->channel, channel_state->state,
gpr_inf_future(GPR_CLOCK_REALTIME), cq_.cq(), tag_saver);
}
}
}
void StartWatchingLocked(grpc_channel* channel) {
if (thd_id_ != 0) {
gpr_ref(&ref_);
ChannelState* channel_state = new ChannelState(channel);
// The first grpc_channel_watch_connectivity_state() is not used to
// monitor the channel state change, but to hold a reference of the
// c channel. So that WatchStateChangeImpl() can observe state ==
// GRPC_CHANNEL_SHUTDOWN before the channel gets destroyed.
grpc_channel_watch_connectivity_state(
channel_state->channel, channel_state->state,
gpr_inf_future(GPR_CLOCK_REALTIME), channel_state->shutdown_cq.cq(),
new TagSaver(nullptr));
grpc_channel_watch_connectivity_state(
channel_state->channel, channel_state->state,
gpr_inf_future(GPR_CLOCK_REALTIME), cq_.cq(),
new TagSaver(channel_state));
}
}
static void InitOnce() { gpr_mu_init(&g_watcher_mu_); }
friend void WatchStateChange(void* arg);
friend void InitConnectivityWatcherOnce();
struct ChannelState {
explicit ChannelState(grpc_channel* channel)
: channel(channel), state(GRPC_CHANNEL_IDLE){};
grpc_channel* channel;
grpc_connectivity_state state;
CompletionQueue shutdown_cq;
};
gpr_thd_id thd_id_;
CompletionQueue cq_;
gpr_refcount ref_;
static gpr_once g_connectivity_watcher_once_;
static gpr_mu g_watcher_mu_;
// protected under g_watcher_mu_
static ChannelConnectivityWatcher* g_watcher_;
};
gpr_once ChannelConnectivityWatcher::g_connectivity_watcher_once_ =
GPR_ONCE_INIT;
gpr_mu ChannelConnectivityWatcher::g_watcher_mu_;
ChannelConnectivityWatcher* ChannelConnectivityWatcher::g_watcher_ = nullptr;
void WatchStateChange(void* arg) {
ChannelConnectivityWatcher* watcher =
static_cast<ChannelConnectivityWatcher*>(arg);
watcher->WatchStateChangeImpl();
}
void InitConnectivityWatcherOnce() { ChannelConnectivityWatcher::InitOnce(); };
} // namespace
static internal::GrpcLibraryInitializer g_gli_initializer;
Channel::Channel(const grpc::string& host, grpc_channel* channel)
: host_(host), c_channel_(channel) {
g_gli_initializer.summon();
if (grpc_channel_support_connectivity_watcher(channel)) {
ChannelConnectivityWatcher::StartWatching(channel);
}
}
Channel::~Channel() {
grpc_channel_destroy(c_channel_);
}
namespace {
grpc::string GetChannelInfoField(grpc_channel* channel,
grpc_channel_info* channel_info,
char*** channel_info_field) {
char* value = NULL;
memset(channel_info, 0, sizeof(*channel_info));
*channel_info_field = &value;
grpc_channel_get_info(channel, channel_info);
if (value == NULL) return "";
grpc::string result = value;
gpr_free(value);
return result;
}
} // namespace
grpc::string Channel::GetLoadBalancingPolicyName() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.lb_policy_name);
}
grpc::string Channel::GetServiceConfigJSON() const {
grpc_channel_info channel_info;
return GetChannelInfoField(c_channel_, &channel_info,
&channel_info.service_config_json);
}
Call Channel::CreateCall(const RpcMethod& method, ClientContext* context,
CompletionQueue* cq) {
const bool kRegistered = method.channel_tag() && context->authority().empty();
grpc_call* c_call = NULL;
if (kRegistered) {
c_call = grpc_channel_create_registered_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(),
method.channel_tag(), context->raw_deadline(), nullptr);
} else {
const char* host_str = NULL;
if (!context->authority().empty()) {
host_str = context->authority_.c_str();
} else if (!host_.empty()) {
host_str = host_.c_str();
}
grpc_slice method_slice = SliceFromCopiedString(method.name());
grpc_slice host_slice;
if (host_str != nullptr) {
host_slice = SliceFromCopiedString(host_str);
}
c_call = grpc_channel_create_call(
c_channel_, context->propagate_from_call_,
context->propagation_options_.c_bitmask(), cq->cq(), method_slice,
host_str == nullptr ? nullptr : &host_slice, context->raw_deadline(),
nullptr);
grpc_slice_unref(method_slice);
if (host_str != nullptr) {
grpc_slice_unref(host_slice);
}
}
grpc_census_call_set_context(c_call, context->census_context());
context->set_call(c_call, shared_from_this());
return Call(c_call, this, cq);
}
void Channel::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) {
static const size_t MAX_OPS = 8;
size_t nops = 0;
grpc_op cops[MAX_OPS];
ops->FillOps(call->call(), cops, &nops);
GPR_ASSERT(GRPC_CALL_OK ==
grpc_call_start_batch(call->call(), cops, nops, ops, nullptr));
}
void* Channel::RegisterMethod(const char* method) {
return grpc_channel_register_call(
c_channel_, method, host_.empty() ? NULL : host_.c_str(), nullptr);
}
grpc_connectivity_state Channel::GetState(bool try_to_connect) {
return grpc_channel_check_connectivity_state(c_channel_, try_to_connect);
}
void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline,
CompletionQueue* cq, void* tag) {
TagSaver* tag_saver = new TagSaver(tag);
grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline,
cq->cq(), tag_saver);
}
bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed,
gpr_timespec deadline) {
CompletionQueue cq;
bool ok = false;
void* tag = NULL;
NotifyOnStateChangeImpl(last_observed, deadline, &cq, NULL);
cq.Next(&tag, &ok);
GPR_ASSERT(tag == NULL);
return ok;
}
} // namespace grpc
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
*/
#ifndef __CPU_O3_SPARC_DYN_INST_HH__
#define __CPU_O3_SPARC_DYN_INST_HH__
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/types.hh"
#include "cpu/base_dyn_inst.hh"
#include "cpu/inst_seq.hh"
#include "cpu/o3/sparc/cpu.hh"
#include "cpu/o3/sparc/impl.hh"
class Packet;
/**
* Mostly implementation & ISA specific SparcDynInst. As with most
* other classes in the new CPU model, it is templated on the Impl to
* allow for passing in of all types, such as the CPU type and the ISA
* type. The SparcDynInst serves as the primary interface to the CPU
* for instructions that are executing.
*/
template <class Impl>
class SparcDynInst : public BaseDynInst<Impl>
{
public:
/** Typedef for the CPU. */
typedef typename Impl::O3CPU O3CPU;
public:
/** BaseDynInst constructor given a binary instruction. */
SparcDynInst(TheISA::ExtMachInst inst, Addr PC, Addr NPC,
Addr Pred_PC, Addr Pred_NPC, InstSeqNum seq_num, O3CPU *cpu);
/** BaseDynInst constructor given a static inst pointer. */
SparcDynInst(StaticInstPtr &_staticInst);
/** Executes the instruction.*/
Fault execute();
/** Initiates the access. Only valid for memory operations. */
Fault initiateAcc();
/** Completes the access. Only valid for memory operations. */
Fault completeAcc(PacketPtr pkt);
private:
/** Initializes variables. */
void initVars();
public:
/** Reads a miscellaneous register. */
TheISA::MiscReg readMiscReg(int misc_reg)
{
return this->cpu->readMiscReg(misc_reg, this->threadNumber);
}
/** Reads a misc. register, including any side-effects the read
* might have as defined by the architecture.
*/
TheISA::MiscReg readMiscRegWithEffect(int misc_reg)
{
return this->cpu->readMiscRegWithEffect(misc_reg, this->threadNumber);
}
/** Sets a misc. register. */
void setMiscReg(int misc_reg, const TheISA::MiscReg &val)
{
this->instResult.integer = val;
return this->cpu->setMiscReg(misc_reg, val, this->threadNumber);
}
/** Sets a misc. register, including any side-effects the write
* might have as defined by the architecture.
*/
void setMiscRegWithEffect(int misc_reg, const TheISA::MiscReg &val)
{
return this->cpu->setMiscRegWithEffect(misc_reg, val,
this->threadNumber);
}
/** Reads a miscellaneous register. */
TheISA::MiscReg readMiscRegOperand(const StaticInst *si, int idx)
{
return this->cpu->readMiscReg(
si->srcRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
this->threadNumber);
}
/** Reads a misc. register, including any side-effects the read
* might have as defined by the architecture.
*/
TheISA::MiscReg readMiscRegOperandWithEffect(const StaticInst *si, int idx)
{
return this->cpu->readMiscRegWithEffect(
si->srcRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
this->threadNumber);
}
/** Sets a misc. register. */
void setMiscRegOperand(const StaticInst * si,
int idx, const TheISA::MiscReg &val)
{
this->instResult.integer = val;
return this->cpu->setMiscReg(
si->destRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
val, this->threadNumber);
}
/** Sets a misc. register, including any side-effects the write
* might have as defined by the architecture.
*/
void setMiscRegOperandWithEffect(
const StaticInst *si, int idx, const TheISA::MiscReg &val)
{
return this->cpu->setMiscRegWithEffect(
si->destRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
val, this->threadNumber);
}
#if FULL_SYSTEM
/** Calls hardware return from error interrupt. */
Fault hwrei();
/** Traps to handle specified fault. */
void trap(Fault fault);
bool simPalCheck(int palFunc);
#else
/** Calls a syscall. */
void syscall(int64_t callnum);
#endif
public:
// The register accessor methods provide the index of the
// instruction's operand (e.g., 0 or 1), not the architectural
// register index, to simplify the implementation of register
// renaming. We find the architectural register index by indexing
// into the instruction's own operand index table. Note that a
// raw pointer to the StaticInst is provided instead of a
// ref-counted StaticInstPtr to redice overhead. This is fine as
// long as these methods don't copy the pointer into any long-term
// storage (which is pretty hard to imagine they would have reason
// to do).
uint64_t readIntRegOperand(const StaticInst *si, int idx)
{
uint64_t val = this->cpu->readIntReg(this->_srcRegIdx[idx]);
DPRINTF(Sparc, "Reading int reg %d (%d, %d) as %x\n", (int)this->_flatSrcRegIdx[idx], (int)this->_srcRegIdx[idx], idx, val);
return this->cpu->readIntReg(this->_srcRegIdx[idx]);
}
TheISA::FloatReg readFloatRegOperand(const StaticInst *si,
int idx, int width)
{
return this->cpu->readFloatReg(this->_srcRegIdx[idx], width);
}
TheISA::FloatReg readFloatRegOperand(const StaticInst *si, int idx)
{
return this->cpu->readFloatReg(this->_srcRegIdx[idx]);
}
TheISA::FloatRegBits readFloatRegOperandBits(const StaticInst *si,
int idx, int width)
{
return this->cpu->readFloatRegBits(this->_srcRegIdx[idx], width);
}
TheISA::FloatRegBits readFloatRegOperandBits(const StaticInst *si, int idx)
{
return this->cpu->readFloatRegBits(this->_srcRegIdx[idx]);
}
/** @todo: Make results into arrays so they can handle multiple dest
* registers.
*/
void setIntRegOperand(const StaticInst *si, int idx, uint64_t val)
{
DPRINTF(Sparc, "Setting int reg %d (%d, %d) to %x\n", (int)this->_flatDestRegIdx[idx], (int)this->_destRegIdx[idx], idx, val);
this->cpu->setIntReg(this->_destRegIdx[idx], val);
BaseDynInst<Impl>::setIntRegOperand(si, idx, val);
}
void setFloatRegOperand(const StaticInst *si, int idx,
TheISA::FloatReg val, int width)
{
this->cpu->setFloatReg(this->_destRegIdx[idx], val, width);
BaseDynInst<Impl>::setFloatRegOperand(si, idx, val, width);
}
void setFloatRegOperand(const StaticInst *si, int idx, TheISA::FloatReg val)
{
this->cpu->setFloatReg(this->_destRegIdx[idx], val);
BaseDynInst<Impl>::setFloatRegOperand(si, idx, val);
}
void setFloatRegOperandBits(const StaticInst *si, int idx,
TheISA::FloatRegBits val, int width)
{
this->cpu->setFloatRegBits(this->_destRegIdx[idx], val, width);
BaseDynInst<Impl>::setFloatRegOperandBits(si, idx, val);
}
void setFloatRegOperandBits(const StaticInst *si,
int idx, TheISA::FloatRegBits val)
{
this->cpu->setFloatRegBits(this->_destRegIdx[idx], val);
BaseDynInst<Impl>::setFloatRegOperandBits(si, idx, val);
}
public:
/** Calculates EA part of a memory instruction. Currently unused,
* though it may be useful in the future if we want to split
* memory operations into EA calculation and memory access parts.
*/
Fault calcEA()
{
return this->staticInst->eaCompInst()->execute(this, this->traceData);
}
/** Does the memory access part of a memory instruction. Currently unused,
* though it may be useful in the future if we want to split
* memory operations into EA calculation and memory access parts.
*/
Fault memAccess()
{
return this->staticInst->memAccInst()->execute(this, this->traceData);
}
};
#endif // __CPU_O3_SPARC_DYN_INST_HH__
<commit_msg>Fixed a warning about an unused variable.<commit_after>/*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
*/
#ifndef __CPU_O3_SPARC_DYN_INST_HH__
#define __CPU_O3_SPARC_DYN_INST_HH__
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/types.hh"
#include "cpu/base_dyn_inst.hh"
#include "cpu/inst_seq.hh"
#include "cpu/o3/sparc/cpu.hh"
#include "cpu/o3/sparc/impl.hh"
class Packet;
/**
* Mostly implementation & ISA specific SparcDynInst. As with most
* other classes in the new CPU model, it is templated on the Impl to
* allow for passing in of all types, such as the CPU type and the ISA
* type. The SparcDynInst serves as the primary interface to the CPU
* for instructions that are executing.
*/
template <class Impl>
class SparcDynInst : public BaseDynInst<Impl>
{
public:
/** Typedef for the CPU. */
typedef typename Impl::O3CPU O3CPU;
public:
/** BaseDynInst constructor given a binary instruction. */
SparcDynInst(TheISA::ExtMachInst inst, Addr PC, Addr NPC,
Addr Pred_PC, Addr Pred_NPC, InstSeqNum seq_num, O3CPU *cpu);
/** BaseDynInst constructor given a static inst pointer. */
SparcDynInst(StaticInstPtr &_staticInst);
/** Executes the instruction.*/
Fault execute();
/** Initiates the access. Only valid for memory operations. */
Fault initiateAcc();
/** Completes the access. Only valid for memory operations. */
Fault completeAcc(PacketPtr pkt);
private:
/** Initializes variables. */
void initVars();
public:
/** Reads a miscellaneous register. */
TheISA::MiscReg readMiscReg(int misc_reg)
{
return this->cpu->readMiscReg(misc_reg, this->threadNumber);
}
/** Reads a misc. register, including any side-effects the read
* might have as defined by the architecture.
*/
TheISA::MiscReg readMiscRegWithEffect(int misc_reg)
{
return this->cpu->readMiscRegWithEffect(misc_reg, this->threadNumber);
}
/** Sets a misc. register. */
void setMiscReg(int misc_reg, const TheISA::MiscReg &val)
{
this->instResult.integer = val;
return this->cpu->setMiscReg(misc_reg, val, this->threadNumber);
}
/** Sets a misc. register, including any side-effects the write
* might have as defined by the architecture.
*/
void setMiscRegWithEffect(int misc_reg, const TheISA::MiscReg &val)
{
return this->cpu->setMiscRegWithEffect(misc_reg, val,
this->threadNumber);
}
/** Reads a miscellaneous register. */
TheISA::MiscReg readMiscRegOperand(const StaticInst *si, int idx)
{
return this->cpu->readMiscReg(
si->srcRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
this->threadNumber);
}
/** Reads a misc. register, including any side-effects the read
* might have as defined by the architecture.
*/
TheISA::MiscReg readMiscRegOperandWithEffect(const StaticInst *si, int idx)
{
return this->cpu->readMiscRegWithEffect(
si->srcRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
this->threadNumber);
}
/** Sets a misc. register. */
void setMiscRegOperand(const StaticInst * si,
int idx, const TheISA::MiscReg &val)
{
this->instResult.integer = val;
return this->cpu->setMiscReg(
si->destRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
val, this->threadNumber);
}
/** Sets a misc. register, including any side-effects the write
* might have as defined by the architecture.
*/
void setMiscRegOperandWithEffect(
const StaticInst *si, int idx, const TheISA::MiscReg &val)
{
return this->cpu->setMiscRegWithEffect(
si->destRegIdx(idx) - TheISA::Ctrl_Base_DepTag,
val, this->threadNumber);
}
#if FULL_SYSTEM
/** Calls hardware return from error interrupt. */
Fault hwrei();
/** Traps to handle specified fault. */
void trap(Fault fault);
bool simPalCheck(int palFunc);
#else
/** Calls a syscall. */
void syscall(int64_t callnum);
#endif
public:
// The register accessor methods provide the index of the
// instruction's operand (e.g., 0 or 1), not the architectural
// register index, to simplify the implementation of register
// renaming. We find the architectural register index by indexing
// into the instruction's own operand index table. Note that a
// raw pointer to the StaticInst is provided instead of a
// ref-counted StaticInstPtr to redice overhead. This is fine as
// long as these methods don't copy the pointer into any long-term
// storage (which is pretty hard to imagine they would have reason
// to do).
uint64_t readIntRegOperand(const StaticInst *si, int idx)
{
uint64_t val = this->cpu->readIntReg(this->_srcRegIdx[idx]);
DPRINTF(Sparc, "Reading int reg %d (%d, %d) as %x\n", (int)this->_flatSrcRegIdx[idx], (int)this->_srcRegIdx[idx], idx, val);
return val;
}
TheISA::FloatReg readFloatRegOperand(const StaticInst *si,
int idx, int width)
{
return this->cpu->readFloatReg(this->_srcRegIdx[idx], width);
}
TheISA::FloatReg readFloatRegOperand(const StaticInst *si, int idx)
{
return this->cpu->readFloatReg(this->_srcRegIdx[idx]);
}
TheISA::FloatRegBits readFloatRegOperandBits(const StaticInst *si,
int idx, int width)
{
return this->cpu->readFloatRegBits(this->_srcRegIdx[idx], width);
}
TheISA::FloatRegBits readFloatRegOperandBits(const StaticInst *si, int idx)
{
return this->cpu->readFloatRegBits(this->_srcRegIdx[idx]);
}
/** @todo: Make results into arrays so they can handle multiple dest
* registers.
*/
void setIntRegOperand(const StaticInst *si, int idx, uint64_t val)
{
DPRINTF(Sparc, "Setting int reg %d (%d, %d) to %x\n", (int)this->_flatDestRegIdx[idx], (int)this->_destRegIdx[idx], idx, val);
this->cpu->setIntReg(this->_destRegIdx[idx], val);
BaseDynInst<Impl>::setIntRegOperand(si, idx, val);
}
void setFloatRegOperand(const StaticInst *si, int idx,
TheISA::FloatReg val, int width)
{
this->cpu->setFloatReg(this->_destRegIdx[idx], val, width);
BaseDynInst<Impl>::setFloatRegOperand(si, idx, val, width);
}
void setFloatRegOperand(const StaticInst *si, int idx, TheISA::FloatReg val)
{
this->cpu->setFloatReg(this->_destRegIdx[idx], val);
BaseDynInst<Impl>::setFloatRegOperand(si, idx, val);
}
void setFloatRegOperandBits(const StaticInst *si, int idx,
TheISA::FloatRegBits val, int width)
{
this->cpu->setFloatRegBits(this->_destRegIdx[idx], val, width);
BaseDynInst<Impl>::setFloatRegOperandBits(si, idx, val);
}
void setFloatRegOperandBits(const StaticInst *si,
int idx, TheISA::FloatRegBits val)
{
this->cpu->setFloatRegBits(this->_destRegIdx[idx], val);
BaseDynInst<Impl>::setFloatRegOperandBits(si, idx, val);
}
public:
/** Calculates EA part of a memory instruction. Currently unused,
* though it may be useful in the future if we want to split
* memory operations into EA calculation and memory access parts.
*/
Fault calcEA()
{
return this->staticInst->eaCompInst()->execute(this, this->traceData);
}
/** Does the memory access part of a memory instruction. Currently unused,
* though it may be useful in the future if we want to split
* memory operations into EA calculation and memory access parts.
*/
Fault memAccess()
{
return this->staticInst->memAccInst()->execute(this, this->traceData);
}
};
#endif // __CPU_O3_SPARC_DYN_INST_HH__
<|endoftext|>
|
<commit_before>// Copyright 2016-2020 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// 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 <array>
#include <cstring>
#include <stdexcept>
#include <string>
#include <mp++/config.hpp>
#include <mp++/detail/parse_complex.hpp>
namespace mppp
{
namespace detail
{
// This function will try to parse the null-terminated
// string str as a complex number. The expected format is one of:
//
// - "x",
// - "(x)",
// - "(x,y)",
//
// where "x" and "y" are string representations of the real
// and imaginary parts.
//
// The return value is an array of 4 pointers representing
// two ranges in str encompassing "x" and "y" respectively.
// If the format is "x" or "(x)", the second range consists
// of two null pointers.
//
// If parsing fails, an exception will be raised.
std::array<const char *, 4> parse_complex(const char *str)
{
// Small helper to raise an error in case
// of a malformed string.
auto raise_error = [str]() {
throw std::invalid_argument(std::string("The string '") + str
+ "' is not a valid representation of a complex value");
};
auto s = str;
// Skip leading whitespaces.
for (; *s == ' '; ++s) {
}
if (mppp_unlikely(*s == '\0')) {
// The string consists only of whitespaces.
raise_error();
}
if (*s == '(') {
// The string starts with a round bracket. Try to
// understand if we have only the real component, or
// the imaginary as well.
// Examine the string until we get either to a comma
// (the separator between real and imaginary parts)
// or the end of the string.
auto p = s + 1;
for (; *p != ',' && *p != '\0'; ++p) {
}
if (*p == '\0') {
// We reached the end of the string,
// the format must be (real).
if (mppp_unlikely(*(p - 1) != ')')) {
// Unbalanced bracket.
raise_error();
}
// NOTE: here we know that:
//
// - *s == '(',
// - p > s,
// - *(p-1) == ')'.
//
// Thus, p-1 > s >= s+1.
return {s + 1, p - 1, nullptr, nullptr};
} else {
// We reached a comma, the format must
// be (real,imag).
// Record the char range for the real part.
const auto re_start = s + 1, re_end = p;
// Move p past the comma, assign to s.
s = ++p;
if (mppp_unlikely(*p == '\0')) {
// There's nothing after the comma.
raise_error();
}
// Look for the end of the string.
for (++p; *p != '\0'; ++p) {
}
// NOTE: here we are sure that p > s.
if (mppp_unlikely(*(p - 1) != ')')) {
// Unbalanced bracket.
raise_error();
}
return {re_start, re_end, s, p - 1};
}
} else {
// The string does not start with a round
// bracket, interpret as a real value.
return {s, s + std::strlen(s), nullptr, nullptr};
}
}
} // namespace detail
} // namespace mppp
<commit_msg>Tentative clang warning fix.<commit_after>// Copyright 2016-2020 Francesco Biscani (bluescarni@gmail.com)
//
// This file is part of the mp++ library.
//
// 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 <array>
#include <cstring>
#include <stdexcept>
#include <string>
#include <mp++/config.hpp>
#include <mp++/detail/parse_complex.hpp>
namespace mppp
{
namespace detail
{
// This function will try to parse the null-terminated
// string str as a complex number. The expected format is one of:
//
// - "x",
// - "(x)",
// - "(x,y)",
//
// where "x" and "y" are string representations of the real
// and imaginary parts.
//
// The return value is an array of 4 pointers representing
// two ranges in str encompassing "x" and "y" respectively.
// If the format is "x" or "(x)", the second range consists
// of two null pointers.
//
// If parsing fails, an exception will be raised.
std::array<const char *, 4> parse_complex(const char *str)
{
// Small helper to raise an error in case
// of a malformed string.
auto raise_error = [str]() {
throw std::invalid_argument(std::string("The string '") + str
+ "' is not a valid representation of a complex value");
};
auto s = str;
// Skip leading whitespaces.
for (; *s == ' '; ++s) {
}
if (mppp_unlikely(*s == '\0')) {
// The string consists only of whitespaces.
raise_error();
}
if (*s == '(') {
// The string starts with a round bracket. Try to
// understand if we have only the real component, or
// the imaginary as well.
// Examine the string until we get either to a comma
// (the separator between real and imaginary parts)
// or the end of the string.
auto p = s + 1;
for (; *p != ',' && *p != '\0'; ++p) {
}
if (*p == '\0') {
// We reached the end of the string,
// the format must be (real).
if (mppp_unlikely(*(p - 1) != ')')) {
// Unbalanced bracket.
raise_error();
}
// NOTE: here we know that:
//
// - *s == '(',
// - p > s,
// - *(p-1) == ')'.
//
// Thus, p-1 > s >= s+1.
return {{s + 1, p - 1, nullptr, nullptr}};
} else {
// We reached a comma, the format must
// be (real,imag).
// Record the char range for the real part.
const auto re_start = s + 1, re_end = p;
// Move p past the comma, assign to s.
s = ++p;
if (mppp_unlikely(*p == '\0')) {
// There's nothing after the comma.
raise_error();
}
// Look for the end of the string.
for (++p; *p != '\0'; ++p) {
}
// NOTE: here we are sure that p > s.
if (mppp_unlikely(*(p - 1) != ')')) {
// Unbalanced bracket.
raise_error();
}
return {{re_start, re_end, s, p - 1}};
}
} else {
// The string does not start with a round
// bracket, interpret as a real value.
return {{s, s + std::strlen(s), nullptr, nullptr}};
}
}
} // namespace detail
} // namespace mppp
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004 Georgy Yunaev tim@krasnogorsk.ru
* Copyright (C) 2008 J-P Nurmi jpnurmi@gmail.com
*
* This example is free, and not covered by LGPL license. There is no
* restriction applied to their modification, redistribution, using and so on.
* You can study them, modify them, use them in your own program - either
* completely or partially. By using it you may give me some credits in your
* program, but you don't have to.
*
*
* This example tests most features of libirc. It can join the specific
* channel, welcoming all the people there, and react on some messages -
* 'help', 'quit', 'dcc chat', 'dcc send', 'ctcp'. Also it can reply to
* CTCP requests, receive DCC files and accept DCC chats.
*
* Features used:
* - nickname parsing;
* - handling 'channel' event to track the messages;
* - handling dcc and ctcp events;
* - using internal ctcp rely procedure;
* - generating channel messages;
* - handling dcc send and dcc chat events;
* - initiating dcc send and dcc chat.
*
* $Id$
*/
#include <QtCore>
#include "ircsession.h"
class IrcTest : public QObject
{
Q_OBJECT
public:
IrcTest(IrcSession* session)
{
session->setParent(this);
session->setObjectName("irc");
QMetaObject::connectSlotsByName(this);
}
protected slots:
void on_irc_connected();
void on_irc_nickChanged(const QString& origin, const QString& nick);
void on_irc_quit(const QString& origin, const QString& message);
void on_irc_joined(const QString& origin, const QString& channel);
void on_irc_parted(const QString& origin, const QString& channel, const QString& message);
void on_irc_channelModeChanged(const QString& origin, const QString& channel, const QString& mode, const QString& args);
void on_irc_userModeChanged(const QString& origin, const QString& mode);
void on_irc_topicChanged(const QString& origin, const QString& channel, const QString& topic);
void on_irc_kicked(const QString& origin, const QString& channel, const QString& nick, const QString& message);
void on_irc_channelMessageReceived(const QString& origin, const QString& channel, const QString& message);
void on_irc_privateMessageReceived(const QString& origin, const QString& receiver, const QString& message);
void on_irc_noticeReceived(const QString& origin, const QString& receiver, const QString& message);
void on_irc_invited(const QString& origin, const QString& nick, const QString& channel);
void on_irc_ctcpRequestReceived(const QString& origin, const QString& message);
void on_irc_ctcpReplyReceived(const QString& origin, const QString& message);
void on_irc_ctcpActionReceived(const QString& origin, const QString& message);
void on_irc_unknownMessageReceived(const QString& origin, const QStringList& params);
void on_irc_numericMessageReceived(const QString& origin, const QStringList& params);
};
void IrcTest::on_irc_connected()
{
qDebug() << "connected:";
}
void IrcTest::on_irc_nickChanged(const QString& origin, const QString& nick)
{
qDebug() << "nick:" << origin << nick;
}
void IrcTest::on_irc_quit(const QString& origin, const QString& message)
{
qDebug() << "quit:" << origin << message;
}
void IrcTest::on_irc_joined(const QString& origin, const QString& channel)
{
qDebug() << "join:" << origin << channel;
}
void IrcTest::on_irc_parted(const QString& origin, const QString& channel, const QString& message)
{
qDebug() << "part:" << origin << channel << message;
}
void IrcTest::on_irc_channelModeChanged(const QString& origin, const QString& channel, const QString& mode, const QString& args)
{
qDebug() << "channel_mode:" << origin << channel << mode << args;
}
void IrcTest::on_irc_userModeChanged(const QString& origin, const QString& mode)
{
qDebug() << "user_mode:" << origin << mode;
}
void IrcTest::on_irc_topicChanged(const QString& origin, const QString& channel, const QString& topic)
{
qDebug() << "topic:" << origin << channel << topic;
}
void IrcTest::on_irc_kicked(const QString& origin, const QString& channel, const QString& nick, const QString& message)
{
qDebug() << "kick:" << origin << channel << nick << message;
}
void IrcTest::on_irc_channelMessageReceived(const QString& origin, const QString& channel, const QString& message)
{
qDebug() << "channel:" << origin << channel << message;
}
void IrcTest::on_irc_privateMessageReceived(const QString& origin, const QString& receiver, const QString& message)
{
qDebug() << "private:" << origin << receiver << message;
}
void IrcTest::on_irc_noticeReceived(const QString& origin, const QString& receiver, const QString& message)
{
qDebug() << "notice:" << origin << receiver << message;
}
void IrcTest::on_irc_invited(const QString& origin, const QString& nick, const QString& channel)
{
qDebug() << "invite:" << origin << nick << channel;
}
void IrcTest::on_irc_ctcpRequestReceived(const QString& origin, const QString& message)
{
qDebug() << "ctcp_request:" << origin << message;
}
void IrcTest::on_irc_ctcpReplyReceived(const QString& origin, const QString& message)
{
qDebug() << "ctcp_reply:" << origin << message;
}
void IrcTest::on_irc_ctcpActionReceived(const QString& origin, const QString& message)
{
qDebug() << "ctcp_action:" << origin << message;
}
void IrcTest::on_irc_unknownMessageReceived(const QString& origin, const QStringList& params)
{
qDebug() << "unknown:" << origin << params;
}
void IrcTest::on_irc_numericMessageReceived(const QString& origin, const QStringList& params)
{
qDebug() << "numeric:" << origin << params;
}
int main (int argc, char* argv[])
{
QCoreApplication app(argc, argv);
if (argc < 4)
{
qDebug("Usage: %s <server> <nick> <channels...>", argv[0]);
return 1;
}
IrcSession session;
IrcTest test(&session);
QStringList channels;
for (int i = 3; i < argc; ++i)
{
channels.append(argv[i]);
}
session.setAutoJoinChannels(channels);
if (!session.connectTo(argv[1], 6667, "", argv[2], "nobody", "reality"))
{
qWarning("Could not connect: %s", qPrintable(session.errorString()));
return 1;
}
return app.exec();
}
#include "main.moc"
<commit_msg>Updated IrcTest to reflect latest changes.<commit_after>/*
* Copyright (C) 2004 Georgy Yunaev tim@krasnogorsk.ru
* Copyright (C) 2008 J-P Nurmi jpnurmi@gmail.com
*
* This example is free, and not covered by LGPL license. There is no
* restriction applied to their modification, redistribution, using and so on.
* You can study them, modify them, use them in your own program - either
* completely or partially. By using it you may give me some credits in your
* program, but you don't have to.
*
*
* This example tests most features of libirc. It can join the specific
* channel, welcoming all the people there, and react on some messages -
* 'help', 'quit', 'dcc chat', 'dcc send', 'ctcp'. Also it can reply to
* CTCP requests, receive DCC files and accept DCC chats.
*
* Features used:
* - nickname parsing;
* - handling 'channel' event to track the messages;
* - handling dcc and ctcp events;
* - using internal ctcp rely procedure;
* - generating channel messages;
* - handling dcc send and dcc chat events;
* - initiating dcc send and dcc chat.
*
* $Id$
*/
#include <QtCore>
#include "coreircsession.h"
class MyIrcSession : public CoreIrcSession
{
Q_OBJECT
public:
MyIrcSession(QObject* parent = 0);
protected slots:
void on_connected();
void on_nickChanged(const QString& origin, const QString& nick);
void on_quit(const QString& origin, const QString& message);
void on_joined(const QString& origin, const QString& channel);
void on_parted(const QString& origin, const QString& channel, const QString& message);
void on_channelModeChanged(const QString& origin, const QString& channel, const QString& mode, const QString& args);
void on_userModeChanged(const QString& origin, const QString& mode);
void on_topicChanged(const QString& origin, const QString& channel, const QString& topic);
void on_kicked(const QString& origin, const QString& channel, const QString& nick, const QString& message);
void on_channelMessageReceived(const QString& origin, const QString& channel, const QString& message);
void on_privateMessageReceived(const QString& origin, const QString& receiver, const QString& message);
void on_noticeReceived(const QString& origin, const QString& receiver, const QString& message);
void on_invited(const QString& origin, const QString& nick, const QString& channel);
void on_ctcpRequestReceived(const QString& origin, const QString& message);
void on_ctcpReplyReceived(const QString& origin, const QString& message);
void on_ctcpActionReceived(const QString& origin, const QString& message);
void on_unknownMessageReceived(const QString& origin, const QStringList& params);
void on_numericMessageReceived(const QString& origin, const QStringList& params);
};
MyIrcSession::MyIrcSession(QObject* parent) : CoreIrcSession(parent)
{
connectSlotsByName(this);
}
void MyIrcSession::on_connected()
{
qDebug() << "connected:";
}
void MyIrcSession::on_nickChanged(const QString& origin, const QString& nick)
{
qDebug() << "nick:" << origin << nick;
}
void MyIrcSession::on_quit(const QString& origin, const QString& message)
{
qDebug() << "quit:" << origin << message;
}
void MyIrcSession::on_joined(const QString& origin, const QString& channel)
{
qDebug() << "join:" << origin << channel;
}
void MyIrcSession::on_parted(const QString& origin, const QString& channel, const QString& message)
{
qDebug() << "part:" << origin << channel << message;
}
void MyIrcSession::on_channelModeChanged(const QString& origin, const QString& channel, const QString& mode, const QString& args)
{
qDebug() << "channel_mode:" << origin << channel << mode << args;
}
void MyIrcSession::on_userModeChanged(const QString& origin, const QString& mode)
{
qDebug() << "user_mode:" << origin << mode;
}
void MyIrcSession::on_topicChanged(const QString& origin, const QString& channel, const QString& topic)
{
qDebug() << "topic:" << origin << channel << topic;
}
void MyIrcSession::on_kicked(const QString& origin, const QString& channel, const QString& nick, const QString& message)
{
qDebug() << "kick:" << origin << channel << nick << message;
}
void MyIrcSession::on_channelMessageReceived(const QString& origin, const QString& channel, const QString& message)
{
qDebug() << "channel:" << origin << channel << message;
}
void MyIrcSession::on_privateMessageReceived(const QString& origin, const QString& receiver, const QString& message)
{
qDebug() << "private:" << origin << receiver << message;
}
void MyIrcSession::on_noticeReceived(const QString& origin, const QString& receiver, const QString& message)
{
qDebug() << "notice:" << origin << receiver << message;
}
void MyIrcSession::on_invited(const QString& origin, const QString& nick, const QString& channel)
{
qDebug() << "invite:" << origin << nick << channel;
}
void MyIrcSession::on_ctcpRequestReceived(const QString& origin, const QString& message)
{
qDebug() << "ctcp_request:" << origin << message;
}
void MyIrcSession::on_ctcpReplyReceived(const QString& origin, const QString& message)
{
qDebug() << "ctcp_reply:" << origin << message;
}
void MyIrcSession::on_ctcpActionReceived(const QString& origin, const QString& message)
{
qDebug() << "ctcp_action:" << origin << message;
}
void MyIrcSession::on_unknownMessageReceived(const QString& origin, const QStringList& params)
{
qDebug() << "unknown:" << origin << params;
}
void MyIrcSession::on_numericMessageReceived(const QString& origin, const QStringList& params)
{
qDebug() << "numeric:" << origin << params;
}
int main (int argc, char* argv[])
{
if (argc < 4)
{
qDebug("Usage: %s <server> <nick> <channels...>", argv[0]);
return 1;
}
QStringList channels;
for (int i = 3; i < argc; ++i)
{
channels.append(argv[i]);
}
MyIrcSession session;
session.setAutoJoinChannels(channels);
if (!session.connectToServer(argv[1], 6667, argv[2], "nobody", "reality"))
{
qWarning("Could not connect: %s", qPrintable(session.errorString()));
return 1;
}
return session.exec();
}
#include "main.moc"
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 <fstream>
#include <iterator>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
using namespace libtorrent;
void add_files(
torrent_info& t
, path const& p
, path const& l)
{
path f(p / l);
if (is_directory(f))
{
for (directory_iterator i(f), end; i != end; ++i)
add_files(t, p, l / i->leaf());
}
else
{
std::cerr << "adding \"" << l.string() << "\"\n";
t.add_file(l, file_size(f));
}
}
int main(int argc, char* argv[])
{
using namespace libtorrent;
using namespace boost::filesystem;
path::default_name_check(no_check);
if (argc != 4)
{
std::cerr << "usage: make_torrent <output torrent-file> "
"<announce url> <file or directory to create torrent from>\n";
return 1;
}
try
{
torrent_info t;
path full_path = complete(path(argv[3]));
ofstream out(complete(path(argv[1])), std::ios_base::binary);
int piece_size = 256 * 1024;
char const* creator_str = "libtorrent";
add_files(t, full_path.branch_path(), full_path.leaf());
t.set_piece_size(piece_size);
file_pool fp;
storage st(t, full_path.branch_path(), fp);
t.add_tracker(argv[2]);
// calculate the hash for all pieces
int num = t.num_pieces();
std::vector<char> buf(piece_size);
for (int i = 0; i < num; ++i)
{
st.read(&buf[0], i, 0, t.piece_size(i));
hasher h(&buf[0], t.piece_size(i));
t.set_hash(i, h.final());
std::cerr << (i+1) << "/" << num << "\r";
}
t.set_creator(creator_str);
// create the torrent and print it to out
entry e = t.create_torrent();
libtorrent::bencode(std::ostream_iterator<char>(out), e);
}
catch (std::exception& e)
{
std::cerr << e.what() << "\n";
}
return 0;
}
<commit_msg>the torrent maker now skips hidden files<commit_after>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 <fstream>
#include <iterator>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost::filesystem;
using namespace libtorrent;
void add_files(
torrent_info& t
, path const& p
, path const& l)
{
if (l.leaf()[0] == '.') return;
path f(p / l);
if (is_directory(f))
{
for (directory_iterator i(f), end; i != end; ++i)
add_files(t, p, l / i->leaf());
}
else
{
std::cerr << "adding \"" << l.string() << "\"\n";
t.add_file(l, file_size(f));
}
}
int main(int argc, char* argv[])
{
using namespace libtorrent;
using namespace boost::filesystem;
path::default_name_check(no_check);
if (argc != 4)
{
std::cerr << "usage: make_torrent <output torrent-file> "
"<announce url> <file or directory to create torrent from>\n";
return 1;
}
try
{
torrent_info t;
path full_path = complete(path(argv[3]));
ofstream out(complete(path(argv[1])), std::ios_base::binary);
int piece_size = 256 * 1024;
char const* creator_str = "libtorrent";
add_files(t, full_path.branch_path(), full_path.leaf());
t.set_piece_size(piece_size);
file_pool fp;
storage st(t, full_path.branch_path(), fp);
t.add_tracker(argv[2]);
// calculate the hash for all pieces
int num = t.num_pieces();
std::vector<char> buf(piece_size);
for (int i = 0; i < num; ++i)
{
st.read(&buf[0], i, 0, t.piece_size(i));
hasher h(&buf[0], t.piece_size(i));
t.set_hash(i, h.final());
std::cerr << (i+1) << "/" << num << "\r";
}
t.set_creator(creator_str);
// create the torrent and print it to out
entry e = t.create_torrent();
libtorrent::bencode(std::ostream_iterator<char>(out), e);
}
catch (std::exception& e)
{
std::cerr << e.what() << "\n";
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file Motion.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
*
*/
#include "Motion.h"
#include <glib.h>
#include "MorphologyProcessor/ForwardKinematics.h"
#include "CameraMatrixCalculator/CameraMatrixCalculator.h"
Motion::Motion():theBlackBoard(MotionBlackBoard::getInstance())
{
theSupportPolygonGenerator.init(theBlackBoard.theFSRData.force,
theBlackBoard.theFSRPos,
theBlackBoard.theKinematicChain.theLinks);
}
Motion::~Motion()
{
}
void Motion::init(naoth::PlatformDataInterface& platformInterface)
{
theBlackBoard.init();
theBlackBoard.currentlyExecutedMotion = &theEmptyMotion;
g_message("Motion register begin");
#define REG_INPUT(R) \
platformInterface.registerMotionInput(theBlackBoard.the##R)
REG_INPUT(SensorJointData);
REG_INPUT(FrameInfo);
REG_INPUT(InertialSensorData);
REG_INPUT(FSRData);
REG_INPUT(AccelerometerData);
REG_INPUT(GyrometerData);
#define REG_OUTPUT(R) \
platformInterface.registerMotionOutput(theBlackBoard.the##R)
REG_OUTPUT(MotorJointData);
g_message("Motion register end");
//theInverseKinematicsMotionFactory.init();
//theKeyFrameMotionEngine.init();
//theDebugMotionEngine.init();
}//end init
void Motion::call()
{
// TODO
//STOPWATCH_START("MotionExecute");
// process sensor data
processSensorData();
// get orders from cognition
//SwapSpace::getInstance().theCognitionCache.pull(
// theBlackBoard.theHeadMotionRequest,
// theBlackBoard.theMotionRequest
//);
// execute head motion firstly
//theHeadMotionEngine.execute();
// motion engine execute
//selectMotion();
//ASSERT(NULL!=currentlyExecutedMotion);
//currentlyExecutedMotion->execute(theBlackBoard.theMotionRequest, theBlackBoard.theMotionStatus);
// HACK: execute the grasping motion
//if(theBlackBoard.theMotionRequest.id != MotionRequestID::init)
//{
// theInverseKinematicsMotionFactory.theIKArmGrasping.execute(theBlackBoard.theMotionRequest, theBlackBoard.theMotionStatus);
//}
// TODO
//STOPWATCH_STOP("MotionExecute");
postProcess();
}//end call
void Motion::processSensorData()
{
// check all joint stiffness
theBlackBoard.theSensorJointData.checkStiffness();
Kinematics::ForwardKinematics::calculateKinematicChainAll(
theBlackBoard.theAccelerometerData,
theBlackBoard.theInertialSensorData,
theBlackBoard.theKinematicChain,
theBlackBoard.theFSRPos,
theBlackBoard.theFrameInfo.getBasicTimeStepInSecond());
cout<<"---------------"<<endl;
theSupportPolygonGenerator.calcSupportPolygon(theBlackBoard.theSupportPolygon);
CameraMatrixCalculator::calculateCameraMatrix(
theBlackBoard.theCameraMatrix,
theBlackBoard.theHeadMotionRequest.cameraID,
theBlackBoard.theKinematicChain);
theOdometryCalculator.calculateOdometry(
theBlackBoard.theOdometryData,
theBlackBoard.theKinematicChain,
theBlackBoard.theFSRData);
cout<<theBlackBoard.theOdometryData<<endl;
/*
Kinematics::ForwardKinematics::updateKinematicChainFrom(theBlackBoard.theKinematicChainModel.theLinks);
theBlackBoard.theKinematicChainModel.updateCoM();*/
}//end processSensorData
void Motion::postProcess()
{
}
<commit_msg>processSensorData complete<commit_after>/**
* @file Motion.cpp
*
* @author <a href="mailto:xu@informatik.hu-berlin.de">Xu, Yuan</a>
*
*/
#include "Motion.h"
#include <glib.h>
#include "MorphologyProcessor/ForwardKinematics.h"
#include "CameraMatrixCalculator/CameraMatrixCalculator.h"
Motion::Motion():theBlackBoard(MotionBlackBoard::getInstance())
{
theSupportPolygonGenerator.init(theBlackBoard.theFSRData.force,
theBlackBoard.theFSRPos,
theBlackBoard.theKinematicChain.theLinks);
}
Motion::~Motion()
{
}
void Motion::init(naoth::PlatformDataInterface& platformInterface)
{
theBlackBoard.init();
theBlackBoard.currentlyExecutedMotion = &theEmptyMotion;
g_message("Motion register begin");
#define REG_INPUT(R) \
platformInterface.registerMotionInput(theBlackBoard.the##R)
REG_INPUT(SensorJointData);
REG_INPUT(FrameInfo);
REG_INPUT(InertialSensorData);
REG_INPUT(FSRData);
REG_INPUT(AccelerometerData);
REG_INPUT(GyrometerData);
#define REG_OUTPUT(R) \
platformInterface.registerMotionOutput(theBlackBoard.the##R)
REG_OUTPUT(MotorJointData);
g_message("Motion register end");
//theInverseKinematicsMotionFactory.init();
//theKeyFrameMotionEngine.init();
//theDebugMotionEngine.init();
}//end init
void Motion::call()
{
// TODO
//STOPWATCH_START("MotionExecute");
// process sensor data
processSensorData();
// get orders from cognition
//SwapSpace::getInstance().theCognitionCache.pull(
// theBlackBoard.theHeadMotionRequest,
// theBlackBoard.theMotionRequest
//);
// execute head motion firstly
//theHeadMotionEngine.execute();
// motion engine execute
//selectMotion();
//ASSERT(NULL!=currentlyExecutedMotion);
//currentlyExecutedMotion->execute(theBlackBoard.theMotionRequest, theBlackBoard.theMotionStatus);
// HACK: execute the grasping motion
//if(theBlackBoard.theMotionRequest.id != MotionRequestID::init)
//{
// theInverseKinematicsMotionFactory.theIKArmGrasping.execute(theBlackBoard.theMotionRequest, theBlackBoard.theMotionStatus);
//}
// TODO
//STOPWATCH_STOP("MotionExecute");
postProcess();
}//end call
void Motion::processSensorData()
{
// check all joint stiffness
theBlackBoard.theSensorJointData.checkStiffness();
Kinematics::ForwardKinematics::calculateKinematicChainAll(
theBlackBoard.theAccelerometerData,
theBlackBoard.theInertialSensorData,
theBlackBoard.theKinematicChain,
theBlackBoard.theFSRPos,
theBlackBoard.theFrameInfo.getBasicTimeStepInSecond());
theSupportPolygonGenerator.calcSupportPolygon(theBlackBoard.theSupportPolygon);
CameraMatrixCalculator::calculateCameraMatrix(
theBlackBoard.theCameraMatrix,
theBlackBoard.theHeadMotionRequest.cameraID,
theBlackBoard.theKinematicChain);
theOdometryCalculator.calculateOdometry(
theBlackBoard.theOdometryData,
theBlackBoard.theKinematicChain,
theBlackBoard.theFSRData);
Kinematics::ForwardKinematics::updateKinematicChainFrom(theBlackBoard.theKinematicChainModel.theLinks);
theBlackBoard.theKinematicChainModel.updateCoM();
}//end processSensorData
void Motion::postProcess()
{
}
<|endoftext|>
|
<commit_before>// $Id$
//
// Test Suite for geos::io::ByteOrderValues
// TUT
#include <tut.h>
// GEOS
#include <geos/io/ByteOrderValues.h>
#include <geos/platform.h> // for int64
#include <sstream>
#include <memory>
namespace tut
{
//
// Test Group
//
// dummy data, not used
struct test_byteordervalues_data
{
};
typedef test_group<test_byteordervalues_data> group;
typedef group::object object;
group test_byteordervalues_group("geos::io::ByteOrderValues");
//
// Test Cases
//
// 1 - Read/write an int
template<>
template<>
void object::test<1>()
{
using geos::io::ByteOrderValues;
unsigned char buf[4];
int in = 1;
int out;
ByteOrderValues::putInt(in, buf, ByteOrderValues::ENDIAN_BIG);
ensure("putInt big endian[0]", buf[0] == 0);
ensure("putInt big endian[1]", buf[1] == 0);
ensure("putInt big endian[2]", buf[2] == 0);
ensure("putInt big endian[3]", buf[3] == 1);
out = ByteOrderValues::getInt(buf,
ByteOrderValues::ENDIAN_BIG);
ensure_equals("getInt big endian", out, in);
ByteOrderValues::putInt(1, buf, ByteOrderValues::ENDIAN_LITTLE);
ensure("putInt little endian[0]", buf[0] == 1);
ensure("putInt little endian[1]", buf[1] == 0);
ensure("putInt little endian[2]", buf[2] == 0);
ensure("putInt little endian[3]", buf[3] == 0);
out = ByteOrderValues::getInt(buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure_equals("getInt little endian", out, in);
}
// 2 - Read/write a double
template<>
template<>
void object::test<2>()
{
using geos::io::ByteOrderValues;
unsigned char buf[8];
double in = 2;
double out;
ByteOrderValues::putDouble(in, buf,
ByteOrderValues::ENDIAN_BIG);
ensure("putDouble big endian[0]", buf[0] == 64);
ensure("putDouble big endian[1]", buf[1] == 0);
ensure("putDouble big endian[2]", buf[2] == 0);
ensure("putDouble big endian[3]", buf[3] == 0);
ensure("putDouble big endian[4]", buf[4] == 0);
ensure("putDouble big endian[5]", buf[5] == 0);
ensure("putDouble big endian[6]", buf[6] == 0);
ensure("putDouble big endian[7]", buf[7] == 0);
out = ByteOrderValues::getDouble(buf,
ByteOrderValues::ENDIAN_BIG);
ensure_equals("getDouble big endian", out, in);
ByteOrderValues::putDouble(in, buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure("putDouble little endian[0]", buf[0] == 0);
ensure("putDouble little endian[1]", buf[1] == 0);
ensure("putDouble little endian[2]", buf[2] == 0);
ensure("putDouble little endian[3]", buf[3] == 0);
ensure("putDouble little endian[4]", buf[4] == 0);
ensure("putDouble little endian[5]", buf[5] == 0);
ensure("putDouble little endian[6]", buf[6] == 0);
ensure("putDouble little endian[7]", buf[7] == 64);
out = ByteOrderValues::getDouble(buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure_equals("getDouble little endian", out, in);
}
} // namespace tut
<commit_msg>Added test for put/get Long values<commit_after>// $Id$
//
// Test Suite for geos::io::ByteOrderValues
// TUT
#include <tut.h>
// GEOS
#include <geos/io/ByteOrderValues.h>
#include <geos/platform.h> // for int64
#include <sstream>
#include <memory>
namespace tut
{
//
// Test Group
//
// dummy data, not used
struct test_byteordervalues_data
{
};
typedef test_group<test_byteordervalues_data> group;
typedef group::object object;
group test_byteordervalues_group("geos::io::ByteOrderValues");
//
// Test Cases
//
// 1 - Read/write an int
template<>
template<>
void object::test<1>()
{
using geos::io::ByteOrderValues;
unsigned char buf[4];
int in = 1;
int out;
ByteOrderValues::putInt(in, buf, ByteOrderValues::ENDIAN_BIG);
ensure("putInt big endian[0]", buf[0] == 0);
ensure("putInt big endian[1]", buf[1] == 0);
ensure("putInt big endian[2]", buf[2] == 0);
ensure("putInt big endian[3]", buf[3] == 1);
out = ByteOrderValues::getInt(buf,
ByteOrderValues::ENDIAN_BIG);
ensure_equals("getInt big endian", out, in);
ByteOrderValues::putInt(1, buf, ByteOrderValues::ENDIAN_LITTLE);
ensure("putInt little endian[0]", buf[0] == 1);
ensure("putInt little endian[1]", buf[1] == 0);
ensure("putInt little endian[2]", buf[2] == 0);
ensure("putInt little endian[3]", buf[3] == 0);
out = ByteOrderValues::getInt(buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure_equals("getInt little endian", out, in);
}
// 2 - Read/write a double
template<>
template<>
void object::test<2>()
{
using geos::io::ByteOrderValues;
unsigned char buf[8];
double in = 2;
double out;
ByteOrderValues::putDouble(in, buf,
ByteOrderValues::ENDIAN_BIG);
ensure("putDouble big endian[0]", buf[0] == 64);
ensure("putDouble big endian[1]", buf[1] == 0);
ensure("putDouble big endian[2]", buf[2] == 0);
ensure("putDouble big endian[3]", buf[3] == 0);
ensure("putDouble big endian[4]", buf[4] == 0);
ensure("putDouble big endian[5]", buf[5] == 0);
ensure("putDouble big endian[6]", buf[6] == 0);
ensure("putDouble big endian[7]", buf[7] == 0);
out = ByteOrderValues::getDouble(buf,
ByteOrderValues::ENDIAN_BIG);
ensure_equals("getDouble big endian", out, in);
ByteOrderValues::putDouble(in, buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure("putDouble little endian[0]", buf[0] == 0);
ensure("putDouble little endian[1]", buf[1] == 0);
ensure("putDouble little endian[2]", buf[2] == 0);
ensure("putDouble little endian[3]", buf[3] == 0);
ensure("putDouble little endian[4]", buf[4] == 0);
ensure("putDouble little endian[5]", buf[5] == 0);
ensure("putDouble little endian[6]", buf[6] == 0);
ensure("putDouble little endian[7]", buf[7] == 64);
out = ByteOrderValues::getDouble(buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure_equals("getDouble little endian", out, in);
}
// 3 - Read/write a long
template<>
template<>
void object::test<3>()
{
using geos::io::ByteOrderValues;
unsigned char buf[8];
long in = 2;
long out;
ByteOrderValues::putLong(in, buf,
ByteOrderValues::ENDIAN_BIG);
ensure("putLong big endian[0]", buf[0] == 0);
ensure("putLong big endian[1]", buf[1] == 0);
ensure("putLong big endian[2]", buf[2] == 0);
ensure("putLong big endian[3]", buf[3] == 0);
ensure("putLong big endian[4]", buf[4] == 0);
ensure("putLong big endian[5]", buf[5] == 0);
ensure("putLong big endian[6]", buf[6] == 0);
ensure("putLong big endian[7]", buf[7] == 2);
out = ByteOrderValues::getLong(buf,
ByteOrderValues::ENDIAN_BIG);
ensure_equals("getLong big endian", out, in);
ByteOrderValues::putLong(in, buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure("putLong little endian[0]", buf[0] == 2);
ensure("putLong little endian[1]", buf[1] == 0);
ensure("putLong little endian[2]", buf[2] == 0);
ensure("putLong little endian[3]", buf[3] == 0);
ensure("putLong little endian[4]", buf[4] == 0);
ensure("putLong little endian[5]", buf[5] == 0);
ensure("putLong little endian[6]", buf[6] == 0);
ensure("putLong little endian[7]", buf[7] == 0);
out = ByteOrderValues::getLong(buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure_equals("getLong little endian", out, in);
}
} // namespace tut
<|endoftext|>
|
<commit_before>/* httpreply.cpp
Copyright (C) 2003-2005 Tommi Maekitalo
This file is part of tntnet.
Tntnet is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
#include <tnt/httpreply.h>
#include <tnt/http.h>
#include <tnt/httpheader.h>
#include <tnt/deflatestream.h>
#include <cxxtools/log.h>
#include <cxxtools/md5stream.h>
#include <cxxtools/dynbuffer.h>
#include <zlib.h>
#include <netinet/in.h>
namespace tnt
{
log_define("tntnet.httpreply")
////////////////////////////////////////////////////////////////////////
// HttpReply
//
unsigned HttpReply::keepAliveTimeout = 15000;
void HttpReply::tryCompress(std::string& body)
{
if (!hasHeader(httpheader::contentEncoding))
{
if (acceptEncoding.accept("gzip"))
{
log_debug("gzip");
std::ostringstream b;
char f[] = "\x1f\x8b\x08\x00"
"\x00\x00\x00\x00"
"\x04\x03";
b.write(f, sizeof(f) - 1);
DeflateStream deflator(b);
deflator.write(body.data(), body.size());
deflator.end();
uLong crc = crc32(0, reinterpret_cast<const Bytef*>(body.data()), body.size());
uint32_t u = htonl(crc);
b.write(reinterpret_cast<const char*>(&crc), 4);
u = htonl(body.size());
b.write(reinterpret_cast<const char*>(&u), 4);
std::string::size_type oldSize = body.size();
body = b.str();
log_info("gzip body " << oldSize << " bytes to " << body.size() << " bytes");
setHeader(httpheader::contentEncoding, "gzip");
}
}
}
void HttpReply::send(unsigned ret)
{
std::string body = outstream.str();
// complete headers
if (!hasHeader(httpheader::date))
setHeader(httpheader::date, htdate(time(0)));
if (!hasHeader(httpheader::server))
setHeader(httpheader::server, httpheader::serverName);
tryCompress(body);
if (keepAliveTimeout > 0 && keepAliveCounter > 0)
{
if (!hasHeader(httpheader::connection))
setKeepAliveHeader(getKeepAliveTimeout() + 999 / 1000);
if (!hasHeader(httpheader::contentLength))
setContentLengthHeader(body.size());
}
else if (!hasHeader(httpheader::connection))
setKeepAliveHeader(0);
if (!hasHeader(httpheader::contentType))
setHeader(httpheader::contentType, contentType);
// send header
if (sendStatusLine)
{
log_debug("HTTP/" << getMajorVersion() << '.' << getMinorVersion()
<< ' ' << ret << " OK");
socket << "HTTP/" << getMajorVersion() << '.' << getMinorVersion()
<< ' ' << ret << " OK" << "\r\n";
}
for (header_type::const_iterator it = header.begin();
it != header.end(); ++it)
{
log_debug(it->first << ' ' << it->second);
socket << it->first << ' ' << it->second << "\r\n";
}
if (hasCookies())
{
log_debug(httpheader::setCookie << ' ' << httpcookies);
socket << httpheader::setCookie << ' ' << httpcookies << "\r\n";
}
socket << "\r\n";
// send body
if (getMethod() == "HEAD")
log_debug("HEAD-request - empty body");
else
{
log_debug("send " << body.size()
<< " bytes body, method=" << getMethod());
socket << body;
}
}
HttpReply::HttpReply(std::ostream& s, bool sendStatusLine_)
: contentType("text/html"),
socket(s),
current_outstream(&outstream),
save_outstream(outstream),
keepAliveCounter(0),
sendStatusLine(sendStatusLine_)
{ }
void HttpReply::sendReply(unsigned ret)
{
if (!isDirectMode())
{
send(ret);
socket.flush();
}
}
void HttpReply::setMd5Sum()
{
cxxtools::Md5stream md5;
md5 << outstream.str().size();
setHeader(httpheader::contentMD5, md5.getHexDigest());
}
void HttpReply::throwError(unsigned errorCode, const std::string& errorMessage) const
{
throw HttpError(errorCode, errorMessage);
}
void HttpReply::throwError(const std::string& errorMessage) const
{
throw HttpError(errorMessage);
}
void HttpReply::throwNotFound(const std::string& errorMessage) const
{
throw NotFoundException(errorMessage);
}
unsigned HttpReply::redirect(const std::string& newLocation)
{
setHeader(httpheader::location, newLocation);
return HTTP_MOVED_TEMPORARILY;
}
void HttpReply::setContentLengthHeader(size_t size)
{
std::ostringstream s;
s << size;
setHeader(httpheader::contentLength, s.str());
}
void HttpReply::setKeepAliveHeader(unsigned timeout)
{
log_debug("setKeepAliveHeader(" << timeout << ')');
removeHeader(httpheader::connection);
removeHeader(httpheader::keepAlive);
if (timeout > 0 && getKeepAliveCounter() > 0)
{
std::ostringstream s;
s << "timeout=" << timeout << ", max=" << getKeepAliveCounter();
setHeader(httpheader::keepAlive, s.str());
setHeader(httpheader::connection, httpheader::connectionKeepAlive);
}
else
setHeader(httpheader::connection, httpheader::connectionClose);
}
void HttpReply::setDirectMode()
{
if (!isDirectMode())
{
send(HTTP_OK);
current_outstream = &socket;
save_outstream.setSink(socket);
}
}
void HttpReply::setDirectModeNoFlush()
{
current_outstream = &socket;
save_outstream.setSink(socket);
}
void HttpReply::setCookie(const std::string& name, const Cookie& value)
{
log_debug("setCookie(\"" << name << "\",\"" << value.getValue() << "\")");
httpcookies.setCookie(name, value);
}
bool HttpReply::keepAlive() const
{
if (getKeepAliveCounter() <= 0
|| getKeepAliveTimeout() <= 0)
return false;
header_type::const_iterator it = header.find(httpheader::connection);
return it != header.end() && it->second == httpheader::connectionKeepAlive;
}
}
<commit_msg>invalid length-field in gzip-encoding fixed<commit_after>/* httpreply.cpp
Copyright (C) 2003-2005 Tommi Maekitalo
This file is part of tntnet.
Tntnet is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
#include <tnt/httpreply.h>
#include <tnt/http.h>
#include <tnt/httpheader.h>
#include <tnt/deflatestream.h>
#include <cxxtools/log.h>
#include <cxxtools/md5stream.h>
#include <cxxtools/dynbuffer.h>
#include <zlib.h>
#include <netinet/in.h>
namespace tnt
{
log_define("tntnet.httpreply")
////////////////////////////////////////////////////////////////////////
// HttpReply
//
unsigned HttpReply::keepAliveTimeout = 15000;
void HttpReply::tryCompress(std::string& body)
{
if (!body.empty() && !hasHeader(httpheader::contentEncoding))
{
if (acceptEncoding.accept("gzip"))
{
log_debug("gzip");
std::ostringstream b;
char f[] = "\x1f\x8b\x08\x00"
"\x00\x00\x00\x00"
"\x04\x03";
b.write(f, sizeof(f) - 1);
DeflateStream deflator(b);
deflator.write(body.data(), body.size());
deflator.end();
uLong crc = crc32(0, reinterpret_cast<const Bytef*>(body.data()), body.size());
uint32_t u = crc;
b.put(static_cast<char>(u & 0xFF));
b.put(static_cast<char>((u >>= 8) & 0xFF));
b.put(static_cast<char>((u >>= 8) & 0xFF));
b.put(static_cast<char>((u >>= 8) & 0xFF));
u = body.size();
b.put(static_cast<char>(u & 0xFF));
b.put(static_cast<char>((u >>= 8) & 0xFF));
b.put(static_cast<char>((u >>= 8) & 0xFF));
b.put(static_cast<char>((u >>= 8) & 0xFF));
std::string::size_type oldSize = body.size();
// only send compressed data, if the data is compressed more than 10%
if (oldSize * 9 / 10 > b.str().size())
{
body = b.str();
log_info("gzip body " << oldSize << " bytes to " << body.size() << " bytes");
setHeader(httpheader::contentEncoding, "gzip");
}
}
}
}
void HttpReply::send(unsigned ret)
{
std::string body = outstream.str();
// complete headers
if (!hasHeader(httpheader::date))
setHeader(httpheader::date, htdate(time(0)));
if (!hasHeader(httpheader::server))
setHeader(httpheader::server, httpheader::serverName);
tryCompress(body);
if (keepAliveTimeout > 0 && keepAliveCounter > 0)
{
if (!hasHeader(httpheader::connection))
setKeepAliveHeader(getKeepAliveTimeout() + 999 / 1000);
if (!hasHeader(httpheader::contentLength))
setContentLengthHeader(body.size());
}
else if (!hasHeader(httpheader::connection))
setKeepAliveHeader(0);
if (!hasHeader(httpheader::contentType))
setHeader(httpheader::contentType, contentType);
// send header
if (sendStatusLine)
{
log_debug("HTTP/" << getMajorVersion() << '.' << getMinorVersion()
<< ' ' << ret << " OK");
socket << "HTTP/" << getMajorVersion() << '.' << getMinorVersion()
<< ' ' << ret << " OK" << "\r\n";
}
for (header_type::const_iterator it = header.begin();
it != header.end(); ++it)
{
log_debug(it->first << ' ' << it->second);
socket << it->first << ' ' << it->second << "\r\n";
}
if (hasCookies())
{
log_debug(httpheader::setCookie << ' ' << httpcookies);
socket << httpheader::setCookie << ' ' << httpcookies << "\r\n";
}
socket << "\r\n";
// send body
if (getMethod() == "HEAD")
log_debug("HEAD-request - empty body");
else
{
log_debug("send " << body.size()
<< " bytes body, method=" << getMethod());
socket << body;
}
}
HttpReply::HttpReply(std::ostream& s, bool sendStatusLine_)
: contentType("text/html"),
socket(s),
current_outstream(&outstream),
save_outstream(outstream),
keepAliveCounter(0),
sendStatusLine(sendStatusLine_)
{ }
void HttpReply::sendReply(unsigned ret)
{
if (!isDirectMode())
{
send(ret);
socket.flush();
}
}
void HttpReply::setMd5Sum()
{
cxxtools::Md5stream md5;
md5 << outstream.str().size();
setHeader(httpheader::contentMD5, md5.getHexDigest());
}
void HttpReply::throwError(unsigned errorCode, const std::string& errorMessage) const
{
throw HttpError(errorCode, errorMessage);
}
void HttpReply::throwError(const std::string& errorMessage) const
{
throw HttpError(errorMessage);
}
void HttpReply::throwNotFound(const std::string& errorMessage) const
{
throw NotFoundException(errorMessage);
}
unsigned HttpReply::redirect(const std::string& newLocation)
{
setHeader(httpheader::location, newLocation);
return HTTP_MOVED_TEMPORARILY;
}
void HttpReply::setContentLengthHeader(size_t size)
{
std::ostringstream s;
s << size;
setHeader(httpheader::contentLength, s.str());
}
void HttpReply::setKeepAliveHeader(unsigned timeout)
{
log_debug("setKeepAliveHeader(" << timeout << ')');
removeHeader(httpheader::connection);
removeHeader(httpheader::keepAlive);
if (timeout > 0 && getKeepAliveCounter() > 0)
{
std::ostringstream s;
s << "timeout=" << timeout << ", max=" << getKeepAliveCounter();
setHeader(httpheader::keepAlive, s.str());
setHeader(httpheader::connection, httpheader::connectionKeepAlive);
}
else
setHeader(httpheader::connection, httpheader::connectionClose);
}
void HttpReply::setDirectMode()
{
if (!isDirectMode())
{
send(HTTP_OK);
current_outstream = &socket;
save_outstream.setSink(socket);
}
}
void HttpReply::setDirectModeNoFlush()
{
current_outstream = &socket;
save_outstream.setSink(socket);
}
void HttpReply::setCookie(const std::string& name, const Cookie& value)
{
log_debug("setCookie(\"" << name << "\",\"" << value.getValue() << "\")");
httpcookies.setCookie(name, value);
}
bool HttpReply::keepAlive() const
{
if (getKeepAliveCounter() <= 0
|| getKeepAliveTimeout() <= 0)
return false;
header_type::const_iterator it = header.find(httpheader::connection);
return it != header.end() && it->second == httpheader::connectionKeepAlive;
}
}
<|endoftext|>
|
<commit_before>#include "LevelDirector.h"
#define SUCCESS 1
#define FAIL 0
LevelDirector::LevelDirector(){}
LevelDirector::~LevelDirector(){}
int LevelDirector::Shutdown()
{
return SUCCESS;
}
int LevelDirector::Initialize()
{
// Reset values
this->m_states.clear();
// temp reset values
this->m_currentState = NONE;
this->m_defaultState = DEFAULT;
return SUCCESS;
}
int LevelDirector::Update(float dt)
{
if (this->m_states.size() == 0)
return SUCCESS;
if (this->m_currentState == NONE)
this->m_currentState = this->m_defaultState;
//if(!(this->m_currentState))
// return SUCCESS;
State oldState = this->m_currentState;
State newState = State::DEFAULT; // please ignore
if (State::GOAL != oldState)// temporary static goal
{
if (this->ChangeState(newState))
{
//this->m_currentState->Exit();
//this->m_currentState = this->m_goalState;
//this->m_currentState->Enter();
}
//this->m_currentState->Update(dt);
}
return SUCCESS;
}
int LevelDirector::React(int entityID, EVENT event)
{
return SUCCESS;
}
void LevelDirector::AddState(State newState)
{
this->m_states.push_back(newState);
}
void LevelDirector::SetDefaultState(State state)
{
this->m_defaultState = state;
}
bool FSMEnvironment::LevelDirector::ChangeState(int newState)
{
bool change = false;
// Query list of states to see if the state exists
for (int i = 0; i < m_states.size(); i++)
{
if (m_states[i].stateID == newState)
{
change = true;
break;
}
}
return change;
}
#pragma region temp
int FSMEnvironment::State::CheckTransitions()
{
return 1;// TODO: Return ID
}
void FSMEnvironment::State::Enter()
{
}
void FSMEnvironment::State::Exit()
{
}
void FSMEnvironment::State::Update(float dt)
{
}
#pragma endregion
<commit_msg>ADD test code in Initialize() to make sure states work<commit_after>#include "LevelDirector.h"
#define SUCCESS 1
#define FAIL 0
LevelDirector::LevelDirector(){}
LevelDirector::~LevelDirector(){}
int LevelDirector::Shutdown()
{
return SUCCESS;
}
int LevelDirector::Initialize()
{
// Reset values
this->m_states.clear();
// temp reset values
this->m_currentState = NONE;
this->m_defaultState = DEFAULT;
// TODO: Import new states from new LevelState
#pragma region temp
State test;
test.stateID = 0;
test.timeDelay = 10;
test.hint = Hint::EXAMPLE;
AddState(&test);
//m_states.push_back(test);
test.stateID = 1;
test.timeDelay = 15;
test.hint = Hint::EXAMPLE;
AddState(&test);
//m_states.push_back(test);
test.stateID = 2;
test.timeDelay = 20;
test.hint = Hint::EXAMPLE;
AddState(&test);
//m_states.push_back(test);
for (int i = 0; i < 3; i++)
{
printf("%d\n", m_states[i].stateID);
}
m_currentState = &m_states.front();
#pragma endregion
return SUCCESS;
}
int LevelDirector::Update(float dt)
{
if (this->m_states.size() == 0)
return SUCCESS;
if (this->m_currentState == NONE)
this->m_currentState = this->m_defaultState;
//if(!(this->m_currentState))
// return SUCCESS;
State oldState = this->m_currentState;
State newState = State::DEFAULT; // please ignore
if (State::GOAL != oldState)// temporary static goal
{
if (this->ChangeState(newState))
{
//this->m_currentState->Exit();
//this->m_currentState = this->m_goalState;
//this->m_currentState->Enter();
}
//this->m_currentState->Update(dt);
}
return SUCCESS;
}
int LevelDirector::React(int entityID, EVENT event)
{
return SUCCESS;
}
void LevelDirector::AddState(State newState)
{
this->m_states.push_back(newState);
}
void LevelDirector::SetDefaultState(State state)
{
this->m_defaultState = state;
}
bool FSMEnvironment::LevelDirector::ChangeState(int newState)
{
bool change = false;
// Query list of states to see if the state exists
for (int i = 0; i < m_states.size(); i++)
{
if (m_states[i].stateID == newState)
{
change = true;
break;
}
}
return change;
}
#pragma region temp
int FSMEnvironment::State::CheckTransitions()
{
return 1;// TODO: Return ID
}
void FSMEnvironment::State::Enter()
{
}
void FSMEnvironment::State::Exit()
{
}
void FSMEnvironment::State::Update(float dt)
{
}
#pragma endregion
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/extensions/common/xwalk_external_extension.h"
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/values.h"
#include "xwalk/extensions/common/xwalk_external_adapter.h"
namespace xwalk {
namespace extensions {
XWalkExternalExtension::XWalkExternalExtension(const base::FilePath& path)
: xw_extension_(0),
created_instance_callback_(NULL),
destroyed_instance_callback_(NULL),
shutdown_callback_(NULL),
handle_msg_callback_(NULL),
handle_sync_msg_callback_(NULL),
handle_binary_msg_callback_(NULL),
library_path_(path),
initialized_(false) {
}
XWalkExternalExtension::~XWalkExternalExtension() {
if (!initialized_)
return;
if (shutdown_callback_)
shutdown_callback_(xw_extension_);
XWalkExternalAdapter::GetInstance()->UnregisterExtension(this);
}
bool XWalkExternalExtension::Initialize() {
if (initialized_)
return true;
base::NativeLibraryLoadError error;
base::ScopedNativeLibrary library(
base::LoadNativeLibrary(library_path_, &error));
if (!library.is_valid()) {
LOG(WARNING) << "Error loading extension '"
<< library_path_.AsUTF8Unsafe()
<< "': "
<< error.ToString();
return false;
}
XW_Initialize_Func initialize = reinterpret_cast<XW_Initialize_Func>(
library.GetFunctionPointer("XW_Initialize"));
if (!initialize) {
LOG(WARNING) << "Error loading extension '"
<< library_path_.AsUTF8Unsafe() << "': "
<< "couldn't get XW_Initialize function.";
return false;
}
XWalkExternalAdapter* external_adapter = XWalkExternalAdapter::GetInstance();
xw_extension_ = external_adapter->GetNextXWExtension();
external_adapter->RegisterExtension(this);
int ret = initialize(xw_extension_, XWalkExternalAdapter::GetInterface);
if (ret != XW_OK) {
LOG(WARNING) << "Error loading extension '"
<< library_path_.AsUTF8Unsafe() << "': "
<< "XW_Initialize function returned error value.";
return false;
}
library_.Reset(library.Release());
initialized_ = true;
return true;
}
XWalkExtensionInstance* XWalkExternalExtension::CreateInstance() {
XW_Instance xw_instance =
XWalkExternalAdapter::GetInstance()->GetNextXWInstance();
return new XWalkExternalInstance(this, xw_instance);
}
#define RETURN_IF_INITIALIZED(FUNCTION) \
if (initialized_) { \
LOG(WARNING) << "Error: can't call " FUNCTION \
<< " for extension '" << this->name() << "'" \
<< " after XW_Initialize returned."; \
return; \
}
void XWalkExternalExtension::CoreSetExtensionName(const char* name) {
RETURN_IF_INITIALIZED("SetExtensionName from CoreInterface");
set_name(name);
}
void XWalkExternalExtension::CoreSetJavaScriptAPI(const char* js_api) {
RETURN_IF_INITIALIZED("SetJavaScriptAPI from CoreInterface");
set_javascript_api(std::string(js_api));
}
void XWalkExternalExtension::CoreRegisterInstanceCallbacks(
XW_CreatedInstanceCallback created_callback,
XW_DestroyedInstanceCallback destroyed_callback) {
RETURN_IF_INITIALIZED("RegisterInstanceCallbacks from CoreInterface");
created_instance_callback_ = created_callback;
destroyed_instance_callback_ = destroyed_callback;
}
void XWalkExternalExtension::CoreRegisterShutdownCallback(
XW_ShutdownCallback callback) {
RETURN_IF_INITIALIZED("RegisterShutdownCallbacks from CoreInterface");
shutdown_callback_ = callback;
}
void XWalkExternalExtension::MessagingRegister(
XW_HandleMessageCallback callback) {
RETURN_IF_INITIALIZED("Register from MessagingInterface");
handle_msg_callback_ = callback;
}
void XWalkExternalExtension::MessagingRegisterBinaryMessageCallback(
XW_HandleBinaryMessageCallback callback) {
RETURN_IF_INITIALIZED("Register from MessagingInterface_2");
handle_binary_msg_callback_ = callback;
}
void XWalkExternalExtension::SyncMessagingRegister(
XW_HandleSyncMessageCallback callback) {
RETURN_IF_INITIALIZED("Register from Internal_SyncMessagingInterface");
handle_sync_msg_callback_ = callback;
}
void XWalkExternalExtension::EntryPointsSetExtraJSEntryPoints(
const char** entry_points) {
RETURN_IF_INITIALIZED("SetExtraJSEntryPoints from EntryPoints");
if (!entry_points)
return;
std::vector<std::string> entries;
for (int i = 0; entry_points[i]; ++i)
entries.push_back(std::string(entry_points[i]));
set_entry_points(entries);
}
void XWalkExternalExtension::RuntimeGetStringVariable(const char* key,
char* value, size_t value_len) {
const base::ValueMap::const_iterator it = runtime_variables_.find(key);
if (it != runtime_variables_.end()) {
std::string json;
base::JSONWriter::Write(*(it->second), &json);
strncpy(value, json.c_str(), value_len);
} else {
strncpy(value, "", 1);
}
}
} // namespace extensions
} // namespace xwalk
<commit_msg>Fix build warning: initialize order<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/extensions/common/xwalk_external_extension.h"
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/values.h"
#include "xwalk/extensions/common/xwalk_external_adapter.h"
namespace xwalk {
namespace extensions {
XWalkExternalExtension::XWalkExternalExtension(const base::FilePath& path)
: library_path_(path),
xw_extension_(0),
created_instance_callback_(NULL),
destroyed_instance_callback_(NULL),
shutdown_callback_(NULL),
handle_msg_callback_(NULL),
handle_sync_msg_callback_(NULL),
handle_binary_msg_callback_(NULL),
initialized_(false) {
}
XWalkExternalExtension::~XWalkExternalExtension() {
if (!initialized_)
return;
if (shutdown_callback_)
shutdown_callback_(xw_extension_);
XWalkExternalAdapter::GetInstance()->UnregisterExtension(this);
}
bool XWalkExternalExtension::Initialize() {
if (initialized_)
return true;
base::NativeLibraryLoadError error;
base::ScopedNativeLibrary library(
base::LoadNativeLibrary(library_path_, &error));
if (!library.is_valid()) {
LOG(WARNING) << "Error loading extension '"
<< library_path_.AsUTF8Unsafe()
<< "': "
<< error.ToString();
return false;
}
XW_Initialize_Func initialize = reinterpret_cast<XW_Initialize_Func>(
library.GetFunctionPointer("XW_Initialize"));
if (!initialize) {
LOG(WARNING) << "Error loading extension '"
<< library_path_.AsUTF8Unsafe() << "': "
<< "couldn't get XW_Initialize function.";
return false;
}
XWalkExternalAdapter* external_adapter = XWalkExternalAdapter::GetInstance();
xw_extension_ = external_adapter->GetNextXWExtension();
external_adapter->RegisterExtension(this);
int ret = initialize(xw_extension_, XWalkExternalAdapter::GetInterface);
if (ret != XW_OK) {
LOG(WARNING) << "Error loading extension '"
<< library_path_.AsUTF8Unsafe() << "': "
<< "XW_Initialize function returned error value.";
return false;
}
library_.Reset(library.Release());
initialized_ = true;
return true;
}
XWalkExtensionInstance* XWalkExternalExtension::CreateInstance() {
XW_Instance xw_instance =
XWalkExternalAdapter::GetInstance()->GetNextXWInstance();
return new XWalkExternalInstance(this, xw_instance);
}
#define RETURN_IF_INITIALIZED(FUNCTION) \
if (initialized_) { \
LOG(WARNING) << "Error: can't call " FUNCTION \
<< " for extension '" << this->name() << "'" \
<< " after XW_Initialize returned."; \
return; \
}
void XWalkExternalExtension::CoreSetExtensionName(const char* name) {
RETURN_IF_INITIALIZED("SetExtensionName from CoreInterface");
set_name(name);
}
void XWalkExternalExtension::CoreSetJavaScriptAPI(const char* js_api) {
RETURN_IF_INITIALIZED("SetJavaScriptAPI from CoreInterface");
set_javascript_api(std::string(js_api));
}
void XWalkExternalExtension::CoreRegisterInstanceCallbacks(
XW_CreatedInstanceCallback created_callback,
XW_DestroyedInstanceCallback destroyed_callback) {
RETURN_IF_INITIALIZED("RegisterInstanceCallbacks from CoreInterface");
created_instance_callback_ = created_callback;
destroyed_instance_callback_ = destroyed_callback;
}
void XWalkExternalExtension::CoreRegisterShutdownCallback(
XW_ShutdownCallback callback) {
RETURN_IF_INITIALIZED("RegisterShutdownCallbacks from CoreInterface");
shutdown_callback_ = callback;
}
void XWalkExternalExtension::MessagingRegister(
XW_HandleMessageCallback callback) {
RETURN_IF_INITIALIZED("Register from MessagingInterface");
handle_msg_callback_ = callback;
}
void XWalkExternalExtension::MessagingRegisterBinaryMessageCallback(
XW_HandleBinaryMessageCallback callback) {
RETURN_IF_INITIALIZED("Register from MessagingInterface_2");
handle_binary_msg_callback_ = callback;
}
void XWalkExternalExtension::SyncMessagingRegister(
XW_HandleSyncMessageCallback callback) {
RETURN_IF_INITIALIZED("Register from Internal_SyncMessagingInterface");
handle_sync_msg_callback_ = callback;
}
void XWalkExternalExtension::EntryPointsSetExtraJSEntryPoints(
const char** entry_points) {
RETURN_IF_INITIALIZED("SetExtraJSEntryPoints from EntryPoints");
if (!entry_points)
return;
std::vector<std::string> entries;
for (int i = 0; entry_points[i]; ++i)
entries.push_back(std::string(entry_points[i]));
set_entry_points(entries);
}
void XWalkExternalExtension::RuntimeGetStringVariable(const char* key,
char* value, size_t value_len) {
const base::ValueMap::const_iterator it = runtime_variables_.find(key);
if (it != runtime_variables_.end()) {
std::string json;
base::JSONWriter::Write(*(it->second), &json);
strncpy(value, json.c_str(), value_len);
} else {
strncpy(value, "", 1);
}
}
} // namespace extensions
} // namespace xwalk
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005, 2008 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "core/editing/RemoveNodeCommand.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Node.h"
#include "wtf/Assertions.h"
namespace WebCore {
RemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
: SimpleEditCommand(node->document())
, m_node(node)
, m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)
{
ASSERT(m_node);
ASSERT(m_node->parentNode());
}
void RemoveNodeCommand::doApply()
{
ContainerNode* parent = m_node->parentNode();
if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
&& !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->confusingAndOftenMisusedAttached()))
return;
ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->confusingAndOftenMisusedAttached());
m_parent = parent;
m_refChild = m_node->nextSibling();
m_node->remove(IGNORE_EXCEPTION);
}
void RemoveNodeCommand::doUnapply()
{
RefPtr<ContainerNode> parent = m_parent.release();
RefPtr<Node> refChild = m_refChild.release();
if (!parent || !parent->rendererIsEditable())
return;
parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION);
}
}
<commit_msg>RemoveNodeCommand shouldn't use confusingAndOftenMisusedAttached()<commit_after>/*
* Copyright (C) 2005, 2008 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "core/editing/RemoveNodeCommand.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Node.h"
#include "wtf/Assertions.h"
namespace WebCore {
RemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)
: SimpleEditCommand(node->document())
, m_node(node)
, m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)
{
ASSERT(m_node);
ASSERT(m_node->parentNode());
}
void RemoveNodeCommand::doApply()
{
ContainerNode* parent = m_node->parentNode();
if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
&& !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->inActiveDocument()))
return;
ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->inActiveDocument());
m_parent = parent;
m_refChild = m_node->nextSibling();
m_node->remove(IGNORE_EXCEPTION);
}
void RemoveNodeCommand::doUnapply()
{
RefPtr<ContainerNode> parent = m_parent.release();
RefPtr<Node> refChild = m_refChild.release();
if (!parent || !parent->rendererIsEditable())
return;
parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION);
}
}
<|endoftext|>
|
<commit_before>/*
SWARM
Copyright (C) 2012-2017 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
void pushop(char newop, char ** cigarendp, char * op, int * count)
{
if (newop == *op)
(*count)++;
else
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = sprintf(buf, "%d", *count);
*cigarendp -= len;
memcpy(*cigarendp, buf, len);
}
*op = newop;
*count = 1;
}
}
void finishop(char ** cigarendp, char * op, int * count)
{
if ((op) && (count))
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = sprintf(buf, "%d", *count);
*cigarendp -= len;
memcpy(*cigarendp, buf, len);
}
*op = 0;
*count = 0;
}
}
const unsigned char maskup = 1;
const unsigned char maskleft = 2;
const unsigned char maskextup = 4;
const unsigned char maskextleft = 8;
/*
Needleman/Wunsch/Sellers aligner
finds a global alignment with minimum cost
there should be positive costs/penalties for gaps and for mismatches
matches should have zero cost (0)
alignment priority when backtracking (from lower right corner):
1. left/insert/e (gap in query sequence (qseq))
2. align/diag/h (match/mismatch)
3. up/delete/f (gap in database sequence (dseq))
qseq: the reference/query/upper/vertical/from sequence
dseq: the sample/database/lower/horisontal/to sequence
typical costs:
match: 0
mismatch: 3
gapopen: 4
gapextend: 3
input
dseq: pointer to start of database sequence
dend: pointer after database sequence
qseq: pointer to start of query sequence
qend: pointer after database sequence
score_matrix: 32x32 matrix of longs with scores for aligning two symbols
gapopen: positive number indicating penalty for opening a gap of length zero
gapextend: positive number indicating penalty for extending a gap
output
nwscore: the global alignment score
nwdiff: number of non-identical nucleotides in one optimal global alignment
nwalignmentlength: the length of one optimal alignment
nwalignment: cigar string with one optimal alignment
*/
void nw(char * dseq,
char * dend,
char * qseq,
char * qend,
long * score_matrix,
unsigned long gapopen,
unsigned long gapextend,
unsigned long * nwscore,
unsigned long * nwdiff,
unsigned long * nwalignmentlength,
char ** nwalignment,
unsigned char * dir,
unsigned long * hearray,
unsigned long queryno,
unsigned long dbseqno)
{
/* dir must point to at least qlen*dlen bytes of allocated memory
hearray must point to at least 2*qlen longs of allocated memory (8*qlen bytes) */
long n, e;
long qlen = qend - qseq;
long dlen = dend - dseq;
memset(dir, 0, qlen*dlen);
long i, j;
for(i=0; i<qlen; i++)
{
hearray[2*i] = 1 * gapopen + (i+1) * gapextend; // H (N)
hearray[2*i+1] = 2 * gapopen + (i+2) * gapextend; // E
}
for(j=0; j<dlen; j++)
{
long unsigned *hep;
hep = hearray;
long f = 2 * gapopen + (j+2) * gapextend;
long h = (j == 0) ? 0 : (gapopen + j * gapextend);
for(i=0; i<qlen; i++)
{
long index = qlen*j+i;
n = *hep;
e = *(hep+1);
h += score_matrix[(dseq[j]<<5) + qseq[i]];
dir[index] |= (f < h ? maskup : 0);
h = MIN(h, f);
h = MIN(h, e);
dir[index] |= (e == h ? maskleft : 0);
*hep = h;
h += gapopen + gapextend;
e += gapextend;
f += gapextend;
dir[index] |= (f < h ? maskextup : 0);
dir[index] |= (e < h ? maskextleft : 0);
f = MIN(h,f);
e = MIN(h,e);
*(hep+1) = e;
h = n;
hep += 2;
}
}
long dist = hearray[2*qlen-2];
/* backtrack: count differences and save alignment in cigar string */
long score = 0;
long alength = 0;
long matches = 0;
char * cigar = (char *) xmalloc(qlen + dlen + 1);
char * cigarend = cigar+qlen+dlen+1;
char op = 0;
int count = 0;
*(--cigarend) = 0;
i = qlen;
j = dlen;
while ((i>0) && (j>0))
{
int d = dir[qlen*(j-1)+(i-1)];
alength++;
if ((op == 'I') && (d & maskextleft))
{
score += gapextend;
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((op == 'D') && (d & maskextup))
{
score += gapextend;
i--;
pushop('D', &cigarend, &op, &count);
}
else if (d & maskleft)
{
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
else if (d & maskup)
{
score += gapextend;
if (op != 'D')
score +=gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
else
{
score += score_matrix[(dseq[j-1] << 5) + qseq[i-1]];
if (qseq[i-1] == dseq[j-1])
matches++;
i--;
j--;
pushop('M', &cigarend, &op, &count);
}
}
while(i>0)
{
alength++;
score += gapextend;
if (op != 'D')
score += gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
while(j>0)
{
alength++;
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
finishop(&cigarend, &op, &count);
/* move and reallocate cigar */
long cigarlength = cigar+qlen+dlen-cigarend;
memmove(cigar, cigarend, cigarlength+1);
cigar = (char*) xrealloc(cigar, cigarlength+1);
* nwscore = dist;
* nwdiff = alength - matches;
* nwalignmentlength = alength;
* nwalignment = cigar;
if (score != dist)
{
fprintf(stderr, "WARNING: Error with query no %lu and db sequence no %lu:\n", queryno, dbseqno);
fprintf(stderr, "Initial and recomputed alignment score disagreement: %ld %ld\n", dist, score);
fprintf(stderr, "Alignment: %s\n", cigar);
}
}
<commit_msg>Minor security fix for sprintf<commit_after>/*
SWARM
Copyright (C) 2012-2017 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
void pushop(char newop, char ** cigarendp, char * op, int * count)
{
if (newop == *op)
(*count)++;
else
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = snprintf(buf, 25, "%d", *count);
*cigarendp -= len;
memcpy(*cigarendp, buf, len);
}
*op = newop;
*count = 1;
}
}
void finishop(char ** cigarendp, char * op, int * count)
{
if ((op) && (count))
{
*--*cigarendp = *op;
if (*count > 1)
{
char buf[25];
int len = snprintf(buf, 25, "%d", *count);
*cigarendp -= len;
memcpy(*cigarendp, buf, len);
}
*op = 0;
*count = 0;
}
}
const unsigned char maskup = 1;
const unsigned char maskleft = 2;
const unsigned char maskextup = 4;
const unsigned char maskextleft = 8;
/*
Needleman/Wunsch/Sellers aligner
finds a global alignment with minimum cost
there should be positive costs/penalties for gaps and for mismatches
matches should have zero cost (0)
alignment priority when backtracking (from lower right corner):
1. left/insert/e (gap in query sequence (qseq))
2. align/diag/h (match/mismatch)
3. up/delete/f (gap in database sequence (dseq))
qseq: the reference/query/upper/vertical/from sequence
dseq: the sample/database/lower/horisontal/to sequence
typical costs:
match: 0
mismatch: 3
gapopen: 4
gapextend: 3
input
dseq: pointer to start of database sequence
dend: pointer after database sequence
qseq: pointer to start of query sequence
qend: pointer after database sequence
score_matrix: 32x32 matrix of longs with scores for aligning two symbols
gapopen: positive number indicating penalty for opening a gap of length zero
gapextend: positive number indicating penalty for extending a gap
output
nwscore: the global alignment score
nwdiff: number of non-identical nucleotides in one optimal global alignment
nwalignmentlength: the length of one optimal alignment
nwalignment: cigar string with one optimal alignment
*/
void nw(char * dseq,
char * dend,
char * qseq,
char * qend,
long * score_matrix,
unsigned long gapopen,
unsigned long gapextend,
unsigned long * nwscore,
unsigned long * nwdiff,
unsigned long * nwalignmentlength,
char ** nwalignment,
unsigned char * dir,
unsigned long * hearray,
unsigned long queryno,
unsigned long dbseqno)
{
/* dir must point to at least qlen*dlen bytes of allocated memory
hearray must point to at least 2*qlen longs of allocated memory (8*qlen bytes) */
long n, e;
long qlen = qend - qseq;
long dlen = dend - dseq;
memset(dir, 0, qlen*dlen);
long i, j;
for(i=0; i<qlen; i++)
{
hearray[2*i] = 1 * gapopen + (i+1) * gapextend; // H (N)
hearray[2*i+1] = 2 * gapopen + (i+2) * gapextend; // E
}
for(j=0; j<dlen; j++)
{
long unsigned *hep;
hep = hearray;
long f = 2 * gapopen + (j+2) * gapextend;
long h = (j == 0) ? 0 : (gapopen + j * gapextend);
for(i=0; i<qlen; i++)
{
long index = qlen*j+i;
n = *hep;
e = *(hep+1);
h += score_matrix[(dseq[j]<<5) + qseq[i]];
dir[index] |= (f < h ? maskup : 0);
h = MIN(h, f);
h = MIN(h, e);
dir[index] |= (e == h ? maskleft : 0);
*hep = h;
h += gapopen + gapextend;
e += gapextend;
f += gapextend;
dir[index] |= (f < h ? maskextup : 0);
dir[index] |= (e < h ? maskextleft : 0);
f = MIN(h,f);
e = MIN(h,e);
*(hep+1) = e;
h = n;
hep += 2;
}
}
long dist = hearray[2*qlen-2];
/* backtrack: count differences and save alignment in cigar string */
long score = 0;
long alength = 0;
long matches = 0;
char * cigar = (char *) xmalloc(qlen + dlen + 1);
char * cigarend = cigar+qlen+dlen+1;
char op = 0;
int count = 0;
*(--cigarend) = 0;
i = qlen;
j = dlen;
while ((i>0) && (j>0))
{
int d = dir[qlen*(j-1)+(i-1)];
alength++;
if ((op == 'I') && (d & maskextleft))
{
score += gapextend;
j--;
pushop('I', &cigarend, &op, &count);
}
else if ((op == 'D') && (d & maskextup))
{
score += gapextend;
i--;
pushop('D', &cigarend, &op, &count);
}
else if (d & maskleft)
{
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
else if (d & maskup)
{
score += gapextend;
if (op != 'D')
score +=gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
else
{
score += score_matrix[(dseq[j-1] << 5) + qseq[i-1]];
if (qseq[i-1] == dseq[j-1])
matches++;
i--;
j--;
pushop('M', &cigarend, &op, &count);
}
}
while(i>0)
{
alength++;
score += gapextend;
if (op != 'D')
score += gapopen;
i--;
pushop('D', &cigarend, &op, &count);
}
while(j>0)
{
alength++;
score += gapextend;
if (op != 'I')
score += gapopen;
j--;
pushop('I', &cigarend, &op, &count);
}
finishop(&cigarend, &op, &count);
/* move and reallocate cigar */
long cigarlength = cigar+qlen+dlen-cigarend;
memmove(cigar, cigarend, cigarlength+1);
cigar = (char*) xrealloc(cigar, cigarlength+1);
* nwscore = dist;
* nwdiff = alength - matches;
* nwalignmentlength = alength;
* nwalignment = cigar;
if (score != dist)
{
fprintf(stderr, "WARNING: Error with query no %lu and db sequence no %lu:\n", queryno, dbseqno);
fprintf(stderr, "Initial and recomputed alignment score disagreement: %ld %ld\n", dist, score);
fprintf(stderr, "Alignment: %s\n", cigar);
}
}
<|endoftext|>
|
<commit_before>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-12-10 GONG Chen <chen.sst@gmail.com>
//
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <rime_version.h>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/dict/dictionary.h>
#include <rime/dict/dict_compiler.h>
#include <rime/expl/customizer.h>
#include <rime/expl/deployment_tasks.h>
namespace fs = boost::filesystem;
namespace rime {
bool InstallationUpdate::Run(Deployer* deployer) {
EZLOGGERPRINT("updating rime installation.");
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path installation_info(user_data_path / "installation.yaml");
rime::Config config;
std::string installation_id;
std::string last_distro_code_name;
std::string last_distro_version;
std::string last_rime_version;
if (config.LoadFromFile(installation_info.string())) {
if (config.GetString("installation_id", &installation_id)) {
EZLOGGERPRINT("installation info exists. installation id: %s",
installation_id.c_str());
// for now:
deployer->user_id = installation_id;
}
if (config.GetString("distribution_code_name", &last_distro_code_name)) {
EZLOGGERPRINT("previous distribution: %s",
last_distro_code_name.c_str());
}
if (config.GetString("distribution_version", &last_distro_version)) {
EZLOGGERPRINT("previous distribution version: %s",
last_distro_version.c_str());
}
if (config.GetString("rime_version", &last_rime_version)) {
EZLOGGERPRINT("previous Rime version: %s", last_rime_version.c_str());
}
}
if (!installation_id.empty() &&
last_distro_code_name == deployer->distribution_code_name &&
last_distro_version == deployer->distribution_version &&
last_rime_version == RIME_VERSION) {
return true;
}
EZLOGGERPRINT("creating installation.");
time_t now = time(NULL);
std::string time_str(ctime(&now));
boost::trim(time_str);
if (installation_id.empty()) {
installation_id =
boost::uuids::to_string(boost::uuids::random_generator()());
EZLOGGERPRINT("generated installation id: %s", installation_id.c_str());
// for now:
deployer->user_id = installation_id;
config.SetString("installation_id", installation_id);
config.SetString("install_time", time_str);
}
else {
config.SetString("update_time", time_str);
}
if (!deployer->distribution_name.empty()) {
config.SetString("distribution_name", deployer->distribution_name);
EZLOGGERPRINT("distribution: %s", deployer->distribution_name.c_str());
}
if (!deployer->distribution_code_name.empty()) {
config.SetString("distribution_code_name",
deployer->distribution_code_name);
EZLOGGERPRINT("distribution code name: %s",
deployer->distribution_code_name.c_str());
}
if (!deployer->distribution_version.empty()) {
config.SetString("distribution_version",
deployer->distribution_version);
EZLOGGERPRINT("distribution version: %s",
deployer->distribution_version.c_str());
}
config.SetString("rime_version", RIME_VERSION);
EZLOGGERPRINT("rime version: %s", RIME_VERSION);
return config.SaveToFile(installation_info.string());
}
bool WorkspaceUpdate::Run(Deployer* deployer) {
EZLOGGERPRINT("updating workspace.");
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path default_config_path(user_data_path / "default.yaml");
{
scoped_ptr<DeploymentTask> t;
t.reset(new ConfigFileUpdate("default.yaml", "config_version"));
t->Run(deployer);
}
Config config;
if (!config.LoadFromFile(default_config_path.string())) {
EZLOGGERPRINT("Error loading default config from '%s'.",
default_config_path.string().c_str());
return false;
}
ConfigListPtr schema_list = config.GetList("schema_list");
if (!schema_list) {
EZLOGGERPRINT("Warning: schema list not defined.");
return false;
}
EZLOGGERPRINT("updating schemas.");
int success = 0;
int failure = 0;
ConfigList::Iterator it = schema_list->begin();
for (; it != schema_list->end(); ++it) {
ConfigMapPtr item = As<ConfigMap>(*it);
if (!item) continue;
ConfigValuePtr schema_property = item->GetValue("schema");
if (!schema_property) continue;
const std::string &schema_id(schema_property->str());
fs::path schema_path = shared_data_path / (schema_id + ".schema.yaml");
if (!fs::exists(schema_path)) {
schema_path = user_data_path / (schema_id + ".schema.yaml");
}
scoped_ptr<DeploymentTask> t(new SchemaUpdate(schema_path.string()));
if (t->Run(deployer))
++success;
else
++failure;
}
EZLOGGERPRINT("finished updating schemas: %d success, %d failure.",
success, failure);
return failure != 0;
}
bool SchemaUpdate::Run(Deployer* deployer) {
fs::path source_path(schema_file_);
if (!fs::exists(source_path)) {
EZLOGGERPRINT("Error updating schema: nonexistent file '%s'.",
schema_file_.c_str());
return false;
}
Config config;
std::string schema_id;
if (!config.LoadFromFile(schema_file_) ||
!config.GetString("schema/schema_id", &schema_id) ||
schema_id.empty()) {
EZLOGGERPRINT("Error: invalid schema definition in '%s'.",
schema_file_.c_str());
return false;
}
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path destination_path(user_data_path / (schema_id + ".schema.yaml"));
Customizer customizer(source_path, destination_path, "schema/version");
if (customizer.UpdateConfigFile()) {
EZLOGGERPRINT("schema '%s' is updated.", schema_id.c_str());
}
if (!config.LoadFromFile(destination_path.string())) {
EZLOGGERPRINT("Error loading schema file '%s'.",
destination_path.string().c_str());
return false;
}
std::string dict_name;
if (!config.GetString("translator/dictionary", &dict_name)) {
// not requiring a dictionary
return true;
}
std::string dict_file_name(dict_name + ".dict.yaml");
fs::path dict_path(source_path.parent_path() / dict_file_name);
if (!fs::exists(dict_path)) {
dict_path = shared_data_path / dict_file_name;
if (!fs::exists(dict_path)) {
EZLOGGERPRINT("Error: source file for dictionary '%s' does not exist.",
dict_name.c_str());
return false;
}
}
DictionaryComponent component;
scoped_ptr<Dictionary> dict;
dict.reset(component.CreateDictionaryFromConfig(&config, "translator"));
if (!dict) {
EZLOGGERPRINT("Error creating dictionary '%s'.", dict_name.c_str());
return false;
}
EZLOGGERPRINT("preparing dictionary '%s'.", dict_name.c_str());
DictCompiler dict_compiler(dict.get());
dict_compiler.Compile(dict_path.string(), destination_path.string());
EZLOGGERPRINT("dictionary '%s' is ready.", dict_name.c_str());
return true;
}
bool ConfigFileUpdate::Run(Deployer* deployer) {
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path source_config_path(shared_data_path / file_name_);
fs::path dest_config_path(user_data_path / file_name_);
if (!fs::exists(source_config_path)) {
EZLOGGERPRINT("Warning: '%s' is missing from shared data directory.",
file_name_.c_str());
source_config_path = dest_config_path;
}
Customizer customizer(source_config_path, dest_config_path, version_key_);
return customizer.UpdateConfigFile();
}
} // namespace rime
<commit_msg>No comment.<commit_after>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-12-10 GONG Chen <chen.sst@gmail.com>
//
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <rime_version.h>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/dict/dictionary.h>
#include <rime/dict/dict_compiler.h>
#include <rime/expl/customizer.h>
#include <rime/expl/deployment_tasks.h>
namespace fs = boost::filesystem;
namespace rime {
bool InstallationUpdate::Run(Deployer* deployer) {
EZLOGGERPRINT("updating rime installation.");
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path installation_info(user_data_path / "installation.yaml");
rime::Config config;
std::string installation_id;
std::string last_distro_code_name;
std::string last_distro_version;
std::string last_rime_version;
if (config.LoadFromFile(installation_info.string())) {
if (config.GetString("installation_id", &installation_id)) {
EZLOGGERPRINT("installation info exists. installation id: %s",
installation_id.c_str());
// for now:
deployer->user_id = installation_id;
}
if (config.GetString("distribution_code_name", &last_distro_code_name)) {
EZLOGGERPRINT("previous distribution: %s",
last_distro_code_name.c_str());
}
if (config.GetString("distribution_version", &last_distro_version)) {
EZLOGGERPRINT("previous distribution version: %s",
last_distro_version.c_str());
}
if (config.GetString("rime_version", &last_rime_version)) {
EZLOGGERPRINT("previous Rime version: %s", last_rime_version.c_str());
}
}
if (!installation_id.empty() &&
last_distro_code_name == deployer->distribution_code_name &&
last_distro_version == deployer->distribution_version &&
last_rime_version == RIME_VERSION) {
return true;
}
EZLOGGERPRINT("creating installation.");
time_t now = time(NULL);
std::string time_str(ctime(&now));
boost::trim(time_str);
if (installation_id.empty()) {
installation_id =
boost::uuids::to_string(boost::uuids::random_generator()());
EZLOGGERPRINT("generated installation id: %s", installation_id.c_str());
// for now:
deployer->user_id = installation_id;
config.SetString("installation_id", installation_id);
config.SetString("install_time", time_str);
}
else {
config.SetString("update_time", time_str);
}
if (!deployer->distribution_name.empty()) {
config.SetString("distribution_name", deployer->distribution_name);
EZLOGGERPRINT("distribution: %s", deployer->distribution_name.c_str());
}
if (!deployer->distribution_code_name.empty()) {
config.SetString("distribution_code_name",
deployer->distribution_code_name);
EZLOGGERPRINT("distribution code name: %s",
deployer->distribution_code_name.c_str());
}
if (!deployer->distribution_version.empty()) {
config.SetString("distribution_version",
deployer->distribution_version);
EZLOGGERPRINT("distribution version: %s",
deployer->distribution_version.c_str());
}
config.SetString("rime_version", RIME_VERSION);
EZLOGGERPRINT("rime version: %s", RIME_VERSION);
return config.SaveToFile(installation_info.string());
}
bool WorkspaceUpdate::Run(Deployer* deployer) {
EZLOGGERPRINT("updating workspace.");
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path default_config_path(user_data_path / "default.yaml");
{
scoped_ptr<DeploymentTask> t;
t.reset(new ConfigFileUpdate("default.yaml", "config_version"));
t->Run(deployer);
}
Config config;
if (!config.LoadFromFile(default_config_path.string())) {
EZLOGGERPRINT("Error loading default config from '%s'.",
default_config_path.string().c_str());
return false;
}
ConfigListPtr schema_list = config.GetList("schema_list");
if (!schema_list) {
EZLOGGERPRINT("Warning: schema list not defined.");
return false;
}
EZLOGGERPRINT("updating schemas.");
int success = 0;
int failure = 0;
ConfigList::Iterator it = schema_list->begin();
for (; it != schema_list->end(); ++it) {
ConfigMapPtr item = As<ConfigMap>(*it);
if (!item) continue;
ConfigValuePtr schema_property = item->GetValue("schema");
if (!schema_property) continue;
const std::string &schema_id(schema_property->str());
fs::path schema_path = shared_data_path / (schema_id + ".schema.yaml");
if (!fs::exists(schema_path)) {
schema_path = user_data_path / (schema_id + ".schema.yaml");
}
scoped_ptr<DeploymentTask> t(new SchemaUpdate(schema_path.string()));
if (t->Run(deployer))
++success;
else
++failure;
}
EZLOGGERPRINT("finished updating schemas: %d success, %d failure.",
success, failure);
return failure == 0;
}
bool SchemaUpdate::Run(Deployer* deployer) {
fs::path source_path(schema_file_);
if (!fs::exists(source_path)) {
EZLOGGERPRINT("Error updating schema: nonexistent file '%s'.",
schema_file_.c_str());
return false;
}
Config config;
std::string schema_id;
if (!config.LoadFromFile(schema_file_) ||
!config.GetString("schema/schema_id", &schema_id) ||
schema_id.empty()) {
EZLOGGERPRINT("Error: invalid schema definition in '%s'.",
schema_file_.c_str());
return false;
}
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path destination_path(user_data_path / (schema_id + ".schema.yaml"));
Customizer customizer(source_path, destination_path, "schema/version");
if (customizer.UpdateConfigFile()) {
EZLOGGERPRINT("schema '%s' is updated.", schema_id.c_str());
}
if (!config.LoadFromFile(destination_path.string())) {
EZLOGGERPRINT("Error loading schema file '%s'.",
destination_path.string().c_str());
return false;
}
std::string dict_name;
if (!config.GetString("translator/dictionary", &dict_name)) {
// not requiring a dictionary
return true;
}
std::string dict_file_name(dict_name + ".dict.yaml");
fs::path dict_path(source_path.parent_path() / dict_file_name);
if (!fs::exists(dict_path)) {
dict_path = shared_data_path / dict_file_name;
if (!fs::exists(dict_path)) {
EZLOGGERPRINT("Error: source file for dictionary '%s' does not exist.",
dict_name.c_str());
return false;
}
}
DictionaryComponent component;
scoped_ptr<Dictionary> dict;
dict.reset(component.CreateDictionaryFromConfig(&config, "translator"));
if (!dict) {
EZLOGGERPRINT("Error creating dictionary '%s'.", dict_name.c_str());
return false;
}
EZLOGGERPRINT("preparing dictionary '%s'.", dict_name.c_str());
DictCompiler dict_compiler(dict.get());
dict_compiler.Compile(dict_path.string(), destination_path.string());
EZLOGGERPRINT("dictionary '%s' is ready.", dict_name.c_str());
return true;
}
bool ConfigFileUpdate::Run(Deployer* deployer) {
fs::path shared_data_path(deployer->shared_data_dir);
fs::path user_data_path(deployer->user_data_dir);
fs::path source_config_path(shared_data_path / file_name_);
fs::path dest_config_path(user_data_path / file_name_);
if (!fs::exists(source_config_path)) {
EZLOGGERPRINT("Warning: '%s' is missing from shared data directory.",
file_name_.c_str());
source_config_path = dest_config_path;
}
Customizer customizer(source_config_path, dest_config_path, version_key_);
return customizer.UpdateConfigFile();
}
} // namespace rime
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/pdal_internal.hpp>
#ifdef PDAL_HAVE_PYTHON
#include <pdal/GlobalEnvironment.hpp>
#include <pdal/filters/Programmable.hpp>
#include <pdal/PointBuffer.hpp>
namespace pdal
{
namespace filters
{
Options Programmable::getDefaultOptions()
{
Options options;
options.add("script", "");
options.add("module", "");
options.add("function", "");
return options;
}
void Programmable::processOptions(const Options& options)
{
m_source = options.getValueOrDefault<std::string>("source", "");
if (m_source.empty())
m_source = FileUtils::readFileIntoString(
options.getValueOrThrow<std::string>("filename"));
m_module = options.getValueOrThrow<std::string>("module");
m_function = options.getValueOrThrow<std::string>("function");
}
void Programmable::ready(PointContext ctx)
{
m_script = new plang::Script(m_source, m_module, m_function);
m_pythonMethod = new plang::BufferedInvocation(*m_script);
m_pythonMethod->compile();
GlobalEnvironment::get().getPythonEnvironment().set_stdout(
log()->getLogStream());
}
void Programmable::filter(PointBuffer& buf)
{
log()->get(logDEBUG5) << "Python script " << *m_script << " processing " <<
buf.size() << " points." << std::endl;
m_pythonMethod->resetArguments();
m_pythonMethod->beginChunk(buf);
m_pythonMethod->execute();
m_pythonMethod->endChunk(buf);
}
void Programmable::done(PointContext ctx)
{
GlobalEnvironment::get().getPythonEnvironment().reset_stdout();
delete m_pythonMethod;
delete m_script;
}
} // namespace filters
} // namespace pdal
#endif
<commit_msg>LogLevel rename<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <pdal/pdal_internal.hpp>
#ifdef PDAL_HAVE_PYTHON
#include <pdal/GlobalEnvironment.hpp>
#include <pdal/filters/Programmable.hpp>
#include <pdal/PointBuffer.hpp>
namespace pdal
{
namespace filters
{
Options Programmable::getDefaultOptions()
{
Options options;
options.add("script", "");
options.add("module", "");
options.add("function", "");
return options;
}
void Programmable::processOptions(const Options& options)
{
m_source = options.getValueOrDefault<std::string>("source", "");
if (m_source.empty())
m_source = FileUtils::readFileIntoString(
options.getValueOrThrow<std::string>("filename"));
m_module = options.getValueOrThrow<std::string>("module");
m_function = options.getValueOrThrow<std::string>("function");
}
void Programmable::ready(PointContext ctx)
{
m_script = new plang::Script(m_source, m_module, m_function);
m_pythonMethod = new plang::BufferedInvocation(*m_script);
m_pythonMethod->compile();
GlobalEnvironment::get().getPythonEnvironment().set_stdout(
log()->getLogStream());
}
void Programmable::filter(PointBuffer& buf)
{
log()->get(LogLevel::DEBUG5) << "Python script " << *m_script << " processing " <<
buf.size() << " points." << std::endl;
m_pythonMethod->resetArguments();
m_pythonMethod->beginChunk(buf);
m_pythonMethod->execute();
m_pythonMethod->endChunk(buf);
}
void Programmable::done(PointContext ctx)
{
GlobalEnvironment::get().getPythonEnvironment().reset_stdout();
delete m_pythonMethod;
delete m_script;
}
} // namespace filters
} // namespace pdal
#endif
<|endoftext|>
|
<commit_before>/* get_struct_from_inchi.cc
* Copyright 2014 Cubane Canada, Inc.
*
* Released under the MIT license -- see MIT-LICENSE for details
*/
#include <nan.h>
#include "./using_v8.h"
#include "./get_struct_from_inchi_data.h"
#include "./get_struct_from_inchi_worker.h"
#include "./inchi_stereo.h"
void addstring(Handle<Object> ret, const char * name, const char * value);
NAN_METHOD(GetStructFromINCHI) {
NanScope();
char * inchi = NanCString(args[0], 0);
NanCallback * callback = new NanCallback(args[1].As<Function>());
NanAsyncQueueWorker(new GetStructFromINCHIWorker(callback, inchi));
delete[] inchi;
NanReturnUndefined();
}
static Handle<Object> MakeBond(const inchi_Atom& a, int n) {
Local<Object> ret = Object::New();
ret->Set(NanSymbol("neighbor"), Number::New(a.neighbor[n]));
ret->Set(NanSymbol("bond_type"), Number::New(a.bond_type[n]));
ret->Set(NanSymbol("bond_stereo"), Number::New(a.bond_stereo[n]));
return ret;
}
static Handle<Object> MakeAtom(const inchi_Atom& a) {
Local<Object> ret = Object::New();
ret->Set(NanSymbol("x"), Number::New(a.x));
ret->Set(NanSymbol("y"), Number::New(a.y));
ret->Set(NanSymbol("z"), Number::New(a.z));
addstring(ret, "elname", a.elname);
// compress neighbor, bond_type, and bond_stereo arrays
Local<Array> bonds = Array::New();
for (int i = 0; i < a.num_bonds; i += 1) {
bonds->Set(i, MakeBond(a, i));
}
ret->Set(NanSymbol("bonds"), bonds);
// implicit hydrogens
Local<Array> num_iso_H = Array::New();
for (int i = 0; i < NUM_H_ISOTOPES+1; i += 1) {
num_iso_H->Set(i, Number::New(a.num_iso_H[i]));
}
ret->Set(NanSymbol("num_iso_H"), num_iso_H);
ret->Set(NanSymbol("isotopic_mass"), Number::New(a.isotopic_mass));
ret->Set(NanSymbol("radical"), Number::New(a.radical));
ret->Set(NanSymbol("charge"), Number::New(a.charge));
return ret;
}
Handle<Object> MakeStereo0D(const inchi_Stereo0D& stereo) {
Local<Object> ret = Object::New();
Local<Array> neighbor = Array::New();
for (int i = 0; i < STEREO0D_NEIGHBORS; i += 1) {
neighbor->Set(i, Number::New(stereo.neighbor[i]));
}
ret->Set(NanSymbol("neighbor"), neighbor);
ret->Set(NanSymbol("central_atom"), Number::New(stereo.central_atom));
ret->Set(NanSymbol("type"), Number::New(stereo.type));
ret->Set(NanSymbol("parity"), Number::New(stereo.parity));
return ret;
}
Handle<Object> MakeStructure(const GetStructFromINCHIData& data) {
Local<Object> ret = Object::New();
// atom -- array of atom objects
Local<Array> atom = Array::New();
for (int i = 0; i < data.out_.num_atoms; i += 1) {
atom->Set(i, MakeAtom(data.out_.atom[i]));
}
ret->Set(NanSymbol("atom"), atom);
// stereo0D -- array of stereo0D objects
Local<Array> stereo0D = Array::New();
for (int i = 0; i < data.out_.num_stereo0D; i += 1) {
stereo0D->Set(i, MakeStereo0D(data.out_.stereo0D[i]));
}
ret->Set(NanSymbol("stereo0D"), stereo0D);
// message
addstring(ret, "message", data.out_.szMessage);
// log
addstring(ret, "log", data.out_.szLog);
// warning flags
// TODO(SOM): add these
return ret;
}
<commit_msg>inchilib: protect intermediate values from gc<commit_after>/* get_struct_from_inchi.cc
* Copyright 2014 Cubane Canada, Inc.
*
* Released under the MIT license -- see MIT-LICENSE for details
*/
#include <nan.h>
#include "./using_v8.h"
#include "./get_struct_from_inchi_data.h"
#include "./get_struct_from_inchi_worker.h"
#include "./inchi_stereo.h"
void addstring(Handle<Object> ret, const char * name, const char * value);
NAN_METHOD(GetStructFromINCHI) {
NanScope();
char * inchi = NanCString(args[0], 0);
NanCallback * callback = new NanCallback(args[1].As<Function>());
NanAsyncQueueWorker(new GetStructFromINCHIWorker(callback, inchi));
delete[] inchi;
NanReturnUndefined();
}
static Handle<Object> MakeBond(const inchi_Atom& a, int n) {
NanScope();
Handle<Object> ret = NanNewLocal<Object>(Object::New());
ret->Set(NanSymbol("neighbor"), Number::New(a.neighbor[n]));
ret->Set(NanSymbol("bond_type"), Number::New(a.bond_type[n]));
ret->Set(NanSymbol("bond_stereo"), Number::New(a.bond_stereo[n]));
return scope.Close(ret);
}
static Handle<Object> MakeAtom(const inchi_Atom& a) {
NanScope();
Handle<Object> ret = NanNewLocal<Object>(Object::New());
ret->Set(NanSymbol("x"), Number::New(a.x));
ret->Set(NanSymbol("y"), Number::New(a.y));
ret->Set(NanSymbol("z"), Number::New(a.z));
addstring(ret, "elname", a.elname);
// compress neighbor, bond_type, and bond_stereo arrays
ret->Set(NanSymbol("bonds"), Array::New());
Local<Array> bonds = ret->Get(NanSymbol("bonds")).As<Array>();
for (int i = 0; i < a.num_bonds; i += 1) {
bonds->Set(i, MakeBond(a, i));
}
// implicit hydrogens
ret->Set(NanSymbol("num_iso_H"), Array::New());
Local<Array> num_iso_H = ret->Get(NanSymbol("num_iso_H")).As<Array>();
for (int i = 0; i < NUM_H_ISOTOPES+1; i += 1) {
num_iso_H->Set(i, Number::New(a.num_iso_H[i]));
}
ret->Set(NanSymbol("isotopic_mass"), Number::New(a.isotopic_mass));
ret->Set(NanSymbol("radical"), Number::New(a.radical));
ret->Set(NanSymbol("charge"), Number::New(a.charge));
return scope.Close(ret);
}
Handle<Object> MakeStereo0D(const inchi_Stereo0D& stereo) {
NanScope();
Local<Object> ret = NanNewLocal<Object>(Object::New());
Local<Array> neighbor = NanNewLocal<Array>(Array::New());
for (int i = 0; i < STEREO0D_NEIGHBORS; i += 1) {
neighbor->Set(i, Number::New(stereo.neighbor[i]));
}
ret->Set(NanSymbol("neighbor"), neighbor);
ret->Set(NanSymbol("central_atom"), Number::New(stereo.central_atom));
ret->Set(NanSymbol("type"), Number::New(stereo.type));
ret->Set(NanSymbol("parity"), Number::New(stereo.parity));
return scope.Close(ret);
}
Handle<Object> MakeStructure(const GetStructFromINCHIData& data) {
NanScope();
Handle<Object> ret = NanNewLocal<Object>(Object::New());
// atom -- array of atom objects
ret->Set(NanSymbol("atom"), Array::New());
Local<Array> atom = ret->Get(NanSymbol("atom")).As<Array>();
for (int i = 0; i < data.out_.num_atoms; i += 1) {
atom->Set(i, MakeAtom(data.out_.atom[i]));
}
// stereo0D -- array of stereo0D objects
Local<Array> stereo0D = Array::New();
for (int i = 0; i < data.out_.num_stereo0D; i += 1) {
stereo0D->Set(i, MakeStereo0D(data.out_.stereo0D[i]));
}
ret->Set(NanSymbol("stereo0D"), stereo0D);
// message
addstring(ret, "message", data.out_.szMessage);
// log
addstring(ret, "log", data.out_.szLog);
// warning flags
// TODO(SOM): add these
return scope.Close(ret);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrDrawingManager.h"
#include "GrContext.h"
#include "GrDrawContext.h"
#include "GrDrawTarget.h"
#include "GrPathRenderingDrawContext.h"
#include "GrResourceProvider.h"
#include "GrSoftwarePathRenderer.h"
#include "GrSurfacePriv.h"
#include "SkSurface_Gpu.h"
#include "SkTTopoSort.h"
#include "instanced/InstancedRendering.h"
#include "text/GrAtlasTextContext.h"
#include "text/GrStencilAndCoverTextContext.h"
using gr_instanced::InstancedRendering;
void GrDrawingManager::cleanup() {
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->makeClosed(); // no drawTarget should receive a new command after this
fDrawTargets[i]->clearRT();
// We shouldn't need to do this, but it turns out some clients still hold onto drawtargets
// after a cleanup
fDrawTargets[i]->reset();
fDrawTargets[i]->unref();
}
fDrawTargets.reset();
delete fPathRendererChain;
fPathRendererChain = nullptr;
SkSafeSetNull(fSoftwarePathRenderer);
}
GrDrawingManager::~GrDrawingManager() {
this->cleanup();
}
void GrDrawingManager::abandon() {
fAbandoned = true;
for (int i = 0; i < fDrawTargets.count(); ++i) {
if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport()) {
InstancedRendering* ir = fDrawTargets[i]->instancedRendering();
ir->resetGpuResources(InstancedRendering::ResetType::kAbandon);
}
}
this->cleanup();
}
void GrDrawingManager::freeGpuResources() {
// a path renderer may be holding onto resources
delete fPathRendererChain;
fPathRendererChain = nullptr;
SkSafeSetNull(fSoftwarePathRenderer);
for (int i = 0; i < fDrawTargets.count(); ++i) {
if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport()) {
InstancedRendering* ir = fDrawTargets[i]->instancedRendering();
ir->resetGpuResources(InstancedRendering::ResetType::kDestroy);
}
}
}
void GrDrawingManager::reset() {
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->reset();
}
fFlushState.reset();
}
void GrDrawingManager::internalFlush(GrResourceCache::FlushType type) {
if (fFlushing || this->wasAbandoned()) {
return;
}
fFlushing = true;
bool flushed = false;
SkDEBUGCODE(bool result =)
SkTTopoSort<GrDrawTarget, GrDrawTarget::TopoSortTraits>(&fDrawTargets);
SkASSERT(result);
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->prepareBatches(&fFlushState);
}
// Enable this to print out verbose batching information
#if 0
for (int i = 0; i < fDrawTargets.count(); ++i) {
SkDEBUGCODE(fDrawTargets[i]->dump();)
}
#endif
// Upload all data to the GPU
fFlushState.preIssueDraws();
for (int i = 0; i < fDrawTargets.count(); ++i) {
if (fDrawTargets[i]->drawBatches(&fFlushState)) {
flushed = true;
}
}
SkASSERT(fFlushState.nextDrawToken() == fFlushState.nextTokenToFlush());
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->reset();
#ifdef ENABLE_MDB
fDrawTargets[i]->unref();
#endif
}
#ifndef ENABLE_MDB
// When MDB is disabled we keep reusing the same drawTarget
if (fDrawTargets.count()) {
SkASSERT(fDrawTargets.count() == 1);
// Clear out this flag so the topological sort's SkTTopoSort_CheckAllUnmarked check
// won't bark
fDrawTargets[0]->resetFlag(GrDrawTarget::kWasOutput_Flag);
}
#else
fDrawTargets.reset();
#endif
fFlushState.reset();
// We always have to notify the cache when it requested a flush so it can reset its state.
if (flushed || type == GrResourceCache::FlushType::kCacheRequested) {
fContext->getResourceCache()->notifyFlushOccurred(type);
}
fFlushing = false;
}
void GrDrawingManager::prepareSurfaceForExternalIO(GrSurface* surface) {
if (this->wasAbandoned()) {
return;
}
SkASSERT(surface);
SkASSERT(surface->getContext() == fContext);
if (surface->surfacePriv().hasPendingIO()) {
this->flush();
}
GrRenderTarget* rt = surface->asRenderTarget();
if (fContext->getGpu() && rt) {
fContext->getGpu()->resolveRenderTarget(rt);
}
}
GrDrawTarget* GrDrawingManager::newDrawTarget(GrRenderTarget* rt) {
SkASSERT(fContext);
#ifndef ENABLE_MDB
// When MDB is disabled we always just return the single drawTarget
if (fDrawTargets.count()) {
SkASSERT(fDrawTargets.count() == 1);
// In the non-MDB-world the same drawTarget gets reused for multiple render targets.
// Update this pointer so all the asserts are happy
rt->setLastDrawTarget(fDrawTargets[0]);
// DrawingManager gets the creation ref - this ref is for the caller
return SkRef(fDrawTargets[0]);
}
#endif
GrDrawTarget* dt = new GrDrawTarget(rt, fContext->getGpu(), fContext->resourceProvider(),
fContext->getAuditTrail(), fOptionsForDrawTargets);
*fDrawTargets.append() = dt;
// DrawingManager gets the creation ref - this ref is for the caller
return SkRef(dt);
}
GrAtlasTextContext* GrDrawingManager::getAtlasTextContext() {
if (!fAtlasTextContext) {
fAtlasTextContext.reset(GrAtlasTextContext::Create());
}
return fAtlasTextContext.get();
}
/*
* This method finds a path renderer that can draw the specified path on
* the provided target.
* Due to its expense, the software path renderer has split out so it can
* can be individually allowed/disallowed via the "allowSW" boolean.
*/
GrPathRenderer* GrDrawingManager::getPathRenderer(const GrPathRenderer::CanDrawPathArgs& args,
bool allowSW,
GrPathRendererChain::DrawType drawType,
GrPathRenderer::StencilSupport* stencilSupport) {
if (!fPathRendererChain) {
fPathRendererChain = new GrPathRendererChain(fContext, fOptionsForPathRendererChain);
}
GrPathRenderer* pr = fPathRendererChain->getPathRenderer(args, drawType, stencilSupport);
if (!pr && allowSW) {
if (!fSoftwarePathRenderer) {
fSoftwarePathRenderer =
new GrSoftwarePathRenderer(fContext->textureProvider(),
fOptionsForPathRendererChain.fAllowPathMaskCaching);
}
pr = fSoftwarePathRenderer;
}
return pr;
}
sk_sp<GrDrawContext> GrDrawingManager::makeDrawContext(sk_sp<GrRenderTarget> rt,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps) {
if (this->wasAbandoned()) {
return nullptr;
}
// SkSurface catches bad color space usage at creation. This check handles anything that slips
// by, including internal usage. We allow a null color space here, for read/write pixels and
// other special code paths. If a color space is provided, though, enforce all other rules.
if (colorSpace && !SkSurface_Gpu::Valid(fContext, rt->config(), colorSpace.get())) {
// SRGBTODO: Enable this assert once image filters are propagating color type and space
// SkDEBUGFAIL("Invalid config and colorspace combination");
return nullptr;
}
bool useDIF = false;
if (surfaceProps) {
useDIF = surfaceProps->isUseDeviceIndependentFonts();
}
if (useDIF && fContext->caps()->shaderCaps()->pathRenderingSupport() &&
rt->isStencilBufferMultisampled()) {
GrStencilAttachment* sb = fContext->resourceProvider()->attachStencilAttachment(rt.get());
if (sb) {
return sk_sp<GrDrawContext>(new GrPathRenderingDrawContext(
fContext, this, std::move(rt),
std::move(colorSpace), surfaceProps,
fContext->getAuditTrail(), fSingleOwner));
}
}
return sk_sp<GrDrawContext>(new GrDrawContext(fContext, this, std::move(rt),
std::move(colorSpace), surfaceProps,
fContext->getAuditTrail(),
fSingleOwner));
}
<commit_msg>Recent image filter work now allows this check to be enabled.<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrDrawingManager.h"
#include "GrContext.h"
#include "GrDrawContext.h"
#include "GrDrawTarget.h"
#include "GrPathRenderingDrawContext.h"
#include "GrResourceProvider.h"
#include "GrSoftwarePathRenderer.h"
#include "GrSurfacePriv.h"
#include "SkSurface_Gpu.h"
#include "SkTTopoSort.h"
#include "instanced/InstancedRendering.h"
#include "text/GrAtlasTextContext.h"
#include "text/GrStencilAndCoverTextContext.h"
using gr_instanced::InstancedRendering;
void GrDrawingManager::cleanup() {
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->makeClosed(); // no drawTarget should receive a new command after this
fDrawTargets[i]->clearRT();
// We shouldn't need to do this, but it turns out some clients still hold onto drawtargets
// after a cleanup
fDrawTargets[i]->reset();
fDrawTargets[i]->unref();
}
fDrawTargets.reset();
delete fPathRendererChain;
fPathRendererChain = nullptr;
SkSafeSetNull(fSoftwarePathRenderer);
}
GrDrawingManager::~GrDrawingManager() {
this->cleanup();
}
void GrDrawingManager::abandon() {
fAbandoned = true;
for (int i = 0; i < fDrawTargets.count(); ++i) {
if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport()) {
InstancedRendering* ir = fDrawTargets[i]->instancedRendering();
ir->resetGpuResources(InstancedRendering::ResetType::kAbandon);
}
}
this->cleanup();
}
void GrDrawingManager::freeGpuResources() {
// a path renderer may be holding onto resources
delete fPathRendererChain;
fPathRendererChain = nullptr;
SkSafeSetNull(fSoftwarePathRenderer);
for (int i = 0; i < fDrawTargets.count(); ++i) {
if (GrCaps::InstancedSupport::kNone != fContext->caps()->instancedSupport()) {
InstancedRendering* ir = fDrawTargets[i]->instancedRendering();
ir->resetGpuResources(InstancedRendering::ResetType::kDestroy);
}
}
}
void GrDrawingManager::reset() {
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->reset();
}
fFlushState.reset();
}
void GrDrawingManager::internalFlush(GrResourceCache::FlushType type) {
if (fFlushing || this->wasAbandoned()) {
return;
}
fFlushing = true;
bool flushed = false;
SkDEBUGCODE(bool result =)
SkTTopoSort<GrDrawTarget, GrDrawTarget::TopoSortTraits>(&fDrawTargets);
SkASSERT(result);
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->prepareBatches(&fFlushState);
}
// Enable this to print out verbose batching information
#if 0
for (int i = 0; i < fDrawTargets.count(); ++i) {
SkDEBUGCODE(fDrawTargets[i]->dump();)
}
#endif
// Upload all data to the GPU
fFlushState.preIssueDraws();
for (int i = 0; i < fDrawTargets.count(); ++i) {
if (fDrawTargets[i]->drawBatches(&fFlushState)) {
flushed = true;
}
}
SkASSERT(fFlushState.nextDrawToken() == fFlushState.nextTokenToFlush());
for (int i = 0; i < fDrawTargets.count(); ++i) {
fDrawTargets[i]->reset();
#ifdef ENABLE_MDB
fDrawTargets[i]->unref();
#endif
}
#ifndef ENABLE_MDB
// When MDB is disabled we keep reusing the same drawTarget
if (fDrawTargets.count()) {
SkASSERT(fDrawTargets.count() == 1);
// Clear out this flag so the topological sort's SkTTopoSort_CheckAllUnmarked check
// won't bark
fDrawTargets[0]->resetFlag(GrDrawTarget::kWasOutput_Flag);
}
#else
fDrawTargets.reset();
#endif
fFlushState.reset();
// We always have to notify the cache when it requested a flush so it can reset its state.
if (flushed || type == GrResourceCache::FlushType::kCacheRequested) {
fContext->getResourceCache()->notifyFlushOccurred(type);
}
fFlushing = false;
}
void GrDrawingManager::prepareSurfaceForExternalIO(GrSurface* surface) {
if (this->wasAbandoned()) {
return;
}
SkASSERT(surface);
SkASSERT(surface->getContext() == fContext);
if (surface->surfacePriv().hasPendingIO()) {
this->flush();
}
GrRenderTarget* rt = surface->asRenderTarget();
if (fContext->getGpu() && rt) {
fContext->getGpu()->resolveRenderTarget(rt);
}
}
GrDrawTarget* GrDrawingManager::newDrawTarget(GrRenderTarget* rt) {
SkASSERT(fContext);
#ifndef ENABLE_MDB
// When MDB is disabled we always just return the single drawTarget
if (fDrawTargets.count()) {
SkASSERT(fDrawTargets.count() == 1);
// In the non-MDB-world the same drawTarget gets reused for multiple render targets.
// Update this pointer so all the asserts are happy
rt->setLastDrawTarget(fDrawTargets[0]);
// DrawingManager gets the creation ref - this ref is for the caller
return SkRef(fDrawTargets[0]);
}
#endif
GrDrawTarget* dt = new GrDrawTarget(rt, fContext->getGpu(), fContext->resourceProvider(),
fContext->getAuditTrail(), fOptionsForDrawTargets);
*fDrawTargets.append() = dt;
// DrawingManager gets the creation ref - this ref is for the caller
return SkRef(dt);
}
GrAtlasTextContext* GrDrawingManager::getAtlasTextContext() {
if (!fAtlasTextContext) {
fAtlasTextContext.reset(GrAtlasTextContext::Create());
}
return fAtlasTextContext.get();
}
/*
* This method finds a path renderer that can draw the specified path on
* the provided target.
* Due to its expense, the software path renderer has split out so it can
* can be individually allowed/disallowed via the "allowSW" boolean.
*/
GrPathRenderer* GrDrawingManager::getPathRenderer(const GrPathRenderer::CanDrawPathArgs& args,
bool allowSW,
GrPathRendererChain::DrawType drawType,
GrPathRenderer::StencilSupport* stencilSupport) {
if (!fPathRendererChain) {
fPathRendererChain = new GrPathRendererChain(fContext, fOptionsForPathRendererChain);
}
GrPathRenderer* pr = fPathRendererChain->getPathRenderer(args, drawType, stencilSupport);
if (!pr && allowSW) {
if (!fSoftwarePathRenderer) {
fSoftwarePathRenderer =
new GrSoftwarePathRenderer(fContext->textureProvider(),
fOptionsForPathRendererChain.fAllowPathMaskCaching);
}
pr = fSoftwarePathRenderer;
}
return pr;
}
sk_sp<GrDrawContext> GrDrawingManager::makeDrawContext(sk_sp<GrRenderTarget> rt,
sk_sp<SkColorSpace> colorSpace,
const SkSurfaceProps* surfaceProps) {
if (this->wasAbandoned()) {
return nullptr;
}
// SkSurface catches bad color space usage at creation. This check handles anything that slips
// by, including internal usage. We allow a null color space here, for read/write pixels and
// other special code paths. If a color space is provided, though, enforce all other rules.
if (colorSpace && !SkSurface_Gpu::Valid(fContext, rt->config(), colorSpace.get())) {
SkDEBUGFAIL("Invalid config and colorspace combination");
return nullptr;
}
bool useDIF = false;
if (surfaceProps) {
useDIF = surfaceProps->isUseDeviceIndependentFonts();
}
if (useDIF && fContext->caps()->shaderCaps()->pathRenderingSupport() &&
rt->isStencilBufferMultisampled()) {
GrStencilAttachment* sb = fContext->resourceProvider()->attachStencilAttachment(rt.get());
if (sb) {
return sk_sp<GrDrawContext>(new GrPathRenderingDrawContext(
fContext, this, std::move(rt),
std::move(colorSpace), surfaceProps,
fContext->getAuditTrail(), fSingleOwner));
}
}
return sk_sp<GrDrawContext>(new GrDrawContext(fContext, this, std::move(rt),
std::move(colorSpace), surfaceProps,
fContext->getAuditTrail(),
fSingleOwner));
}
<|endoftext|>
|
<commit_before>#include "../../base/SRC_FIRST.hpp"
#include "../../testing/testing.hpp"
#include "../../platform/platform.hpp"
#include "../../map/feature_vec_model.hpp"
#include "../../indexer/data_header.hpp"
#include "../../indexer/scales.hpp"
#include "../../indexer/feature_visibility.hpp"
#include "../../indexer/feature_processor.hpp"
#include "../../indexer/classificator.hpp"
#include "../../geometry/rect_intersect.hpp"
#include "../../base/logging.hpp"
#include "../../std/string.hpp"
#include "../../std/algorithm.hpp"
#include "../../std/iostream.hpp"
#include "../../base/start_mem_debug.hpp"
typedef vector<pair<FeatureType, string> > feature_cont_t;
class AccumulatorBase
{
mutable string m_dbgString;
feature_cont_t & m_cont;
protected:
int m_scale;
bool is_drawable(FeatureType const & f) const
{
m_dbgString = f.DebugString(m_scale);
CHECK(m_dbgString == f.DebugString(m_scale), ());
// Feature that hasn't any geometry for m_scale returns empty DebugString().
return (!f.IsEmptyGeometry(m_scale) && feature::IsDrawableForIndex(f, m_scale));
}
void add(FeatureType const & f) const
{
m_cont.push_back(make_pair(f, m_dbgString));
}
public:
AccumulatorBase(m2::RectD const & r, feature_cont_t & cont)
: m_cont(cont)
{
m_scale = scales::GetScaleLevel(r);
}
void operator() (FeatureType const & f) const
{
if (is_drawable(f))
add(f);
}
};
class IntersectCheck
{
m2::RectD m_rect;
m2::PointD m_prev;
bool m_isPrev, m_intersect;
public:
IntersectCheck(m2::RectD const & r)
: m_rect(r), m_isPrev(false), m_intersect(false)
{
}
void operator() (CoordPointT const & p)
{
if (m_intersect) return;
m2::PointD pt(p.first, p.second);
if (m_isPrev)
{
m2::PointD d1 = m_prev;
m2::PointD d2 = pt;
m_intersect = m2::Intersect(m_rect, d1, d2);
}
else
m_isPrev = true;
m_prev = pt;
}
bool IsIntersect() const { return m_intersect; }
};
class AccumulatorEtalon : public AccumulatorBase
{
typedef AccumulatorBase base_type;
m2::RectD m_rect;
bool is_intersect(FeatureType const & f) const
{
IntersectCheck check(m_rect);
f.ForEachPointRef(check, m_scale);
return check.IsIntersect();
}
public:
AccumulatorEtalon(m2::RectD const & r, feature_cont_t & cont)
: base_type(r, cont), m_rect(r)
{
}
void operator() (FeatureType const & f, uint64_t /*offset*/) const
{
if (is_drawable(f) && is_intersect(f))
add(f);
}
};
// invoke this comparator to ensure that "sort" and "compare_sequence" use equal criterion
struct compare_strings
{
int compare(string const & r1, string const & r2) const
{
if (r1 < r2)
return -1;
if (r2 < r1)
return 1;
return 0;
}
template <class T>
int compare(T const & r1, T const & r2) const
{
return compare(r1.second, r2.second);
}
template <class T>
bool operator() (T const & r1, T const & r2) const
{
return (compare(r1, r2) == -1);
}
};
template <class TAccumulator, class TSource>
void for_each_in_rect(TSource & src, feature_cont_t & cont, m2::RectD const & rect)
{
cont.clear();
TAccumulator acc(rect, cont);
src.ForEachFeature(rect, acc);
sort(cont.begin(), cont.end(), compare_strings());
}
class file_source_t
{
ModelReaderPtr m_file;
public:
file_source_t(ModelReaderPtr const & file) : m_file(file) {}
template <class ToDo>
void ForEachFeature(m2::RectD const & /*rect*/, ToDo toDo)
{
feature::ForEachFromDat(m_file, toDo);
}
};
/// "test" should contain all elements from etalon
template <class TCont, class TCompare>
bool compare_sequence(TCont const & etalon, TCont const & test, TCompare comp, size_t & errInd)
{
if (test.size() < etalon.size())
return false;
typedef typename TCont::const_iterator iter_t;
iter_t i1 = etalon.begin();
iter_t i2 = test.begin();
while (i1 != etalon.end() && i2 != test.end())
{
switch (comp.compare(*i1, *i2))
{
case 0:
++i1;
++i2;
break;
case -1:
{
errInd = distance(etalon.begin(), i1);
return false;
}
case 1:
++i2;
break;
}
}
return true;
}
namespace
{
class FindOffset
{
int m_level;
pair<FeatureType, string> const & m_test;
public:
FindOffset(int level, pair<FeatureType, string> const & test)
: m_level(level), m_test(test)
{}
void operator() (FeatureType const & f, uint64_t offset)
{
string const s = f.DebugString(m_level);
if (s == m_test.second)
{
cout << s << endl << "Feature offset = " << offset << endl;
cout << "Feature classificator types:\n";
FeatureType::GetTypesFn getTypes;
f.ForEachTypeRef(getTypes);
for (size_t i = 0; i < getTypes.m_size; ++i)
cout << classif().GetFullObjectName(getTypes.m_types[i]) << endl;
}
}
};
void RunTest(string const & file)
{
model::FeaturesFetcher src1;
src1.InitClassificator();
src1.AddMap(file);
feature::DataHeader mapInfo;
ModelReaderPtr reader = GetPlatform().GetReader(file);
mapInfo.Load(FilesContainerR(reader).GetReader(HEADER_FILE_TAG));
vector<m2::RectD> rects;
rects.push_back(mapInfo.GetBounds());
while (!rects.empty())
{
m2::RectD r = rects.back();
rects.pop_back();
feature_cont_t v1, v2;
for_each_in_rect<AccumulatorBase>(src1, v1, r);
file_source_t src2(reader);
for_each_in_rect<AccumulatorEtalon>(src2, v2, r);
int const level = scales::GetScaleLevel(r);
size_t const emptyInd = size_t(-1);
size_t errInd = emptyInd;
if (!compare_sequence(v2, v1, compare_strings(), errInd))
{
if (errInd != emptyInd)
src2.ForEachFeature(r, FindOffset(level, v2[errInd]));
TEST(false, ("Failed for rect: ", r, "; Scale level = ", level, ". Etalon size = ", v2.size(), ". Index size = ", v1.size()));
}
if (!v2.empty() && (level < scales::GetUpperScale()))
{
m2::RectD r1, r2;
r.DivideByGreaterSize(r1, r2);
rects.push_back(r1);
rects.push_back(r2);
}
}
}
void RunTestForChoice(string const & fName)
{
cout << "Run " << fName << "? (y/n)\n";
char c;
cin >> c;
if (c == 'y')
RunTest(fName + DATA_FILE_EXTENSION);
}
}
UNIT_TEST(IndexForEachTest)
{
RunTestForChoice("minsk-pass");
RunTestForChoice("london-center");
}
<commit_msg>Do not ask anything in unit-test - simple run.<commit_after>#include "../../base/SRC_FIRST.hpp"
#include "../../testing/testing.hpp"
#include "../../platform/platform.hpp"
#include "../../map/feature_vec_model.hpp"
#include "../../indexer/data_header.hpp"
#include "../../indexer/scales.hpp"
#include "../../indexer/feature_visibility.hpp"
#include "../../indexer/feature_processor.hpp"
#include "../../indexer/classificator.hpp"
#include "../../geometry/rect_intersect.hpp"
#include "../../base/logging.hpp"
#include "../../std/string.hpp"
#include "../../std/algorithm.hpp"
#include "../../std/iostream.hpp"
#include "../../base/start_mem_debug.hpp"
typedef vector<pair<FeatureType, string> > feature_cont_t;
class AccumulatorBase
{
mutable string m_dbgString;
feature_cont_t & m_cont;
protected:
int m_scale;
bool is_drawable(FeatureType const & f) const
{
m_dbgString = f.DebugString(m_scale);
CHECK(m_dbgString == f.DebugString(m_scale), ());
// Feature that hasn't any geometry for m_scale returns empty DebugString().
return (!f.IsEmptyGeometry(m_scale) && feature::IsDrawableForIndex(f, m_scale));
}
void add(FeatureType const & f) const
{
m_cont.push_back(make_pair(f, m_dbgString));
}
public:
AccumulatorBase(m2::RectD const & r, feature_cont_t & cont)
: m_cont(cont)
{
m_scale = scales::GetScaleLevel(r);
}
void operator() (FeatureType const & f) const
{
if (is_drawable(f))
add(f);
}
};
class IntersectCheck
{
m2::RectD m_rect;
m2::PointD m_prev;
bool m_isPrev, m_intersect;
public:
IntersectCheck(m2::RectD const & r)
: m_rect(r), m_isPrev(false), m_intersect(false)
{
}
void operator() (CoordPointT const & p)
{
if (m_intersect) return;
m2::PointD pt(p.first, p.second);
if (m_isPrev)
{
m2::PointD d1 = m_prev;
m2::PointD d2 = pt;
m_intersect = m2::Intersect(m_rect, d1, d2);
}
else
m_isPrev = true;
m_prev = pt;
}
bool IsIntersect() const { return m_intersect; }
};
class AccumulatorEtalon : public AccumulatorBase
{
typedef AccumulatorBase base_type;
m2::RectD m_rect;
bool is_intersect(FeatureType const & f) const
{
IntersectCheck check(m_rect);
f.ForEachPointRef(check, m_scale);
return check.IsIntersect();
}
public:
AccumulatorEtalon(m2::RectD const & r, feature_cont_t & cont)
: base_type(r, cont), m_rect(r)
{
}
void operator() (FeatureType const & f, uint64_t /*offset*/) const
{
if (is_drawable(f) && is_intersect(f))
add(f);
}
};
// invoke this comparator to ensure that "sort" and "compare_sequence" use equal criterion
struct compare_strings
{
int compare(string const & r1, string const & r2) const
{
if (r1 < r2)
return -1;
if (r2 < r1)
return 1;
return 0;
}
template <class T>
int compare(T const & r1, T const & r2) const
{
return compare(r1.second, r2.second);
}
template <class T>
bool operator() (T const & r1, T const & r2) const
{
return (compare(r1, r2) == -1);
}
};
template <class TAccumulator, class TSource>
void for_each_in_rect(TSource & src, feature_cont_t & cont, m2::RectD const & rect)
{
cont.clear();
TAccumulator acc(rect, cont);
src.ForEachFeature(rect, acc);
sort(cont.begin(), cont.end(), compare_strings());
}
class file_source_t
{
ModelReaderPtr m_file;
public:
file_source_t(ModelReaderPtr const & file) : m_file(file) {}
template <class ToDo>
void ForEachFeature(m2::RectD const & /*rect*/, ToDo toDo)
{
feature::ForEachFromDat(m_file, toDo);
}
};
/// "test" should contain all elements from etalon
template <class TCont, class TCompare>
bool compare_sequence(TCont const & etalon, TCont const & test, TCompare comp, size_t & errInd)
{
if (test.size() < etalon.size())
return false;
typedef typename TCont::const_iterator iter_t;
iter_t i1 = etalon.begin();
iter_t i2 = test.begin();
while (i1 != etalon.end() && i2 != test.end())
{
switch (comp.compare(*i1, *i2))
{
case 0:
++i1;
++i2;
break;
case -1:
{
errInd = distance(etalon.begin(), i1);
return false;
}
case 1:
++i2;
break;
}
}
return true;
}
namespace
{
class FindOffset
{
int m_level;
pair<FeatureType, string> const & m_test;
public:
FindOffset(int level, pair<FeatureType, string> const & test)
: m_level(level), m_test(test)
{}
void operator() (FeatureType const & f, uint64_t offset)
{
string const s = f.DebugString(m_level);
if (s == m_test.second)
{
cout << s << endl << "Feature offset = " << offset << endl;
cout << "Feature classificator types:\n";
FeatureType::GetTypesFn getTypes;
f.ForEachTypeRef(getTypes);
for (size_t i = 0; i < getTypes.m_size; ++i)
cout << classif().GetFullObjectName(getTypes.m_types[i]) << endl;
}
}
};
void RunTest(string const & file)
{
model::FeaturesFetcher src1;
src1.InitClassificator();
src1.AddMap(file);
feature::DataHeader mapInfo;
ModelReaderPtr reader = GetPlatform().GetReader(file);
mapInfo.Load(FilesContainerR(reader).GetReader(HEADER_FILE_TAG));
vector<m2::RectD> rects;
rects.push_back(mapInfo.GetBounds());
while (!rects.empty())
{
m2::RectD r = rects.back();
rects.pop_back();
feature_cont_t v1, v2;
for_each_in_rect<AccumulatorBase>(src1, v1, r);
file_source_t src2(reader);
for_each_in_rect<AccumulatorEtalon>(src2, v2, r);
int const level = scales::GetScaleLevel(r);
size_t const emptyInd = size_t(-1);
size_t errInd = emptyInd;
if (!compare_sequence(v2, v1, compare_strings(), errInd))
{
if (errInd != emptyInd)
src2.ForEachFeature(r, FindOffset(level, v2[errInd]));
TEST(false, ("Failed for rect: ", r, "; Scale level = ", level, ". Etalon size = ", v2.size(), ". Index size = ", v1.size()));
}
if (!v2.empty() && (level < scales::GetUpperScale()))
{
m2::RectD r1, r2;
r.DivideByGreaterSize(r1, r2);
rects.push_back(r1);
rects.push_back(r2);
}
}
}
void RunTestForChoice(string const & fName)
{
// cout << "Run " << fName << "? (y/n)\n";
// char c;
// cin >> c;
// if (c == 'y')
RunTest(fName + DATA_FILE_EXTENSION);
}
}
UNIT_TEST(IndexForEachTest)
{
RunTestForChoice("minsk-pass");
//RunTestForChoice("london-center");
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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 "base/base_paths.h"
#include "base/file_util.h"
#include "media/base/yuv_convert.h"
#include "media/base/yuv_row.h"
#include "testing/gtest/include/gtest/gtest.h"
// Reference images were created with the following steps
// ffmpeg -vframes 25 -i bali.mov -vcodec rawvideo -pix_fmt yuv420p -an
// bali.yv12.1280_720.yuv
// yuvhalf -yv12 -skip 24 bali.yv12.1280_720.yuv bali.yv12.640_360.yuv
// ffmpeg -vframes 25 -i bali.mov -vcodec rawvideo -pix_fmt yuv422p -an
// bali.yv16.1280_720.yuv
// yuvhalf -yv16 -skip 24 bali.yv16.1280_720.yuv bali.yv16.640_360.yuv
// Size of raw image.
// Size of raw image.
static const int kWidth = 640;
static const int kHeight = 360;
static const int kScaledWidth = 1024;
static const int kScaledHeight = 768;
static const int kBpp = 4;
// Surface sizes.
static const size_t kYUV12Size = kWidth * kHeight * 12 / 8;
static const size_t kYUV16Size = kWidth * kHeight * 16 / 8;
static const size_t kRGBSize = kWidth * kHeight * kBpp;
static const size_t kRGBSizeConverted = kWidth * kHeight * kBpp;
namespace {
// DJB2 hash
unsigned int hash(unsigned char *s, size_t len, unsigned int hash = 5381) {
while (len--)
hash = hash * 33 + *s++;
return hash;
}
}
// Set to 100 to time ConvertYUVToRGB32.
// This will take approximately 40 to 200 ms.
static const int kTestTimes = 1;
TEST(YUVConvertTest, YV12) {
// Allocate all surfaces.
scoped_array<uint8> yuv_bytes(new uint8[kYUV12Size]);
scoped_array<uint8> rgb_bytes(new uint8[kRGBSize]);
scoped_array<uint8> rgb_converted_bytes(new uint8[kRGBSizeConverted]);
// Read YUV reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv12.640_360.yuv"));
EXPECT_EQ(static_cast<int>(kYUV12Size),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes.get()),
static_cast<int>(kYUV12Size)));
for (int i = 0; i < kTestTimes; ++i) {
// Convert a frame of YUV to 32 bit ARGB.
media::ConvertYUVToRGB32(yuv_bytes.get(), // Y
yuv_bytes.get() + kWidth * kHeight, // U
yuv_bytes.get() + kWidth * kHeight * 5 / 4, // V
rgb_converted_bytes.get(), // RGB output
kWidth, kHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UVStride
kWidth * kBpp, // RGBStride
media::YV12);
}
unsigned int rgb_hash = hash(rgb_converted_bytes.get(), kRGBSizeConverted);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(2413171226u, rgb_hash);
#else
EXPECT_EQ(2936300063u, rgb_hash);
#endif
}
TEST(YUVConvertTest, YV16) {
// Allocate all surfaces.
scoped_array<uint8> yuv_bytes(new uint8[kYUV16Size]);
scoped_array<uint8> rgb_bytes(new uint8[kRGBSize]);
scoped_array<uint8> rgb_converted_bytes(new uint8[kRGBSizeConverted]);
// Read YV16 reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv16.640_360.yuv"));
EXPECT_EQ(static_cast<int>(kYUV16Size),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes.get()),
static_cast<int>(kYUV16Size)));
// Convert a frame of YUV to 32 bit ARGB.
media::ConvertYUVToRGB32(yuv_bytes.get(), // Y
yuv_bytes.get() + kWidth * kHeight, // U
yuv_bytes.get() + kWidth * kHeight * 3 / 2, // V
rgb_converted_bytes.get(), // RGB output
kWidth, kHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UVStride
kWidth * kBpp, // RGBStride
media::YV16);
unsigned int rgb_hash = hash(rgb_converted_bytes.get(), kRGBSizeConverted);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(4222342047u, rgb_hash);
#else
EXPECT_EQ(106869773u, rgb_hash);
#endif
}
TEST(YuvScaleTest, YV12) {
// Read YUV reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv12.640_360.yuv"));
const size_t size_of_yuv = kWidth * kHeight * 12 / 8; // 12 bpp.
uint8* yuv_bytes = new uint8[size_of_yuv];
EXPECT_EQ(static_cast<int>(size_of_yuv),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes),
static_cast<int>(size_of_yuv)));
// Scale a frame of YUV to 32 bit ARGB.
const size_t size_of_rgb_scaled = kScaledWidth * kScaledHeight * kBpp;
uint8* rgb_scaled_bytes = new uint8[size_of_rgb_scaled];
media::ScaleYUVToRGB32(yuv_bytes, // Y plane
yuv_bytes + kWidth * kHeight, // U plane
yuv_bytes + kWidth * kHeight * 5 / 4, // V plane
rgb_scaled_bytes, // Rgb output
kWidth, kHeight, // Dimensions
kScaledWidth, kScaledHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UvStride
kScaledWidth * kBpp, // RgbStride
media::YV12,
media::ROTATE_0);
unsigned int rgb_hash = hash(rgb_scaled_bytes, size_of_rgb_scaled);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(4259656254u, rgb_hash);
#else
EXPECT_EQ(197274901u, rgb_hash);
#endif
}
TEST(YuvScaleTest, YV16) {
// Read YV16 reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv16.640_360.yuv"));
const size_t size_of_yuv = kWidth * kHeight * 16 / 8; // 16 bpp.
uint8* yuv_bytes = new uint8[size_of_yuv];
EXPECT_EQ(static_cast<int>(size_of_yuv),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes),
static_cast<int>(size_of_yuv)));
// Scale a frame of YUV to 32 bit ARGB.
const size_t size_of_rgb_scaled = kScaledWidth * kScaledHeight * kBpp;
uint8* rgb_scaled_bytes = new uint8[size_of_rgb_scaled];
media::ScaleYUVToRGB32(yuv_bytes, // Y plane
yuv_bytes + kWidth * kHeight, // U plane
yuv_bytes + kWidth * kHeight * 3 / 2, // V plane
rgb_scaled_bytes, // Rgb output
kWidth, kHeight, // Dimensions
kScaledWidth, kScaledHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UvStride
kScaledWidth * kBpp, // RgbStride
media::YV16,
media::ROTATE_0);
unsigned int rgb_hash = hash(rgb_scaled_bytes, size_of_rgb_scaled);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(974965419u, rgb_hash);
#else
EXPECT_EQ(2946450771u, rgb_hash);
#endif
}
// This tests a known worst case YUV value, and for overflow.
TEST(YUVConvertTest, Clamp) {
// Allocate all surfaces.
scoped_array<uint8> yuv_bytes(new uint8[1]);
scoped_array<uint8> rgb_bytes(new uint8[1]);
scoped_array<uint8> rgb_converted_bytes(new uint8[1]);
// Values that failed previously in bug report.
unsigned char y = 255u;
unsigned char u = 255u;
unsigned char v = 19u;
// Prefill extra large destination buffer to test for overflow.
unsigned char rgb[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
// TODO(fbarchard): Make reference code mimic MMX exactly
// The code is fixed point and has slight rounding differences.
#if USE_MMX
unsigned char expected[8] = { 255, 255, 104, 255, 4, 5, 6, 7 };
#else
unsigned char expected[8] = { 255, 255, 105, 255, 4, 5, 6, 7 };
#endif
// Convert a frame of YUV to 32 bit ARGB.
media::ConvertYUVToRGB32(&y, // Y
&u, // U
&v, // V
&rgb[0], // RGB output
1, 1, // Dimensions
0, // YStride
0, // UVStride
0, // RGBStride
media::YV12);
int expected_test = memcmp(rgb, expected, sizeof(expected));
EXPECT_EQ(0, expected_test);
}
<commit_msg>Fix memory leask in media yuv_convert unit tests. Replace pointers init'd by plain new[] with scoped_array.<commit_after>// Copyright (c) 2009 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 "base/base_paths.h"
#include "base/file_util.h"
#include "media/base/yuv_convert.h"
#include "media/base/yuv_row.h"
#include "testing/gtest/include/gtest/gtest.h"
// Reference images were created with the following steps
// ffmpeg -vframes 25 -i bali.mov -vcodec rawvideo -pix_fmt yuv420p -an
// bali.yv12.1280_720.yuv
// yuvhalf -yv12 -skip 24 bali.yv12.1280_720.yuv bali.yv12.640_360.yuv
// ffmpeg -vframes 25 -i bali.mov -vcodec rawvideo -pix_fmt yuv422p -an
// bali.yv16.1280_720.yuv
// yuvhalf -yv16 -skip 24 bali.yv16.1280_720.yuv bali.yv16.640_360.yuv
// Size of raw image.
// Size of raw image.
static const int kWidth = 640;
static const int kHeight = 360;
static const int kScaledWidth = 1024;
static const int kScaledHeight = 768;
static const int kBpp = 4;
// Surface sizes.
static const size_t kYUV12Size = kWidth * kHeight * 12 / 8;
static const size_t kYUV16Size = kWidth * kHeight * 16 / 8;
static const size_t kRGBSize = kWidth * kHeight * kBpp;
static const size_t kRGBSizeConverted = kWidth * kHeight * kBpp;
namespace {
// DJB2 hash
unsigned int hash(unsigned char *s, size_t len, unsigned int hash = 5381) {
while (len--)
hash = hash * 33 + *s++;
return hash;
}
}
// Set to 100 to time ConvertYUVToRGB32.
// This will take approximately 40 to 200 ms.
static const int kTestTimes = 1;
TEST(YUVConvertTest, YV12) {
// Allocate all surfaces.
scoped_array<uint8> yuv_bytes(new uint8[kYUV12Size]);
scoped_array<uint8> rgb_bytes(new uint8[kRGBSize]);
scoped_array<uint8> rgb_converted_bytes(new uint8[kRGBSizeConverted]);
// Read YUV reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv12.640_360.yuv"));
EXPECT_EQ(static_cast<int>(kYUV12Size),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes.get()),
static_cast<int>(kYUV12Size)));
for (int i = 0; i < kTestTimes; ++i) {
// Convert a frame of YUV to 32 bit ARGB.
media::ConvertYUVToRGB32(yuv_bytes.get(), // Y
yuv_bytes.get() + kWidth * kHeight, // U
yuv_bytes.get() + kWidth * kHeight * 5 / 4, // V
rgb_converted_bytes.get(), // RGB output
kWidth, kHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UVStride
kWidth * kBpp, // RGBStride
media::YV12);
}
unsigned int rgb_hash = hash(rgb_converted_bytes.get(), kRGBSizeConverted);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(2413171226u, rgb_hash);
#else
EXPECT_EQ(2936300063u, rgb_hash);
#endif
}
TEST(YUVConvertTest, YV16) {
// Allocate all surfaces.
scoped_array<uint8> yuv_bytes(new uint8[kYUV16Size]);
scoped_array<uint8> rgb_bytes(new uint8[kRGBSize]);
scoped_array<uint8> rgb_converted_bytes(new uint8[kRGBSizeConverted]);
// Read YV16 reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv16.640_360.yuv"));
EXPECT_EQ(static_cast<int>(kYUV16Size),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes.get()),
static_cast<int>(kYUV16Size)));
// Convert a frame of YUV to 32 bit ARGB.
media::ConvertYUVToRGB32(yuv_bytes.get(), // Y
yuv_bytes.get() + kWidth * kHeight, // U
yuv_bytes.get() + kWidth * kHeight * 3 / 2, // V
rgb_converted_bytes.get(), // RGB output
kWidth, kHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UVStride
kWidth * kBpp, // RGBStride
media::YV16);
unsigned int rgb_hash = hash(rgb_converted_bytes.get(), kRGBSizeConverted);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(4222342047u, rgb_hash);
#else
EXPECT_EQ(106869773u, rgb_hash);
#endif
}
TEST(YuvScaleTest, YV12) {
// Read YUV reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv12.640_360.yuv"));
const size_t size_of_yuv = kWidth * kHeight * 12 / 8; // 12 bpp.
scoped_array<uint8> yuv_bytes(new uint8[size_of_yuv]);
EXPECT_EQ(static_cast<int>(size_of_yuv),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes.get()),
static_cast<int>(size_of_yuv)));
// Scale a frame of YUV to 32 bit ARGB.
const size_t size_of_rgb_scaled = kScaledWidth * kScaledHeight * kBpp;
scoped_array<uint8> rgb_scaled_bytes(new uint8[size_of_rgb_scaled]);
media::ScaleYUVToRGB32(yuv_bytes.get(), // Y
yuv_bytes.get() + kWidth * kHeight, // U
yuv_bytes.get() + kWidth * kHeight * 5 / 4, // V
rgb_scaled_bytes.get(), // Rgb output
kWidth, kHeight, // Dimensions
kScaledWidth, kScaledHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UvStride
kScaledWidth * kBpp, // RgbStride
media::YV12,
media::ROTATE_0);
unsigned int rgb_hash = hash(rgb_scaled_bytes.get(), size_of_rgb_scaled);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(4259656254u, rgb_hash);
#else
EXPECT_EQ(197274901u, rgb_hash);
#endif
}
TEST(YuvScaleTest, YV16) {
// Read YV16 reference data from file.
FilePath yuv_url;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &yuv_url));
yuv_url = yuv_url.Append(FILE_PATH_LITERAL("media"))
.Append(FILE_PATH_LITERAL("test"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("bali.yv16.640_360.yuv"));
const size_t size_of_yuv = kWidth * kHeight * 16 / 8; // 16 bpp.
scoped_array<uint8> yuv_bytes(new uint8[size_of_yuv]);
EXPECT_EQ(static_cast<int>(size_of_yuv),
file_util::ReadFile(yuv_url,
reinterpret_cast<char*>(yuv_bytes.get()),
static_cast<int>(size_of_yuv)));
// Scale a frame of YUV to 32 bit ARGB.
const size_t size_of_rgb_scaled = kScaledWidth * kScaledHeight * kBpp;
scoped_array<uint8> rgb_scaled_bytes(new uint8[size_of_rgb_scaled]);
media::ScaleYUVToRGB32(yuv_bytes.get(), // Y
yuv_bytes.get() + kWidth * kHeight, // U
yuv_bytes.get() + kWidth * kHeight * 3 / 2, // V
rgb_scaled_bytes.get(), // Rgb output
kWidth, kHeight, // Dimensions
kScaledWidth, kScaledHeight, // Dimensions
kWidth, // YStride
kWidth / 2, // UvStride
kScaledWidth * kBpp, // RgbStride
media::YV16,
media::ROTATE_0);
unsigned int rgb_hash = hash(rgb_scaled_bytes.get(), size_of_rgb_scaled);
// To get this hash value, run once and examine the following EXPECT_EQ.
// Then plug new hash value into EXPECT_EQ statements.
// TODO(fbarchard): Make reference code mimic MMX exactly
#if USE_MMX
EXPECT_EQ(974965419u, rgb_hash);
#else
EXPECT_EQ(2946450771u, rgb_hash);
#endif
}
// This tests a known worst case YUV value, and for overflow.
TEST(YUVConvertTest, Clamp) {
// Allocate all surfaces.
scoped_array<uint8> yuv_bytes(new uint8[1]);
scoped_array<uint8> rgb_bytes(new uint8[1]);
scoped_array<uint8> rgb_converted_bytes(new uint8[1]);
// Values that failed previously in bug report.
unsigned char y = 255u;
unsigned char u = 255u;
unsigned char v = 19u;
// Prefill extra large destination buffer to test for overflow.
unsigned char rgb[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
// TODO(fbarchard): Make reference code mimic MMX exactly
// The code is fixed point and has slight rounding differences.
#if USE_MMX
unsigned char expected[8] = { 255, 255, 104, 255, 4, 5, 6, 7 };
#else
unsigned char expected[8] = { 255, 255, 105, 255, 4, 5, 6, 7 };
#endif
// Convert a frame of YUV to 32 bit ARGB.
media::ConvertYUVToRGB32(&y, // Y
&u, // U
&v, // V
&rgb[0], // RGB output
1, 1, // Dimensions
0, // YStride
0, // UVStride
0, // RGBStride
media::YV12);
int expected_test = memcmp(rgb, expected, sizeof(expected));
EXPECT_EQ(0, expected_test);
}
<|endoftext|>
|
<commit_before>#include<bits/stdc++.h>
#define token std::pair<std::string, std::string> // token type, token content
// The sg compiler
// Pascal Sommer, November 2016
// requires GCC >= 4.4
// some utility functions
bool is_whitespace(char c){
return isspace(c);
}
bool is_not_newline(char c){
return (c!='\n' && c!='\r');
}
bool is_alphanumeric(char c){
return isalnum(c);
}
template <typename T>
void vector_append(std::vector<T> &v1, const std::vector<T> &v2){
v1.insert(v1.end(), v2.begin(), v2.end());
}
class Scanner{
// The Scanner class doesn't do the lexing, but is the interface for the
// actual lexer to the file. It keeps track of the line and character
// number, and lets the lexer fetch words or lines, and provides a simple
// form of backtracking.
std::string buffer;
std::ifstream infile;
std::string file_path;
int line_number;
int line_character_number;
bool fill_buffer(int len){
while (buffer.size() < len){
if(infile.eof()){
return false;
}
char next;
infile.get(next);
buffer+=next;
}
return true;
}
// return substring from buffer and then remove it. If len is
// greater than the buffer length, the entire buffer will be
// returned quietly. len -1 will return the entire buffer as
// well.
// this function updates the line and character number, thus
// every function that clears something from the buffer must
// do such through this function.
std::string clear_from_buffer(int len){
if(len == -1){
len = buffer.size();
}
len = std::min(len, (int)buffer.size());
std::string out = buffer.substr(0, len);
for(auto c:out){
if(is_not_newline(c)){
++line_character_number;
}else{
line_character_number = 0;
++line_number;
}
}
buffer.erase(buffer.begin(), buffer.begin()+len);
return out;
}
// consumes the input while the next character fulfills (*cond).
// usually leaves a single character in the buffer, unless eof
// was reached.
std::string get_while(bool (*cond)(char)){
for(int i = 0; i < buffer.size(); ++i){
if( ! (*cond)(buffer[i])){
return clear_from_buffer(i);
}
}
std::string out = clear_from_buffer(-1);
for(;;){
if( ! fill_buffer(1)) break;
if( ! (*cond)(buffer[1])) break;
out += clear_from_buffer(1);
}
return out;
}
std::string peek_str(int len){
if( ! fill_buffer(len)){
// return as much as possible if eof is reached
len = buffer.size();
}
std::string out = buffer.substr(0, len);
return out;
}
std::string get_str(int len){
std::string out = peek_str(len);
// this might be shorter than the original len
len = out.size();
clear_from_buffer(len);
return out;
}
void skip_whitespace(){
get_while(&is_whitespace);
}
public:
bool eof();
bool match_string(std::string pattern);
std::string get_alphanum();
std::string get_rest_of_line();
std::string get_position();
Scanner(std::string file_path): file_path(file_path)
{
infile.open(file_path, std::ifstream::in);
line_number = 1;
line_character_number = 0;
buffer = "";
}
};
// is eof reached?
bool Scanner::eof(){
return buffer.empty() && infile.eof();
}
// if string matches, consume input, otherwise don't
// consume anything. Skips any leading whitespace.
bool Scanner::match_string(std::string pattern){
std::string in = peek_str(pattern.size());
if(in.size() < pattern.size()){
return false;
}
if( in == pattern ){
get_str(pattern.size());
return true;
}else{
return false;
}
}
// consumes word unless EOF. Returns without leading
// or trailing whitespace.
std::string Scanner::get_alphanum(){
return get_while(&is_alphanumeric);
}
// get until newline, and consume input.
std::string Scanner::get_rest_of_line(){
return get_while(&is_not_newline);
}
// return the file path, line number and character number
std::string Scanner::get_position(){
return file_path + ", " +
std::to_string(line_number) + ":" +
std::to_string(line_character_number);
}
class Lexer{
// The Lexer class uses the Scanner class as an interface to the file. It
// has a single public method (besides the constructor) that returns a
// vector of tokens.
Scanner* scanner;
const std::vector<token> v_empty;
std::vector<token> v_error;
void print_error(std::string message){
std::cerr<<"ERROR in " << scanner->get_position() << ": " << message <<"\n";
}
// the lex_<type> functions return the lexed tokens if
// the type matches, otherwise return an empty vector
// because c++ is lacking a maybe monad.
std::vector<token> lex_node(){
if( ! (scanner->match_string("node") || scanner->match_string("n")) ){
return v_empty;
}
std::string name = scanner->get_alphanum();
std::vector<token> out = {{"node", name}};
if(scanner->match_string(":")){
// bash node
std::string command = scanner->get_rest_of_line();
if(command == ""){
print_error("Expected bash command");
return v_error;
}
out.push_back({"bash_command", command});
}else if(scanner->match_string("/")){
// io node
std::string io_type = scanner->get_alphanum();
if(io_type != "infile" && io_type != "outfile"){
print_error("Expected type of io node ('infile' or 'outfile')");
return v_error;
}
std::string number = scanner->get_alphanum();
if(number == ""){
print_error("Expected number of file");
return v_error;
}
out.push_back({io_type, number});
}else if(scanner->match_string("-")){
// instance node
std::string name = scanner->get_alphanum();
if(name == ""){
print_error("Expected group name");
return v_error;
}
out.push_back({"instance", name});
}else{
print_error("Expected ':', '/' or '-'");
return v_error;
}
return out;
}
std::vector<token> lex_modifier(){
std::vector<token> out;
if(scanner->match_string(".")){
std::string mod = scanner->get_alphanum();
if(mod == ""){
print_error("Expected node modifier");
return v_error;
}
out.push_back({"node_modifier", mod});
}
return out;
}
std::vector<token> lex_mod_name(std::string token_name){
std::vector<token> out;
std::string name = scanner->get_alphanum();
if(name == ""){
print_error("Expected name of node");
return v_error;
}
out.push_back({token_name, name});
// modifier of the source
std::vector<token> mod = lex_modifier();
if(mod == v_error){
return v_error;
}else if(! mod.empty()){
out.push_back(mod[0]);
}
return out;
}
std::vector<token> lex_edge(){
if( ! (scanner->match_string("edge") || scanner->match_string("e")) ){
return v_empty;
}
std::vector<token> out = {{"edge", ""}};
// source of the edge
std::vector<token> name1 = lex_mod_name("edge_source");
if(name1 == v_error){
return v_error;
}
for(auto p:name1){
out.push_back(p);
}
// destination of the edge
std::vector<token> name2 = lex_mod_name("edge_destination");
if(name2 == v_error){
return v_error;
}
for(auto p:name2){
out.push_back(p);
}
return out;
}
std::vector<token> lex_group_header(){
if( ! (scanner->match_string("group") || scanner->match_string("g")) ){
return v_empty;
}
std::string name = scanner->get_alphanum();
if(name == ""){
print_error("Expected group name");
return v_error;
}
if( ! scanner->match_string("{")){
print_error("Expected '{'");
return v_error;
}
std::vector<token> out = {{"group", name}};
return out;
}
std::vector<token> lex_group_close(){
if( ! scanner->match_string("}")){
return v_empty;
}
std::vector<token> out = {{"group_close", "}"}};
return out;
}
std::vector<token> lex_comment(){
if ( ! scanner->match_string("#")){
return v_empty;
}
// inline populate vector, requires GCC >= 4.4
std::vector<token> out = {{"comment", scanner->get_rest_of_line()}};
return out;
}
public:
std::string file_path;
std::vector<token> lex(){
std::vector<token> entire_program;
while( ! scanner->eof() ){
std::vector<token> output;
output = lex_comment(); // try matching comment
if(output == v_empty){
output = lex_node(); // try matching node
}
if(output == v_empty){
output = lex_edge(); // try matching edge
}
if(output == v_empty){
output = lex_group_header(); // try matching group header
}
if(output == v_empty){
output = lex_group_close(); // try matching group end
}
if(output == v_empty){
// nothing could be matched, print error.
print_error("Expected group, edge, node or comment");
output = v_error;
}
if(output == v_error){
// an error has occurred while lexing.
// Stop lexing any further.
break;
}
vector_append(entire_program, output);
}
return entire_program;
}
Lexer(std::string file_path): file_path(file_path){
scanner = new Scanner(file_path);
v_error.push_back({"ERROR", "ERROR"});
}
};
int main(){
Lexer l ("ipLookup.sg");
auto result = l.lex();
for(auto t:result){
std::cout<< t.first << "\t" << t.second<<"\n";
}
}
<commit_msg>Bugfix EOF and whitespace skipping<commit_after>#include<bits/stdc++.h>
#define token std::pair<std::string, std::string> // token type, token content
// The sg compiler
// Pascal Sommer, November 2016
// requires GCC >= 4.4
// some utility functions
bool is_whitespace(char c){
return isspace(c);
}
bool is_not_newline(char c){
return (c!='\n' && c!='\r');
}
bool is_alphanumeric(char c){
return isalnum(c);
}
template <typename T>
void vector_append(std::vector<T> &v1, const std::vector<T> &v2){
v1.insert(v1.end(), v2.begin(), v2.end());
}
class Scanner{
// The Scanner class doesn't do the lexing, but is the interface for the
// actual lexer to the file. It keeps track of the line and character
// number, and lets the lexer fetch words or lines, and provides a simple
// form of backtracking.
std::string buffer;
std::ifstream infile;
std::string file_path;
// has filestream reached eof? if this is true, buffer could still be non-
// empty.
bool eof;
int line_number;
int line_character_number;
bool fill_buffer(int len){
while (buffer.size() < len){
if(infile.eof()){
return false;
}
char next;
if( !infile.get(next)){
eof = true;
return false;
}else{
buffer+=next;
}
}
return true;
}
// return substring from buffer and then remove it. If len is
// greater than the buffer length, the entire buffer will be
// returned quietly. len -1 will return the entire buffer as
// well.
// this function updates the line and character number, thus
// every function that clears something from the buffer must
// do such through this function.
std::string clear_from_buffer(int len){
if(len == -1){
len = buffer.size();
}
len = std::min(len, (int)buffer.size());
std::string out = buffer.substr(0, len);
for(auto c:out){
if(is_not_newline(c)){
++line_character_number;
}else{
line_character_number = 0;
++line_number;
}
}
buffer.erase(buffer.begin(), buffer.begin()+len);
return out;
}
// consumes the input while the next character fulfills (*cond).
// usually leaves a single character in the buffer, unless eof
// was reached.
std::string get_while(bool (*cond)(char)){
for(int i = 0; i < buffer.size(); ++i){
if( ! (*cond)(buffer[i])){
return clear_from_buffer(i);
}
}
std::string out = clear_from_buffer(-1);
for(;;){
if( ! fill_buffer(1)) break;
if( ! (*cond)(buffer[0])) break;
out += clear_from_buffer(1);
}
return out;
}
std::string peek_str(int len){
if( ! fill_buffer(len)){
// return as much as possible if eof is reached
len = buffer.size();
}
std::string out = buffer.substr(0, len);
return out;
}
std::string get_str(int len){
std::string out = peek_str(len);
// this might be shorter than the original len
len = out.size();
clear_from_buffer(len);
return out;
}
public:
bool reached_eof();
bool match_string(std::string pattern);
void skip_whitespace();
std::string get_alphanum();
std::string get_rest_of_line();
std::string get_position();
Scanner(std::string file_path): file_path(file_path)
{
infile.open(file_path, std::ifstream::in);
line_number = 1;
line_character_number = 0;
buffer = "";
eof = false;
}
};
void Scanner::skip_whitespace(){
get_while(&is_whitespace);
}
// is eof reached?
bool Scanner::reached_eof(){
return buffer.empty() && eof;
}
// if string matches, consume input, otherwise don't
// consume anything. Skips any leading whitespace.
bool Scanner::match_string(std::string pattern){
skip_whitespace();
std::string in = peek_str(pattern.size());
if(in.size() < pattern.size()){
return false;
}
if( in == pattern ){
// if string matches, consume it.
get_str(pattern.size());
return true;
}else{
return false;
}
}
// consumes word unless EOF. Returns without leading
// or trailing whitespace.
std::string Scanner::get_alphanum(){
skip_whitespace();
return get_while(&is_alphanumeric);
}
// get until newline, and consume input.
std::string Scanner::get_rest_of_line(){
return get_while(&is_not_newline);
}
// return the file path, line number and character number
std::string Scanner::get_position(){
return file_path + ", " +
std::to_string(line_number) + ":" +
std::to_string(line_character_number);
}
class Lexer{
// The Lexer class uses the Scanner class as an interface to the file. It
// has a single public method (besides the constructor) that returns a
// vector of tokens.
Scanner* scanner;
const std::vector<token> v_empty;
std::vector<token> v_error;
void print_error(std::string message){
std::cerr<<"ERROR in " << scanner->get_position() << ": " << message <<"\n";
}
// the lex_<type> functions return the lexed tokens if
// the type matches, otherwise return an empty vector
// because c++ is lacking a maybe monad.
std::vector<token> lex_node(){
if( ! (scanner->match_string("node") || scanner->match_string("n")) ){
return v_empty;
}
std::string name = scanner->get_alphanum();
std::vector<token> out = {{"node", name}};
if(scanner->match_string(":")){
// bash node
std::string command = scanner->get_rest_of_line();
if(command == ""){
print_error("Expected bash command");
return v_error;
}
out.push_back({"bash_command", command});
}else if(scanner->match_string("/")){
// io node
std::string io_type = scanner->get_alphanum();
if(io_type != "infile" && io_type != "outfile"){
print_error("Expected type of io node ('infile' or 'outfile')");
return v_error;
}
std::string number = scanner->get_alphanum();
if(number == ""){
print_error("Expected number of file");
return v_error;
}
out.push_back({io_type, number});
}else if(scanner->match_string("-")){
// instance node
std::string name = scanner->get_alphanum();
if(name == ""){
print_error("Expected group name");
return v_error;
}
out.push_back({"instance", name});
}else{
print_error("Expected ':', '/' or '-'");
return v_error;
}
return out;
}
std::vector<token> lex_modifier(){
std::vector<token> out;
if(scanner->match_string(".")){
std::string mod = scanner->get_alphanum();
if(mod == ""){
print_error("Expected node modifier");
return v_error;
}
out.push_back({"node_modifier", mod});
}
return out;
}
std::vector<token> lex_mod_name(std::string token_name){
std::vector<token> out;
std::string name = scanner->get_alphanum();
if(name == ""){
print_error("Expected name of node");
return v_error;
}
out.push_back({token_name, name});
// modifier of the source
std::vector<token> mod = lex_modifier();
if(mod == v_error){
return v_error;
}else if(! mod.empty()){
out.push_back(mod[0]);
}
return out;
}
std::vector<token> lex_edge(){
if( ! (scanner->match_string("edge") || scanner->match_string("e")) ){
return v_empty;
}
std::vector<token> out = {{"edge", ""}};
// source of the edge
std::vector<token> name1 = lex_mod_name("edge_source");
if(name1 == v_error){
return v_error;
}
for(auto p:name1){
out.push_back(p);
}
// destination of the edge
std::vector<token> name2 = lex_mod_name("edge_destination");
if(name2 == v_error){
return v_error;
}
for(auto p:name2){
out.push_back(p);
}
return out;
}
std::vector<token> lex_group_header(){
if( ! (scanner->match_string("group") || scanner->match_string("g")) ){
return v_empty;
}
std::string name = scanner->get_alphanum();
if(name == ""){
print_error("Expected group name");
return v_error;
}
if( ! scanner->match_string("{")){
print_error("Expected '{'");
return v_error;
}
std::vector<token> out = {{"group", name}};
return out;
}
std::vector<token> lex_group_close(){
if( ! scanner->match_string("}")){
return v_empty;
}
std::vector<token> out = {{"group_close", "}"}};
return out;
}
std::vector<token> lex_comment(){
if ( ! scanner->match_string("#")){
return v_empty;
}
// inline populate vector, requires GCC >= 4.4
std::vector<token> out = {{"comment", scanner->get_rest_of_line()}};
return out;
}
public:
std::string file_path;
std::vector<token> lex(){
std::vector<token> entire_program;
scanner->skip_whitespace();
while( ! scanner->reached_eof() ){
std::vector<token> output;
output = lex_comment(); // try matching comment
if(output == v_empty){
output = lex_node(); // try matching node
}
if(output == v_empty){
output = lex_edge(); // try matching edge
}
if(output == v_empty){
output = lex_group_header(); // try matching group header
}
if(output == v_empty){
output = lex_group_close(); // try matching group end
}
if(output == v_empty){
// nothing could be matched, print error.
print_error("Expected group, edge, node or comment");
output = v_error;
}
if(output == v_error){
// an error has occurred while lexing.
// Stop lexing any further.
break;
}
vector_append(entire_program, output);
scanner->skip_whitespace();
}
return entire_program;
}
Lexer(std::string file_path): file_path(file_path){
scanner = new Scanner(file_path);
v_error.push_back({"ERROR", "ERROR"});
}
};
int main(){
/*
std::ifstream f ("ipLookup.sg");
char c;
while(true){
std::cout<<f.get(c);
usleep(10000);
if (c == EOF){
std::cout<<"EOF " << EOF <<"\n";
}else{
std::cout<<c<<std::flush;
}
}
*/
Lexer l ("ipLookup.sg");
auto result = l.lex();
for(auto t:result){
std::cout<< t.first << "\t" << t.second<<"\n";
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2006-2012 Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Philippe Houdoin <philippe.houdoin@free.fr>
* Alexander von Gluck IV <kallisti5@unixzen.com>
*/
#include <driver_settings.h>
#include <image.h>
#include <kernel/image.h>
#include <system/safemode_defs.h>
#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <strings.h>
#include "GLDispatcher.h"
#include "GLRendererRoster.h"
#include <new>
#include <string.h>
extern "C" status_t _kern_get_safemode_option(const char* parameter,
char* buffer, size_t* _bufferSize);
GLRendererRoster::GLRendererRoster(BGLView* view, ulong options)
:
fNextID(0),
fView(view),
fOptions(options),
fSafeMode(false),
fABISubDirectory(NULL)
{
char parameter[32];
size_t parameterLength = sizeof(parameter);
if (_kern_get_safemode_option(B_SAFEMODE_SAFE_MODE,
parameter, ¶meterLength) == B_OK) {
if (!strcasecmp(parameter, "enabled") || !strcasecmp(parameter, "on")
|| !strcasecmp(parameter, "true") || !strcasecmp(parameter, "yes")
|| !strcasecmp(parameter, "enable") || !strcmp(parameter, "1"))
fSafeMode = true;
}
if (_kern_get_safemode_option(B_SAFEMODE_DISABLE_USER_ADD_ONS,
parameter, ¶meterLength) == B_OK) {
if (!strcasecmp(parameter, "enabled") || !strcasecmp(parameter, "on")
|| !strcasecmp(parameter, "true") || !strcasecmp(parameter, "yes")
|| !strcasecmp(parameter, "enable") || !strcmp(parameter, "1"))
fSafeMode = true;
}
// We might run in compatibility mode on a system with a different ABI. The
// renderers matching our ABI can usually be found in respective
// subdirectories of the opengl add-ons directories.
system_info info;
if (get_system_info(&info) == B_OK
&& (info.abi & B_HAIKU_ABI_MAJOR)
!= (B_HAIKU_ABI & B_HAIKU_ABI_MAJOR)) {
switch (B_HAIKU_ABI & B_HAIKU_ABI_MAJOR) {
case B_HAIKU_ABI_GCC_2:
fABISubDirectory = "gcc2";
break;
case B_HAIKU_ABI_GCC_4:
fABISubDirectory = "gcc4";
break;
}
}
AddDefaultPaths();
}
GLRendererRoster::~GLRendererRoster()
{
}
BGLRenderer*
GLRendererRoster::GetRenderer(int32 id)
{
RendererMap::const_iterator iterator = fRenderers.find(id);
if (iterator == fRenderers.end())
return NULL;
struct renderer_item item = iterator->second;
return item.renderer;
}
void
GLRendererRoster::AddDefaultPaths()
{
// add user directories first, so that they can override system renderers
const directory_which paths[] = {
B_USER_NONPACKAGED_ADDONS_DIRECTORY,
B_USER_ADDONS_DIRECTORY,
B_SYSTEM_ADDONS_DIRECTORY,
};
for (uint32 i = fSafeMode ? 4 : 0;
i < sizeof(paths) / sizeof(paths[0]); i++) {
BPath path;
status_t status = find_directory(paths[i], &path, true);
if (status == B_OK && path.Append("opengl") == B_OK)
AddPath(path.Path());
}
}
status_t
GLRendererRoster::AddPath(const char* path)
{
BDirectory directory(path);
status_t status = directory.InitCheck();
if (status < B_OK)
return status;
// if a subdirectory for our ABI exists, use that instead
if (fABISubDirectory != NULL) {
BEntry entry(&directory, fABISubDirectory);
if (entry.IsDirectory()) {
status = directory.SetTo(&entry);
if (status != B_OK)
return status;
}
}
node_ref nodeRef;
status = directory.GetNodeRef(&nodeRef);
if (status < B_OK)
return status;
int32 count = 0;
int32 files = 0;
entry_ref ref;
BEntry entry;
while (directory.GetNextRef(&ref) == B_OK) {
entry.SetTo(&ref);
if (entry.InitCheck() == B_OK && !entry.IsFile())
continue;
if (CreateRenderer(ref) == B_OK)
count++;
files++;
}
if (files != 0 && count == 0)
return B_BAD_VALUE;
return B_OK;
}
status_t
GLRendererRoster::AddRenderer(BGLRenderer* renderer,
image_id image, const entry_ref* ref, ino_t node)
{
renderer_item item;
item.renderer = renderer;
item.image = image;
item.node = node;
if (ref != NULL)
item.ref = *ref;
try {
fRenderers[fNextID] = item;
} catch (...) {
return B_NO_MEMORY;
}
renderer->fOwningRoster = this;
renderer->fID = fNextID++;
return B_OK;
}
status_t
GLRendererRoster::CreateRenderer(const entry_ref& ref)
{
BEntry entry(&ref);
node_ref nodeRef;
status_t status = entry.GetNodeRef(&nodeRef);
if (status < B_OK)
return status;
BPath path(&ref);
image_id image = load_add_on(path.Path());
if (image < B_OK)
return image;
BGLRenderer* (*instantiate_renderer)
(BGLView* view, ulong options, BGLDispatcher* dispatcher);
status = get_image_symbol(image, "instantiate_gl_renderer",
B_SYMBOL_TYPE_TEXT, (void**)&instantiate_renderer);
if (status == B_OK) {
BGLRenderer* renderer
= instantiate_renderer(fView, fOptions, new BGLDispatcher());
if (!renderer) {
unload_add_on(image);
return B_UNSUPPORTED;
}
if (AddRenderer(renderer, image, &ref, nodeRef.node) != B_OK) {
renderer->Release();
// this will delete the renderer
unload_add_on(image);
}
return B_OK;
}
unload_add_on(image);
return status;
}
<commit_msg>hgl: traverse add-on entries<commit_after>/*
* Copyright 2006-2012 Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Philippe Houdoin <philippe.houdoin@free.fr>
* Alexander von Gluck IV <kallisti5@unixzen.com>
*/
#include <driver_settings.h>
#include <image.h>
#include <kernel/image.h>
#include <system/safemode_defs.h>
#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <strings.h>
#include "GLDispatcher.h"
#include "GLRendererRoster.h"
#include <new>
#include <string.h>
extern "C" status_t _kern_get_safemode_option(const char* parameter,
char* buffer, size_t* _bufferSize);
GLRendererRoster::GLRendererRoster(BGLView* view, ulong options)
:
fNextID(0),
fView(view),
fOptions(options),
fSafeMode(false),
fABISubDirectory(NULL)
{
char parameter[32];
size_t parameterLength = sizeof(parameter);
if (_kern_get_safemode_option(B_SAFEMODE_SAFE_MODE,
parameter, ¶meterLength) == B_OK) {
if (!strcasecmp(parameter, "enabled") || !strcasecmp(parameter, "on")
|| !strcasecmp(parameter, "true") || !strcasecmp(parameter, "yes")
|| !strcasecmp(parameter, "enable") || !strcmp(parameter, "1"))
fSafeMode = true;
}
if (_kern_get_safemode_option(B_SAFEMODE_DISABLE_USER_ADD_ONS,
parameter, ¶meterLength) == B_OK) {
if (!strcasecmp(parameter, "enabled") || !strcasecmp(parameter, "on")
|| !strcasecmp(parameter, "true") || !strcasecmp(parameter, "yes")
|| !strcasecmp(parameter, "enable") || !strcmp(parameter, "1"))
fSafeMode = true;
}
// We might run in compatibility mode on a system with a different ABI. The
// renderers matching our ABI can usually be found in respective
// subdirectories of the opengl add-ons directories.
system_info info;
if (get_system_info(&info) == B_OK
&& (info.abi & B_HAIKU_ABI_MAJOR)
!= (B_HAIKU_ABI & B_HAIKU_ABI_MAJOR)) {
switch (B_HAIKU_ABI & B_HAIKU_ABI_MAJOR) {
case B_HAIKU_ABI_GCC_2:
fABISubDirectory = "gcc2";
break;
case B_HAIKU_ABI_GCC_4:
fABISubDirectory = "gcc4";
break;
}
}
AddDefaultPaths();
}
GLRendererRoster::~GLRendererRoster()
{
}
BGLRenderer*
GLRendererRoster::GetRenderer(int32 id)
{
RendererMap::const_iterator iterator = fRenderers.find(id);
if (iterator == fRenderers.end())
return NULL;
struct renderer_item item = iterator->second;
return item.renderer;
}
void
GLRendererRoster::AddDefaultPaths()
{
// add user directories first, so that they can override system renderers
const directory_which paths[] = {
B_USER_NONPACKAGED_ADDONS_DIRECTORY,
B_USER_ADDONS_DIRECTORY,
B_SYSTEM_ADDONS_DIRECTORY,
};
for (uint32 i = fSafeMode ? 4 : 0;
i < sizeof(paths) / sizeof(paths[0]); i++) {
BPath path;
status_t status = find_directory(paths[i], &path, true);
if (status == B_OK && path.Append("opengl") == B_OK)
AddPath(path.Path());
}
}
status_t
GLRendererRoster::AddPath(const char* path)
{
BDirectory directory(path);
status_t status = directory.InitCheck();
if (status < B_OK)
return status;
// if a subdirectory for our ABI exists, use that instead
if (fABISubDirectory != NULL) {
BEntry entry(&directory, fABISubDirectory);
if (entry.IsDirectory()) {
status = directory.SetTo(&entry);
if (status != B_OK)
return status;
}
}
node_ref nodeRef;
status = directory.GetNodeRef(&nodeRef);
if (status < B_OK)
return status;
int32 count = 0;
int32 files = 0;
entry_ref ref;
BEntry entry;
while (directory.GetNextRef(&ref) == B_OK) {
entry.SetTo(&ref, true);
if (entry.InitCheck() == B_OK && !entry.IsFile())
continue;
if (CreateRenderer(ref) == B_OK)
count++;
files++;
}
if (files != 0 && count == 0)
return B_BAD_VALUE;
return B_OK;
}
status_t
GLRendererRoster::AddRenderer(BGLRenderer* renderer,
image_id image, const entry_ref* ref, ino_t node)
{
renderer_item item;
item.renderer = renderer;
item.image = image;
item.node = node;
if (ref != NULL)
item.ref = *ref;
try {
fRenderers[fNextID] = item;
} catch (...) {
return B_NO_MEMORY;
}
renderer->fOwningRoster = this;
renderer->fID = fNextID++;
return B_OK;
}
status_t
GLRendererRoster::CreateRenderer(const entry_ref& ref)
{
BEntry entry(&ref, true);
node_ref nodeRef;
status_t status = entry.GetNodeRef(&nodeRef);
if (status < B_OK)
return status;
BPath path(&ref);
image_id image = load_add_on(path.Path());
if (image < B_OK)
return image;
BGLRenderer* (*instantiate_renderer)
(BGLView* view, ulong options, BGLDispatcher* dispatcher);
status = get_image_symbol(image, "instantiate_gl_renderer",
B_SYMBOL_TYPE_TEXT, (void**)&instantiate_renderer);
if (status == B_OK) {
BGLRenderer* renderer
= instantiate_renderer(fView, fOptions, new BGLDispatcher());
if (!renderer) {
unload_add_on(image);
return B_UNSUPPORTED;
}
if (AddRenderer(renderer, image, &ref, nodeRef.node) != B_OK) {
renderer->Release();
// this will delete the renderer
unload_add_on(image);
}
return B_OK;
}
unload_add_on(image);
return status;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/arch/pirformat.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/* A variety of PIR/PID formatting utilities */
#ifndef _PIRFORMAT_H
#define _PIRFORMAT_H
/**
* @brief Format of Processor Id Register (PIR) for P9
*
* GGGGCCCPPPPPTT where
* G = group, C = chip, P = proc, T = thread
*/
struct PIR_t
{
union
{
uint32_t word;
struct
{
// Normal Core Mode
uint32_t reserved:18; // 00:17 = unused
uint32_t groupId:4; // 18:21 = group id
uint32_t chipId:3; // 22:24 = chip id
uint32_t coreId:5; // 25:29 = core id (normal core)
uint32_t threadId:2; // 30:31 = thread id (normal core)
} PACKED;
struct
{
// Fused Core Mode
uint32_t reservedFused:18; // 00:17 = unused
uint32_t groupIdFused:4; // 18:21 = group id
uint32_t chipIdFused:3; // 22:24 = chip id
uint32_t coreIdFused:4; // 25:28 = core id (fused core)
uint32_t threadIdFused:3; // 29:31 = thread id (fused core)
} PACKED;
};
PIR_t(uint32_t i_word = 0) : word(i_word) {}
PIR_t(uint32_t i_groupId, uint32_t i_chipId,
uint32_t i_coreId, uint32_t i_thread = 0) :
reserved(0),
groupId(i_groupId), chipId(i_chipId),
coreId(i_coreId), threadId(i_thread) {}
PIR_t operator= (uint32_t i_word)
{
word = i_word;
return word;
}
bool operator< (const PIR_t& r) const
{
return word < r.word;
}
// Some more handy constants
enum
{
// Normal (non-fused) mode
BITS_IN_GROUP = 4,
BITS_IN_CHIP = 3,
BITS_IN_CORE = 5,
BITS_IN_THREAD = 2,
BITS_AFTER_THREAD = 0,
BITS_AFTER_CORE = BITS_AFTER_THREAD+BITS_IN_THREAD,
BITS_AFTER_CHIP = BITS_AFTER_CORE+BITS_IN_CORE,
BITS_AFTER_GROUP = BITS_AFTER_CHIP+BITS_IN_CHIP,
GROUP_MASK = 0x00003C00,
CHIP_MASK = 0x00000380,
CORE_MASK = 0x0000007C,
THREAD_MASK = 0x00000003,
VALID_BITS = 0x00003FFF,
// Fused mode
BITS_IN_CORE_FUSED = 5,
BITS_IN_THREAD_FUSED = 3,
GROUP_MASK_FUSED = 0x00003C00,
CHIP_MASK_FUSED = 0x00000380,
CORE_MASK_FUSED = 0x00000078,
THREAD_MASK_FUSED = 0x00000007,
};
// Some handy functions
inline static uint32_t groupFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).groupId;
}
inline static uint32_t chipFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).chipId;
}
inline static uint32_t coreFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).coreId;
}
inline static uint32_t threadFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).threadId;
}
inline static uint32_t groupFromChipId( uint32_t i_chipId ) {
return (i_chipId >> BITS_IN_CHIP);
}
inline static uint32_t chipFromChipId( uint32_t i_chipId ) {
return (i_chipId & (CHIP_MASK >>
(BITS_IN_CORE + BITS_IN_THREAD)));
}
inline static uint32_t groupFromCoreId( uint32_t i_chipId ) {
return (i_chipId >> (BITS_IN_CHIP+ BITS_IN_CORE));
}
inline static uint32_t chipFromCoreId( uint32_t i_chipId ) {
return (i_chipId >> BITS_IN_CORE);
}
inline static uint32_t coreFromCoreId( uint32_t i_chipId ) {
return (i_chipId & (CORE_MASK >> BITS_IN_THREAD));
}
inline static uint32_t createChipId( uint32_t i_groupId,
uint32_t i_chipId ) {
return ((i_groupId << BITS_IN_CHIP) | i_chipId);
}
inline static uint32_t createCoreId( uint32_t i_groupId,
uint32_t i_chipId,
uint32_t i_coreId )
{
return ((((i_groupId << BITS_IN_CHIP)
| i_chipId)
<< BITS_IN_CORE) | i_coreId);
}
inline static uint32_t createCoreId( uint32_t i_chipId,
uint32_t i_coreId )
{
return ((i_chipId << BITS_IN_CORE) | i_coreId);
}
};
#endif /* _PIRFORMAT_H */
<commit_msg>Update PIR Structure to Match Specification<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/arch/pirformat.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/* A variety of PIR/PID formatting utilities */
#ifndef _PIRFORMAT_H
#define _PIRFORMAT_H
/**
* @brief Format of Processor Id Register (PIR) for P9
*
* GGGGCCCRPPPPPTT where
* G = group, C = chip, P = proc, T = thread, R = reserved
*/
struct PIR_t
{
union
{
uint32_t word;
struct
{
// Normal Core Mode
uint32_t reserved0:17; // 00:16 = unused
uint32_t groupId:4; // 17:20 = group id
uint32_t chipId:3; // 21:23 = chip id
uint32_t reserved1:1; // 24 = reserved
uint32_t coreId:5; // 25:29 = core id (normal core)
uint32_t threadId:2; // 30:31 = thread id (normal core)
} PACKED;
struct
{
// Fused Core Mode
uint32_t reservedFused0:17; // 00:16 = unused
uint32_t groupIdFused:4; // 17:20 = group id
uint32_t chipIdFused:3; // 21:23 = chip id
uint32_t reservedFused1:1; // 24 = reserved
uint32_t coreIdFused:4; // 25:28 = core id (fused core)
uint32_t threadIdFused:3; // 29:31 = thread id (fused core)
} PACKED;
};
PIR_t(uint32_t i_word = 0) : word(i_word) {}
PIR_t(uint32_t i_groupId, uint32_t i_chipId,
uint32_t i_coreId, uint32_t i_thread = 0) :
reserved0(0),
groupId(i_groupId), chipId(i_chipId),
reserved1(0),
coreId(i_coreId), threadId(i_thread) {}
PIR_t operator= (uint32_t i_word)
{
word = i_word;
return word;
}
bool operator< (const PIR_t& r) const
{
return word < r.word;
}
// Some more handy constants
enum
{
// Normal (non-fused) mode
BITS_IN_GROUP = 4,
BITS_IN_CHIP = 3,
BITS_IN_CORE = 5,
BITS_IN_THREAD = 2,
BITS_IN_RESERVED1 = 1,
BITS_AFTER_THREAD = 0,
BITS_AFTER_CORE = BITS_AFTER_THREAD+BITS_IN_THREAD,
BITS_AFTER_CHIP = BITS_IN_RESERVED1+BITS_AFTER_CORE+BITS_IN_CORE,
BITS_AFTER_GROUP = BITS_AFTER_CHIP+BITS_IN_CHIP,
GROUP_MASK = 0x00007800,
CHIP_MASK = 0x00000700,
CORE_MASK = 0x0000007C,
THREAD_MASK = 0x00000003,
VALID_BITS = 0x00003FFF,
// Fused mode
BITS_IN_CORE_FUSED = 5,
BITS_IN_THREAD_FUSED = 3,
GROUP_MASK_FUSED = 0x00007800,
CHIP_MASK_FUSED = 0x00000700,
CORE_MASK_FUSED = 0x00000078,
THREAD_MASK_FUSED = 0x00000007,
};
// Some handy functions
// TODO RTC 154162 Add testcases for the below functions
inline static uint32_t groupFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).groupId;
}
inline static uint32_t chipFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).chipId;
}
inline static uint32_t coreFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).coreId;
}
inline static uint32_t threadFromPir( uint32_t i_pir ) {
return (static_cast<PIR_t>(i_pir)).threadId;
}
inline static uint32_t groupFromChipId( uint32_t i_chipId ) {
return (i_chipId >> BITS_IN_CHIP);
}
inline static uint32_t chipFromChipId( uint32_t i_chipId ) {
return (i_chipId & (CHIP_MASK >>
(BITS_AFTER_CHIP)));
}
inline static uint32_t groupFromCoreId( uint32_t i_chipId ) {
return (i_chipId >> (BITS_AFTER_GROUP));
}
inline static uint32_t chipFromCoreId( uint32_t i_chipId ) {
return (i_chipId >> BITS_AFTER_CHIP);
}
inline static uint32_t coreFromCoreId( uint32_t i_chipId ) {
return (i_chipId & (CORE_MASK >> BITS_IN_THREAD));
}
inline static uint32_t createChipId( uint32_t i_groupId,
uint32_t i_chipId ) {
return ((i_groupId << BITS_IN_CHIP) | i_chipId);
}
inline static uint32_t createCoreId( uint32_t i_groupId,
uint32_t i_chipId,
uint32_t i_coreId )
{
return ((((i_groupId << BITS_IN_CHIP)
| i_chipId)
<< (BITS_IN_RESERVED1 + BITS_IN_CORE)) | i_coreId);
}
inline static uint32_t createCoreId( uint32_t i_chipId,
uint32_t i_coreId )
{
return ((i_chipId << (BITS_IN_CORE + BITS_IN_RESERVED1)) | i_coreId);
}
};
#endif /* _PIRFORMAT_H */
<|endoftext|>
|
<commit_before>#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include <iostream>
int itkMetaDataDictionaryTest(int argc, char * argv[])
{
//This is a demo program to show how to put data into a dictionary.
itk::MetaDataDictionary MyDictionary;
//------------------------Testing of native types
//-------Floats
MyDictionary["ASimpleFloatInitalized"]=new itk::MetaDataObject<float>(1.234560F);
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
MyDictionary["ASimpleConstFloatInitalized"]=new itk::MetaDataObject<const float>(-1000.234560F);
std::cout << dynamic_cast<itk::MetaDataObject<const float>::Pointer>(MyDictionary["ASimpleConstFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
MyDictionary["ASimpleFloatUnitialized"]=new itk::MetaDataObject<float>;
dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatUnitialized"])->SetMetaDataObjectValue(2.2);
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatUnitialized"])->GetMetaDataObjectValue() << std::endl;
MyDictionary["ASimpleFloatInitializedAndChanged"]=new itk::MetaDataObject<float>(1.234560F);
dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatInitializedAndChanged"])->SetMetaDataObjectValue(3.3);
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatInitializedAndChanged"])->GetMetaDataObjectValue() << std::endl;
//-------Char pointers -- These can be tricky, so be careful!
MyDictionary["char const *"]=new itk::MetaDataObject<char const *>("Value Never Seen");
dynamic_cast<itk::MetaDataObject<char const * >::Pointer>(MyDictionary["char const *"])->SetMetaDataObjectValue("Value That Is Seen");
//This is OK because the pointer can be changed, but the value of the pointer can not. NOTE: no the char array is not copied, just the pointer to the array.
std::cout << (dynamic_cast<itk::MetaDataObject<char const *>::Pointer>(MyDictionary["char const *"])->GetMetaDataObjectValue()) << std::endl;
MyDictionary["char const * const =\"Initial Value\""]=new itk::MetaDataObject<char const * const>("Initial Value");
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const =\"Initial Value\""])->GetMetaDataObjectValue()) << std::endl;
//The data can not be changed, and the pointer can not be changed.
//Compiler Error: assignment of read-only data-member
//dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const =\"Initial Value\""])->SetMetaDataObjectValue("Compiler Error");
const char tempvar[60]="Setting value from const variable";
MyDictionary["char const * const = tempvar"]=new itk::MetaDataObject<char const * const>(tempvar);
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar"])->GetMetaDataObjectValue()) << std::endl;
//Compiler Error: assignment of read-only data-member
//dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar"])->SetMetaDataObjectValue("Compiler Error");
//NOTE: Default value will be a pointer to NULL, or even worse to some unknown place.
//gcc 2.96 will create this useless entry, but the SGI MipsPro compiler recognizes
//That this is uninitialized, and causes a compiler error.
//MyDictionary["char const * const = tempvar2"]=new itk::MetaDataObject<char const * const>;
//
//const char tempvar2[60]="Setting value from const variable";
//Compiler Error: assignment of read-only data-member
//dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar2"])->SetMetaDataObjectValue(tempvar2);
//Runtime Error: Trying to print a character string that points to NULL.
//std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar2"])->GetMetaDataObjectValue()) << std::endl;
//Other gotchas with the Dictionary
char * StrandedMemeory=new char[2345];
strcpy(StrandedMemeory,"This is stranded memory that will not be released when the Dictionary is cleaned up");
//NOTE: Only the pointer is copied, not the data withing the pointer!
MyDictionary["StrandedMemoryExample"]=new itk::MetaDataObject<char *>(StrandedMemeory);
std::cout << (dynamic_cast<itk::MetaDataObject<char *>::Pointer>(MyDictionary["StrandedMemoryExample"])->GetMetaDataObjectValue()) << std::endl;
strcpy(StrandedMemeory,"This this was changed outside the class, and may cause all types of errors.");
std::cout << (dynamic_cast<itk::MetaDataObject<char *>::Pointer>(MyDictionary["StrandedMemoryExample"])->GetMetaDataObjectValue()) << std::endl;
//-------Classes that can be initialized.
MyDictionary["AnSTLString"]=new itk::MetaDataObject<std::string>("This is a std::string That is never Seen");
dynamic_cast<itk::MetaDataObject<std::string>::Pointer>(MyDictionary["AnSTLString"])->SetMetaDataObjectValue("This is a std::string");
std::cout << dynamic_cast<itk::MetaDataObject<std::string>::Pointer>(MyDictionary["AnSTLString"])->GetMetaDataObjectValue() << std::endl;
for(std::map<std::string, itk::MetaDataObjectBase::Pointer>::iterator it=MyDictionary.begin();
it != MyDictionary.end();
it++)
{
std::cout << "Type name for "<<it->first <<" is " << it->second->GetMetaDataObjectTypeName() << std::endl;
}
//------Test copying of Dictionary
//itk::MetaDataDictionary NewDictionary(MyDictionary);
itk::MetaDataDictionary NewDictionary;
NewDictionary=MyDictionary;
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(NewDictionary["ASimpleFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<const float>::Pointer>(NewDictionary["ASimpleConstFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(NewDictionary["ASimpleFloatUnitialized"])->GetMetaDataObjectValue() << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(NewDictionary["ASimpleFloatInitializedAndChanged"])->GetMetaDataObjectValue() << std::endl;
std::cout << (dynamic_cast<itk::MetaDataObject<char const *>::Pointer>(NewDictionary["char const *"])->GetMetaDataObjectValue()) << std::endl;
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(NewDictionary["char const * const =\"Initial Value\""])->GetMetaDataObjectValue()) << std::endl;
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(NewDictionary["char const * const = tempvar"])->GetMetaDataObjectValue()) << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<std::string>::Pointer>(NewDictionary["AnSTLString"])->GetMetaDataObjectValue() << std::endl;
for(std::map<std::string, itk::MetaDataObjectBase::Pointer>::iterator it=NewDictionary.begin();
it != NewDictionary.end();
it++)
{
std::cout << "Type name for "<<it->first <<" is " << it->second->GetMetaDataObjectTypeInfo().name() << std::endl;
}
//PrintSelf functionality Test
std::cout << "===========================================================" << std::endl;
std::cout << "Printing Dictionary" << std::endl;
NewDictionary.PrintSelf(std::cout, 10);
return 0;
}
<commit_msg>ERR: redefinition of for index.<commit_after>#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include <iostream>
int itkMetaDataDictionaryTest(int argc, char * argv[])
{
//This is a demo program to show how to put data into a dictionary.
itk::MetaDataDictionary MyDictionary;
//------------------------Testing of native types
//-------Floats
MyDictionary["ASimpleFloatInitalized"]=new itk::MetaDataObject<float>(1.234560F);
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
MyDictionary["ASimpleConstFloatInitalized"]=new itk::MetaDataObject<const float>(-1000.234560F);
std::cout << dynamic_cast<itk::MetaDataObject<const float>::Pointer>(MyDictionary["ASimpleConstFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
MyDictionary["ASimpleFloatUnitialized"]=new itk::MetaDataObject<float>;
dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatUnitialized"])->SetMetaDataObjectValue(2.2);
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatUnitialized"])->GetMetaDataObjectValue() << std::endl;
MyDictionary["ASimpleFloatInitializedAndChanged"]=new itk::MetaDataObject<float>(1.234560F);
dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatInitializedAndChanged"])->SetMetaDataObjectValue(3.3);
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(MyDictionary["ASimpleFloatInitializedAndChanged"])->GetMetaDataObjectValue() << std::endl;
//-------Char pointers -- These can be tricky, so be careful!
MyDictionary["char const *"]=new itk::MetaDataObject<char const *>("Value Never Seen");
dynamic_cast<itk::MetaDataObject<char const * >::Pointer>(MyDictionary["char const *"])->SetMetaDataObjectValue("Value That Is Seen");
//This is OK because the pointer can be changed, but the value of the pointer can not. NOTE: no the char array is not copied, just the pointer to the array.
std::cout << (dynamic_cast<itk::MetaDataObject<char const *>::Pointer>(MyDictionary["char const *"])->GetMetaDataObjectValue()) << std::endl;
MyDictionary["char const * const =\"Initial Value\""]=new itk::MetaDataObject<char const * const>("Initial Value");
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const =\"Initial Value\""])->GetMetaDataObjectValue()) << std::endl;
//The data can not be changed, and the pointer can not be changed.
//Compiler Error: assignment of read-only data-member
//dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const =\"Initial Value\""])->SetMetaDataObjectValue("Compiler Error");
const char tempvar[60]="Setting value from const variable";
MyDictionary["char const * const = tempvar"]=new itk::MetaDataObject<char const * const>(tempvar);
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar"])->GetMetaDataObjectValue()) << std::endl;
//Compiler Error: assignment of read-only data-member
//dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar"])->SetMetaDataObjectValue("Compiler Error");
//NOTE: Default value will be a pointer to NULL, or even worse to some unknown place.
//gcc 2.96 will create this useless entry, but the SGI MipsPro compiler recognizes
//That this is uninitialized, and causes a compiler error.
//MyDictionary["char const * const = tempvar2"]=new itk::MetaDataObject<char const * const>;
//
//const char tempvar2[60]="Setting value from const variable";
//Compiler Error: assignment of read-only data-member
//dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar2"])->SetMetaDataObjectValue(tempvar2);
//Runtime Error: Trying to print a character string that points to NULL.
//std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(MyDictionary["char const * const = tempvar2"])->GetMetaDataObjectValue()) << std::endl;
//Other gotchas with the Dictionary
char * StrandedMemeory=new char[2345];
strcpy(StrandedMemeory,"This is stranded memory that will not be released when the Dictionary is cleaned up");
//NOTE: Only the pointer is copied, not the data withing the pointer!
MyDictionary["StrandedMemoryExample"]=new itk::MetaDataObject<char *>(StrandedMemeory);
std::cout << (dynamic_cast<itk::MetaDataObject<char *>::Pointer>(MyDictionary["StrandedMemoryExample"])->GetMetaDataObjectValue()) << std::endl;
strcpy(StrandedMemeory,"This this was changed outside the class, and may cause all types of errors.");
std::cout << (dynamic_cast<itk::MetaDataObject<char *>::Pointer>(MyDictionary["StrandedMemoryExample"])->GetMetaDataObjectValue()) << std::endl;
//-------Classes that can be initialized.
MyDictionary["AnSTLString"]=new itk::MetaDataObject<std::string>("This is a std::string That is never Seen");
dynamic_cast<itk::MetaDataObject<std::string>::Pointer>(MyDictionary["AnSTLString"])->SetMetaDataObjectValue("This is a std::string");
std::cout << dynamic_cast<itk::MetaDataObject<std::string>::Pointer>(MyDictionary["AnSTLString"])->GetMetaDataObjectValue() << std::endl;
std::map<std::string, itk::MetaDataObjectBase::Pointer>::iterator it;
for(it=MyDictionary.begin();
it != MyDictionary.end();
it++)
{
std::cout << "Type name for "<<it->first <<" is " << it->second->GetMetaDataObjectTypeName() << std::endl;
}
//------Test copying of Dictionary
//itk::MetaDataDictionary NewDictionary(MyDictionary);
itk::MetaDataDictionary NewDictionary;
NewDictionary=MyDictionary;
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(NewDictionary["ASimpleFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<const float>::Pointer>(NewDictionary["ASimpleConstFloatInitalized"])->GetMetaDataObjectValue() << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(NewDictionary["ASimpleFloatUnitialized"])->GetMetaDataObjectValue() << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<float>::Pointer>(NewDictionary["ASimpleFloatInitializedAndChanged"])->GetMetaDataObjectValue() << std::endl;
std::cout << (dynamic_cast<itk::MetaDataObject<char const *>::Pointer>(NewDictionary["char const *"])->GetMetaDataObjectValue()) << std::endl;
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(NewDictionary["char const * const =\"Initial Value\""])->GetMetaDataObjectValue()) << std::endl;
std::cout << (dynamic_cast<itk::MetaDataObject<char const * const>::Pointer>(NewDictionary["char const * const = tempvar"])->GetMetaDataObjectValue()) << std::endl;
std::cout << dynamic_cast<itk::MetaDataObject<std::string>::Pointer>(NewDictionary["AnSTLString"])->GetMetaDataObjectValue() << std::endl;
for(it=NewDictionary.begin();
it != NewDictionary.end();
it++)
{
std::cout << "Type name for "<<it->first <<" is " << it->second->GetMetaDataObjectTypeInfo().name() << std::endl;
}
//PrintSelf functionality Test
std::cout << "===========================================================" << std::endl;
std::cout << "Printing Dictionary" << std::endl;
NewDictionary.PrintSelf(std::cout, 10);
return 0;
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include "GaussianSmoothingFilter.hpp"
#include "DeviceManager.hpp"
namespace fast {
TEST_CASE("No input given to GaussianSmoothingFilter throws exception", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
CHECK_THROWS(filter->update());
}
TEST_CASE("Negative or zero sigma and mask size input throws exception in GaussianSmoothingFilter" , "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
CHECK_THROWS(filter->setMaskSize(-4));
CHECK_THROWS(filter->setMaskSize(0));
CHECK_THROWS(filter->setStandardDeviation(-4));
CHECK_THROWS(filter->setStandardDeviation(0));
}
TEST_CASE("Even input as mask size throws exception in GaussianSmoothingFilter", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
CHECK_THROWS(filter->setMaskSize(2));
}
TEST_CASE("Correct output with small 3x3 2D image as input to GaussianSmoothingFilter on OpenCLDevice", "[fast][GaussianSmoothingFilter]") {
DeviceManager& deviceManager = DeviceManager::getInstance();
OpenCLDevice::pointer device = deviceManager.getOneOpenCLDevice();
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create2DImage(3,3,TYPE_FLOAT,1,device);
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 9; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(unsigned int x = 0; x < 3; x++) {
for(unsigned int y = 0; y < 3; y++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1);
if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3] - truth) > 0.00001) {
success = false;
break;
}
}}
CHECK(success == true);
}
TEST_CASE("Correct output with small 3x3 2D image as input to GaussianSmoothingFilter on Host", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create2DImage(3,3,TYPE_FLOAT,1,Host::New());
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 9; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(unsigned int x = 0; x < 3; x++) {
for(unsigned int y = 0; y < 3; y++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1);
if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3] - truth) > 0.00001) {
success = false;
break;
}
}}
CHECK(success == true);
}
TEST_CASE("Correct output with small 3x3 3D image as input to GaussianSmoothingFilter on OpenCLDevice", "[fast][GaussianSmoothingFilter]") {
DeviceManager& deviceManager = DeviceManager::getInstance();
OpenCLDevice::pointer device = deviceManager.getOneOpenCLDevice();
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create3DImage(3,3,3,TYPE_FLOAT,1,device);
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 3*3*3; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(unsigned int x = 0; x < 3; x++) {
for(unsigned int y = 0; y < 3; y++) {
for(unsigned int z = 0; z < 3; z++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1)+abs(z-1);
if(distance == 3) {
truth = 0.382549;
} else if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3+z*3*3] - truth) > 0.00001) {
success = false;
break;
}
}}}
CHECK(success == true);
}
TEST_CASE("Correct output with small 3x3 3D image as input to GaussianSmoothingFilter on Host", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create3DImage(3,3,3,TYPE_FLOAT,1,Host::New());
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 3*3*3; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(unsigned int x = 0; x < 3; x++) {
for(unsigned int y = 0; y < 3; y++) {
for(unsigned int z = 0; z < 3; z++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1)+abs(z-1);
if(distance == 3) {
truth = 0.382549;
} else if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3+z*3*3] - truth) > 0.00001) {
success = false;
break;
}
}}}
CHECK(success == true);
}
} // end namespace fast
<commit_msg>Fixed some windows errors in the GaussianSmoothingFilter tests<commit_after>#include "catch.hpp"
#include "GaussianSmoothingFilter.hpp"
#include "DeviceManager.hpp"
namespace fast {
TEST_CASE("No input given to GaussianSmoothingFilter throws exception", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
CHECK_THROWS(filter->update());
}
TEST_CASE("Negative or zero sigma and mask size input throws exception in GaussianSmoothingFilter" , "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
CHECK_THROWS(filter->setMaskSize(-4));
CHECK_THROWS(filter->setMaskSize(0));
CHECK_THROWS(filter->setStandardDeviation(-4));
CHECK_THROWS(filter->setStandardDeviation(0));
}
TEST_CASE("Even input as mask size throws exception in GaussianSmoothingFilter", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
CHECK_THROWS(filter->setMaskSize(2));
}
TEST_CASE("Correct output with small 3x3 2D image as input to GaussianSmoothingFilter on OpenCLDevice", "[fast][GaussianSmoothingFilter]") {
DeviceManager& deviceManager = DeviceManager::getInstance();
OpenCLDevice::pointer device = deviceManager.getOneOpenCLDevice();
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create2DImage(3,3,TYPE_FLOAT,1,device);
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 9; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 3; y++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1);
if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3] - truth) > 0.00001) {
success = false;
break;
}
}}
CHECK(success == true);
}
TEST_CASE("Correct output with small 3x3 2D image as input to GaussianSmoothingFilter on Host", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create2DImage(3,3,TYPE_FLOAT,1,Host::New());
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 9; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 3; y++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1);
if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3] - truth) > 0.00001) {
success = false;
break;
}
}}
CHECK(success == true);
}
TEST_CASE("Correct output with small 3x3 3D image as input to GaussianSmoothingFilter on OpenCLDevice", "[fast][GaussianSmoothingFilter]") {
DeviceManager& deviceManager = DeviceManager::getInstance();
OpenCLDevice::pointer device = deviceManager.getOneOpenCLDevice();
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create3DImage(3,3,3,TYPE_FLOAT,1,device);
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 3*3*3; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 3; y++) {
for(int z = 0; z < 3; z++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1)+abs(z-1);
if(distance == 3) {
truth = 0.382549;
} else if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3+z*3*3] - truth) > 0.00001) {
success = false;
break;
}
}}}
CHECK(success == true);
}
TEST_CASE("Correct output with small 3x3 3D image as input to GaussianSmoothingFilter on Host", "[fast][GaussianSmoothingFilter]") {
GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();
filter->setMaskSize(3);
filter->setStandardDeviation(1.0);
Image::pointer image = Image::New();
image->create3DImage(3,3,3,TYPE_FLOAT,1,Host::New());
ImageAccess access = image->getImageAccess(ACCESS_READ_WRITE);
float* data = (float*)access.get();
for(unsigned int i = 0; i < 3*3*3; i++) {
data[i] = 1.0f;
}
access.release();
filter->setInput(image);
Image::pointer output = filter->getOutput();
filter->update();
access = output->getImageAccess(ACCESS_READ);
data = (float*)access.get();
bool success = true;
for(int x = 0; x < 3; x++) {
for(int y = 0; y < 3; y++) {
for(int z = 0; z < 3; z++) {
float truth;
unsigned int distance = abs(x-1)+abs(y-1)+abs(z-1);
if(distance == 3) {
truth = 0.382549;
} else if(distance == 2) {
truth = 0.526976f;
} else if(distance == 1) {
truth = 0.725931f;
} else {
truth = 1.0f;
}
if(fabs(data[x+y*3+z*3*3] - truth) > 0.00001) {
success = false;
break;
}
}}}
CHECK(success == true);
}
} // end namespace fast
<|endoftext|>
|
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_zero.hxx"
#include "istream_internal.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <limits.h>
struct ZeroIstream {
struct istream stream;
};
static inline ZeroIstream *
istream_to_zero(struct istream *istream)
{
return &ContainerCast2(*istream, &ZeroIstream::stream);
}
static off_t
istream_zero_available(gcc_unused struct istream *istream, bool partial)
{
return partial
? INT_MAX
: -1;
}
static off_t
istream_zero_skip(struct istream *istream gcc_unused, off_t length)
{
return length;
}
static void
istream_zero_read(struct istream *istream)
{
ZeroIstream *zero = istream_to_zero(istream);
static char buffer[1024];
istream_invoke_data(&zero->stream, buffer, sizeof(buffer));
}
static void
istream_zero_close(struct istream *istream)
{
ZeroIstream *zero = istream_to_zero(istream);
istream_deinit(&zero->stream);
}
static const struct istream_class istream_zero = {
.available = istream_zero_available,
.skip = istream_zero_skip,
.read = istream_zero_read,
.close = istream_zero_close,
};
struct istream *
istream_zero_new(struct pool *pool)
{
auto zero = NewFromPool<ZeroIstream>(*pool);
istream_init(&zero->stream, &istream_zero, pool);
return &zero->stream;
}
<commit_msg>istream_zero: use class Istream<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_zero.hxx"
#include "istream_oo.hxx"
#include <limits.h>
class ZeroIstream final : public Istream {
public:
explicit ZeroIstream(struct pool &_pool):Istream(_pool) {}
/* virtual methods from class Istream */
off_t GetAvailable(bool partial) override {
return partial
? INT_MAX
: -1;
}
off_t Skip(off_t length) override {
return length;
}
void Read() override {
static char buffer[1024];
InvokeData(buffer, sizeof(buffer));
}
};
struct istream *
istream_zero_new(struct pool *pool)
{
return NewIstream(*pool);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 Joshua Beitler, Mirus contributors
// 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 <term/terminal.hpp>
// terminal sizes
static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 24;
// term info
static size_t terminal_row;
static size_t terminal_column;
static uint8_t terminal_color;
static uint16_t* terminal_buffer;
uint8_t mirus::make_color(enum vga_color fg, enum vga_color bg) {
return fg | bg << 4;
}
uint16_t mirus::make_vgaentry(char c, uint8_t color) {
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
void mirus::terminal_initialize() {
using namespace mirus;
terminal_row = 0;
terminal_column = 0;
terminal_color = make_color(COLOR_WHITE, COLOR_BLACK);
terminal_buffer = (uint16_t*) 0xB8000;
for ( size_t y = 0; y < VGA_HEIGHT; y++ )
{
for ( size_t x = 0; x < VGA_WIDTH; x++ )
{
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry(' ', terminal_color);
}
}
}
// set color
void mirus::terminal_setcolor(uint8_t color) {
terminal_color = color;
}
// put an entry at location
void mirus::terminal_putentryat(char c, uint8_t color, size_t x, size_t y) {
using namespace mirus;
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry(c, color);
}
// put a char at a location
void mirus::terminal_putchar(char c) {
using namespace mirus;
if (c == '\r') {
++terminal_row;
terminal_column = 0;
}
terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
if ( ++terminal_column == VGA_WIDTH )
{
terminal_column = 0;
terminal_row++;
// if (++terminal_row == 25)
// {
// terminal_scroll();
// }
}
// TODO: bug here
// if (++terminal_row == VGA_HEIGHT) {
// terminal_scroll();
// }
terminal_move_cursor();
}
void mirus::terminal_putchar(char c, uint8_t color) {
uint8_t oldcolor = terminal_color;
terminal_setcolor(color);
mirus::terminal_putchar(c);
terminal_setcolor(oldcolor);
}
// write a string
void mirus::terminal_writestring(const char* data) {
using namespace mirus;
size_t datalen = strlen(data);
for (size_t i = 0; i < datalen; i++) {
if (data[i] == '\r') {
// CR is default...
++terminal_row;
terminal_column = 0;
} else {
terminal_putchar(data[i]);
}
}
}
void mirus::terminal_writestring(const char* data, uint8_t color) {
using namespace mirus;
size_t datalen = strlen(data);
for (size_t i = 0; i < datalen; i++) {
if (data[i] == '\r') {
// CR is default...
++terminal_row;
terminal_column = 0;
} else {
terminal_putchar(data[i], color);
}
}
}
void mirus::terminal_clear() {
using namespace mirus;
uint8_t attributeByte = (0 /*black*/ << 4) | (15 /*white*/ & 0x0F);
uint16_t blank = 0x20 /* space */ | (attributeByte << 8);
for (int i = 0; i < 80 * 25; i++)
terminal_buffer[i] = 0;
// Move the hardware cursor back to the start.
terminal_row = 0;
terminal_column = 0;
terminal_move_cursor();
}
// TODO: does not scroll correctly
void mirus::terminal_scroll() {
using namespace mirus;
uint8_t blank = make_color(COLOR_BLACK, COLOR_BLACK);
unsigned temp;
unsigned short* vidmem = nullptr;
vidmem = (unsigned short*)0xB8000;
temp = terminal_column - 25 + 1;
mirus::memcpy(vidmem, vidmem + temp * 80, (25 - temp) * 80 * 2);
mirus::memsetw(vidmem + (25 - temp) * 80, blank, 80);
terminal_column = 25 - 1;
}
void mirus::terminal_move_cursor() {
using namespace mirus;
unsigned temp;
/* The equation for finding the index in a linear
* chunk of memory can be represented by:
* Index = [(y * width) + x] */
temp = terminal_row * 80 + terminal_column;
/* This sends a command to indicies 14 and 15 in the
* CRT Control Register of the VGA controller. These
* are the high and low bytes of the index that show
* where the hardware cursor is to be 'blinking'. To
* learn more, you should look up some VGA specific
* programming documents. A great start to graphics:
* http://www.brackeen.com/home/vga */
mirus::outb(0x3D4, 14);
mirus::outb(0x3D5, temp >> 8);
mirus::outb(0x3D4, 15);
mirus::outb(0x3D5, temp);
}<commit_msg>Adding backspace functionality<commit_after>// Copyright (c) 2013 Joshua Beitler, Mirus contributors
// 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 <term/terminal.hpp>
// terminal sizes
static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 24;
// term info
static size_t terminal_row;
static size_t terminal_column;
static uint8_t terminal_color;
static uint16_t* terminal_buffer;
uint8_t mirus::make_color(enum vga_color fg, enum vga_color bg) {
return fg | bg << 4;
}
uint16_t mirus::make_vgaentry(char c, uint8_t color) {
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
void mirus::terminal_initialize() {
using namespace mirus;
terminal_row = 0;
terminal_column = 0;
terminal_color = make_color(COLOR_WHITE, COLOR_BLACK);
terminal_buffer = (uint16_t*) 0xB8000;
for ( size_t y = 0; y < VGA_HEIGHT; y++ )
{
for ( size_t x = 0; x < VGA_WIDTH; x++ )
{
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry(' ', terminal_color);
}
}
}
// set color
void mirus::terminal_setcolor(uint8_t color) {
terminal_color = color;
}
// put an entry at location
void mirus::terminal_putentryat(char c, uint8_t color, size_t x, size_t y) {
using namespace mirus;
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry(c, color);
}
// put a char at a location
void mirus::terminal_putchar(char c) {
using namespace mirus;
if (c == '\r') {
++terminal_row;
terminal_column = 0;
} else if (c == '\b') {
--terminal_column;
}
terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
if ( ++terminal_column == VGA_WIDTH )
{
terminal_column = 0;
terminal_row++;
// if (++terminal_row == 25)
// {
// terminal_scroll();
// }
}
// TODO: bug here
// if (++terminal_row == VGA_HEIGHT) {
// terminal_scroll();
// }
terminal_move_cursor();
}
void mirus::terminal_putchar(char c, uint8_t color) {
uint8_t oldcolor = terminal_color;
terminal_setcolor(color);
mirus::terminal_putchar(c);
terminal_setcolor(oldcolor);
}
// write a string
void mirus::terminal_writestring(const char* data) {
using namespace mirus;
size_t datalen = strlen(data);
for (size_t i = 0; i < datalen; i++)
terminal_putchar(data[i]);
}
}
void mirus::terminal_writestring(const char* data, uint8_t color) {
using namespace mirus;
size_t datalen = strlen(data);
for (size_t i = 0; i < datalen; i++)
terminal_putchar(data[i], color);
}
}
void mirus::terminal_clear() {
using namespace mirus;
uint8_t attributeByte = (0 /*black*/ << 4) | (15 /*white*/ & 0x0F);
uint16_t blank = 0x20 /* space */ | (attributeByte << 8);
for (int i = 0; i < 80 * 25; i++)
terminal_buffer[i] = 0;
// Move the hardware cursor back to the start.
terminal_row = 0;
terminal_column = 0;
terminal_move_cursor();
}
// TODO: does not scroll correctly
void mirus::terminal_scroll() {
using namespace mirus;
uint8_t blank = make_color(COLOR_BLACK, COLOR_BLACK);
unsigned temp;
unsigned short* vidmem = nullptr;
vidmem = (unsigned short*)0xB8000;
temp = terminal_column - 25 + 1;
mirus::memcpy(vidmem, vidmem + temp * 80, (25 - temp) * 80 * 2);
mirus::memsetw(vidmem + (25 - temp) * 80, blank, 80);
terminal_column = 25 - 1;
}
void mirus::terminal_move_cursor() {
using namespace mirus;
unsigned temp;
/* The equation for finding the index in a linear
* chunk of memory can be represented by:
* Index = [(y * width) + x] */
temp = terminal_row * 80 + terminal_column;
/* This sends a command to indicies 14 and 15 in the
* CRT Control Register of the VGA controller. These
* are the high and low bytes of the index that show
* where the hardware cursor is to be 'blinking'. To
* learn more, you should look up some VGA specific
* programming documents. A great start to graphics:
* http://www.brackeen.com/home/vga */
mirus::outb(0x3D4, 14);
mirus::outb(0x3D5, temp >> 8);
mirus::outb(0x3D4, 15);
mirus::outb(0x3D5, temp);
}<|endoftext|>
|
<commit_before>// from lib/THC/THCTensorMasked.cu:
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#include <boost/compute/core.hpp>
#include <boost/compute/iterator/buffer_iterator.hpp>
#include <boost/compute/algorithm/reverse.hpp>
#include <boost/compute/algorithm/transform_if.hpp>
#include <boost/compute/lambda.hpp>
#include <boost/compute/iterator/zip_iterator.hpp>
#include "THClTensorMath.h"
#include "THClGeneral.h"
#include "THClBlas.h"
#include "THClTensorCopy.h"
//#include "THClTensorRandom.h"
#include "THClApply.h"
#include "THClReduce.h"
#include <iostream>
using namespace std;
// The largest consecutive integer representable in float32 (2^24)
#define FLOAT32_MAX_CONSECUTIVE_INT 16777216.0f
class TensorMaskedFillOp : public HasOperator2, public HasScalars {
public:
int getNumScalars() const { return 1; }
float getScalar( int index ) const { return value; }
TensorMaskedFillOp(float v) : value(v) {}
std::string operator2() const {
return "if( *in1 != 0.0f ) { *out = val1; }";
}
float value;
};
class TensorMaskedCopyOp : public HasOperator2, public HasGlobalTensors {
public:
TensorMaskedCopyOp(THClTensor *src, THClTensor *baseMask, THClTensor *maskPrefixSum) :
src(src), baseMask(baseMask), maskPrefixSum(maskPrefixSum) {
}
int getNumGlobalTensors() const { return 3; }
THClTensor *getTensor(int index) const {
if(index == 0){ return src; }
if(index == 1){ return baseMask; }
if(index == 2){ return maskPrefixSum; }
THError("index not recognized %i", index);
return 0;
}
std::string getTensorName(int index) const {
if(index == 0){ return "src"; }
if(index == 1){ return "baseMask"; }
if(index == 2){ return "maskPrefixSum"; }
THError("index not recognized %i", index);
return "";
}
std::string operator2() const {
return "if( *in1 != 0.0f ) { *out = src[(int)maskPrefixSum[srcOffset] ]; }";
}
THClTensor *src;
THClTensor *baseMask;
THClTensor *maskPrefixSum;
};
//struct TensorMaskedCopyOp {
// TensorMaskedCopyOp(float* s, float* bm, float* ps)
// : src(s),
// baseMask(bm),
// maskPrefixSum(ps) {
// }
// /*__device__*/ /*__forceline__*/ void operator()(float* out, float* mask) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// // We've already checked that this offset is <= 2^24, so this is ok.
// int srcOffset = (int) (mask - baseMask);
// *out = src[(int) maskPrefixSum[srcOffset]];
// }
// }
// // Where we are copying from
// float* src;
// // The base address of mask so we can calculate offset
// float* baseMask;
// // The index we are copying from
// float* maskPrefixSum;
//};
//class TensorMaskedSelectOp : public HasOperator3, public HasScalars {
//public:
// int getNumScalars() const { return 1; }
// string operator3() const {
// return "if(*out != 0.0f){out[(int)*in1] = *in2; }";
// }
// TensorMaskedSelectOp(float* t) : out(t) {}
// void operator()(float* mask, float* maskPrefixSum, float* in) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// out[(int) *maskPrefixSum] = *in;
// }
// }
// float* out;
//};
void THClTensor_maskedFill(THClState* state,
THClTensor *tensor, THClTensor *mask, float value)
{
THAssert(THClTensor_checkGPU(state, 2, tensor, mask));
THArgCheck(THClTensor_nElement(state, tensor) ==
THClTensor_nElement(state, mask),
2, "sizes do not match");
TensorMaskedFillOp op(value);
if (!THClTensor_pointwiseApply2(state, tensor, mask, &op)) {
THArgCheck(false, 2, CLTORCH_DIM_WARNING);
}
}
void THClTensor_maskedCopy(THClState* state,
THClTensor *tensor, THClTensor *mask, THClTensor *src)
{
THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
long maskSize = THClTensor_nElement(state, mask);
long tensorSize = THClTensor_nElement(state, tensor);
long srcSize = THClTensor_nElement(state, src);
// Since we are performing a prefix sum of mask, it cannot exceed
// the size allowed in consecutive integers in float32
THArgCheck(maskSize <= (long) FLOAT32_MAX_CONSECUTIVE_INT,
3, "mask nElements exceeds single-precision float "
"consecutive integer precision size (2^24)");
// `mask` and `tensor` must have the same number of elements
THArgCheck(maskSize == tensorSize, 2,
"mask and tensor must have the same number of elements");
THClTensor* contigMask = THClTensor_newContiguous(state, mask);
long oneElements = (long) THClTensor_sumall(state, contigMask);
// The number of `1` elements present in the mask must be <= the
// number of elements available in `src`
if (oneElements > srcSize) {
THClTensor_free(state, contigMask);
THArgCheck(false, 2, "source nElements must be == mask `1` elements");
}
// Use a prefix sum to determine the copy locations of the masked elements
THClTensor* maskPrefixSum = THClTensor_newv2(state, src->storage->device);
THClTensor_resizeAs(state, maskPrefixSum, contigMask);
// We are getting elements from `src` based on an offset from
// `maskPrefixSum`, so that should be made contiguous too
THClTensor* contigSrc = THClTensor_newContiguous(state, src);
// TensorAddOp cumOp;
// THAssert(THClTensor_checkGPU(state, 2, maskData, maskPrefixSumData));
// THClTensor_scanDim(state, maskPrefixSumData, maskData, dimension, 0.0f, &cumOp);
// hmmmm: this is scanDim, but what we really need is somsething like: scanAll
// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
THError("Not implemented");
// update `tensor` where `mask` == 1 but pull from `src` at
// maskPrefixSum
TensorMaskedCopyOp maskedCopyOp(
contigSrc, contigMask, maskPrefixSum);
bool status = THClTensor_pointwiseApply2(
state, tensor, contigMask, &maskedCopyOp);
THError("Not implemented");
THClTensor_free(state, contigSrc);
THClTensor_free(state, maskPrefixSum);
THClTensor_free(state, contigMask);
THArgCheck(status, 2, CLTORCH_DIM_WARNING);
THError("Not implemented");
}
void THClTensor_maskedSelect(THClState* state,
THClTensor *tensor, THClTensor *src, THClTensor *mask)
{
THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
THArgCheck(THClTensor_nElement(state, mask) == THClTensor_nElement(state, src),
2, "sizes do not match");
// Since we are performing a prefix sum of mask, it cannot exceed
// the size allowed in consecutive integers in float32
THArgCheck(THClTensor_nElement(state, mask) <=
(long) FLOAT32_MAX_CONSECUTIVE_INT,
3, "mask nElements exceeds single-precision float "
"consecutive integer precision size (2^24)");
THClTensor* contigSrc = THClTensor_newContiguous(state, src);
// Determine our output size
THClTensor* contigMask = THClTensor_newContiguous(state, mask);
long totalElements = (long) THClTensor_sumall(state, contigMask);
cout << "totalElements " << totalElements << endl;
// This should be contiguous already, so no need to make it contig
// for the apply kernel
THClTensor_resize1d(state, tensor, totalElements);
// Use a prefix sum to determine the output locations of the masked elements
// THClTensor* maskPrefixSum = THClTensor_new(state);
// THClTensor_resizeAs(state, maskPrefixSum, contigMask);
// ==== boost compute bit starts ========
EasyCL *cl = src->storage->cl;
boost::compute::context boost_context(*cl->context);
boost::compute::command_queue boost_queue(*cl->queue);
boost::compute::buffer boostData(*contigSrc->storage->wrapper->getDeviceArray());
boost::compute::buffer boostMask(*contigMask->storage->wrapper->getDeviceArray());
boost::compute::buffer boostOut(*tensor->storage->wrapper->getDeviceArray());
transform_if(
make_zip_iterator(
boost::make_tuple(
boost::compute::make_buffer_iterator<float>(boostData, 0),
boost::compute::make_buffer_iterator<float>(boostMask, 0)
)
),
make_zip_iterator(
boost::make_tuple(
boost::compute::make_buffer_iterator<float>(boostData, THClTensor_nElement(state, mask)),
boost::compute::make_buffer_iterator<float>(boostMask, THClTensor_nElement(state, mask))
)
),
boost::compute::make_buffer_iterator<float>(boostOut, 0),
boost::compute::get<0>(), // function that return input value
boost::compute::lambda::get<1>(boost::compute::_1) == 1, // lambda function that checks if mask is 1
boost_queue // command queue (boost::compute::command_queue object)
);
tensor->storage->wrapper->markDeviceDirty();
// ==== boost compute bit ends ========
// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
// Then copy over the masked elements at their desired output index
// bool status = THClTensor_pointwiseApply3(
// state, contigMask, maskPrefixSum,
// src, TensorMaskedSelectOp(THClTensor_data(state, tensor)));
THClTensor_free(state, contigSrc);
THClTensor_free(state, contigMask);
// THClTensor_free(state, maskPrefixSum);
// THArgCheck(status, 2, CLTORCH_DIM_WARNING);
// THError("Not implemented");
}
void THClTensor_maskedFillByte(THClState* state, THClTensor *tensor, THByteTensor *mask, float value)
{
THAssert(THClTensor_checkGPU(state, 1, tensor));
THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
const int device = tensor->storage->device;
THClTensor* maskCl = THClTensor_newWithSize(state, device, maskSize, NULL);
THLongStorage_free(maskSize);
THClTensor_copyByte(state, maskCl, mask);
THClTensor_maskedFill(state, tensor, maskCl, value);
THClTensor_free(state, maskCl);
}
//void THClTensor_maskedCopyByte(THClState* state, THClTensor *tensor, THByteTensor *mask, THClTensor *src)
//{
// THAssert(THClTensor_checkGPU(state, 2, tensor, src));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedCopy(state, tensor, maskCl, src);
// THClTensor_free(state, maskCl);
//}
void THClTensor_maskedSelectByte(THClState* state, THClTensor *tensor, THClTensor *src, THByteTensor *mask)
{
THAssert(THClTensor_checkGPU(state, 2, tensor, src));
THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
const int device = src->storage->device;
THClTensor* maskCl = THClTensor_newWithSize(state, device, maskSize, NULL);
THLongStorage_free(maskSize);
THClTensor_copyByte(state, maskCl, mask);
THClTensor_maskedSelect(state, tensor, src, maskCl);
THClTensor_free(state, maskCl);
}
<commit_msg>comment out warning<commit_after>// from lib/THC/THCTensorMasked.cu:
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#include <boost/compute/core.hpp>
#include <boost/compute/iterator/buffer_iterator.hpp>
#include <boost/compute/algorithm/reverse.hpp>
#include <boost/compute/algorithm/transform_if.hpp>
#include <boost/compute/lambda.hpp>
#include <boost/compute/iterator/zip_iterator.hpp>
#include "THClTensorMath.h"
#include "THClGeneral.h"
#include "THClBlas.h"
#include "THClTensorCopy.h"
//#include "THClTensorRandom.h"
#include "THClApply.h"
#include "THClReduce.h"
#include <iostream>
using namespace std;
// The largest consecutive integer representable in float32 (2^24)
#define FLOAT32_MAX_CONSECUTIVE_INT 16777216.0f
class TensorMaskedFillOp : public HasOperator2, public HasScalars {
public:
int getNumScalars() const { return 1; }
float getScalar( int index ) const { return value; }
TensorMaskedFillOp(float v) : value(v) {}
std::string operator2() const {
return "if( *in1 != 0.0f ) { *out = val1; }";
}
float value;
};
class TensorMaskedCopyOp : public HasOperator2, public HasGlobalTensors {
public:
TensorMaskedCopyOp(THClTensor *src, THClTensor *baseMask, THClTensor *maskPrefixSum) :
src(src), baseMask(baseMask), maskPrefixSum(maskPrefixSum) {
}
int getNumGlobalTensors() const { return 3; }
THClTensor *getTensor(int index) const {
if(index == 0){ return src; }
if(index == 1){ return baseMask; }
if(index == 2){ return maskPrefixSum; }
THError("index not recognized %i", index);
return 0;
}
std::string getTensorName(int index) const {
if(index == 0){ return "src"; }
if(index == 1){ return "baseMask"; }
if(index == 2){ return "maskPrefixSum"; }
THError("index not recognized %i", index);
return "";
}
std::string operator2() const {
return "if( *in1 != 0.0f ) { *out = src[(int)maskPrefixSum[srcOffset] ]; }";
}
THClTensor *src;
THClTensor *baseMask;
THClTensor *maskPrefixSum;
};
//struct TensorMaskedCopyOp {
// TensorMaskedCopyOp(float* s, float* bm, float* ps)
// : src(s),
// baseMask(bm),
// maskPrefixSum(ps) {
// }
// /*__device__*/ /*__forceline__*/ void operator()(float* out, float* mask) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// // We've already checked that this offset is <= 2^24, so this is ok.
// int srcOffset = (int) (mask - baseMask);
// *out = src[(int) maskPrefixSum[srcOffset]];
// }
// }
// // Where we are copying from
// float* src;
// // The base address of mask so we can calculate offset
// float* baseMask;
// // The index we are copying from
// float* maskPrefixSum;
//};
//class TensorMaskedSelectOp : public HasOperator3, public HasScalars {
//public:
// int getNumScalars() const { return 1; }
// string operator3() const {
// return "if(*out != 0.0f){out[(int)*in1] = *in2; }";
// }
// TensorMaskedSelectOp(float* t) : out(t) {}
// void operator()(float* mask, float* maskPrefixSum, float* in) {
// // Really mask should be `0` or `1` but we can't propagate errors here.
// if (*mask != 0.0f) {
// out[(int) *maskPrefixSum] = *in;
// }
// }
// float* out;
//};
void THClTensor_maskedFill(THClState* state,
THClTensor *tensor, THClTensor *mask, float value)
{
THAssert(THClTensor_checkGPU(state, 2, tensor, mask));
THArgCheck(THClTensor_nElement(state, tensor) ==
THClTensor_nElement(state, mask),
2, "sizes do not match");
TensorMaskedFillOp op(value);
if (!THClTensor_pointwiseApply2(state, tensor, mask, &op)) {
THArgCheck(false, 2, CLTORCH_DIM_WARNING);
}
}
void THClTensor_maskedCopy(THClState* state,
THClTensor *tensor, THClTensor *mask, THClTensor *src)
{
THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
long maskSize = THClTensor_nElement(state, mask);
long tensorSize = THClTensor_nElement(state, tensor);
long srcSize = THClTensor_nElement(state, src);
// Since we are performing a prefix sum of mask, it cannot exceed
// the size allowed in consecutive integers in float32
THArgCheck(maskSize <= (long) FLOAT32_MAX_CONSECUTIVE_INT,
3, "mask nElements exceeds single-precision float "
"consecutive integer precision size (2^24)");
// `mask` and `tensor` must have the same number of elements
THArgCheck(maskSize == tensorSize, 2,
"mask and tensor must have the same number of elements");
THClTensor* contigMask = THClTensor_newContiguous(state, mask);
long oneElements = (long) THClTensor_sumall(state, contigMask);
// The number of `1` elements present in the mask must be <= the
// number of elements available in `src`
if (oneElements > srcSize) {
THClTensor_free(state, contigMask);
THArgCheck(false, 2, "source nElements must be == mask `1` elements");
}
// Use a prefix sum to determine the copy locations of the masked elements
THClTensor* maskPrefixSum = THClTensor_newv2(state, src->storage->device);
THClTensor_resizeAs(state, maskPrefixSum, contigMask);
// We are getting elements from `src` based on an offset from
// `maskPrefixSum`, so that should be made contiguous too
THClTensor* contigSrc = THClTensor_newContiguous(state, src);
// TensorAddOp cumOp;
// THAssert(THClTensor_checkGPU(state, 2, maskData, maskPrefixSumData));
// THClTensor_scanDim(state, maskPrefixSumData, maskData, dimension, 0.0f, &cumOp);
// hmmmm: this is scanDim, but what we really need is somsething like: scanAll
// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
THError("Not implemented");
// update `tensor` where `mask` == 1 but pull from `src` at
// maskPrefixSum
TensorMaskedCopyOp maskedCopyOp(
contigSrc, contigMask, maskPrefixSum);
bool status = THClTensor_pointwiseApply2(
state, tensor, contigMask, &maskedCopyOp);
THError("Not implemented");
THClTensor_free(state, contigSrc);
THClTensor_free(state, maskPrefixSum);
THClTensor_free(state, contigMask);
THArgCheck(status, 2, CLTORCH_DIM_WARNING);
THError("Not implemented");
}
void THClTensor_maskedSelect(THClState* state,
THClTensor *tensor, THClTensor *src, THClTensor *mask)
{
THAssert(THClTensor_checkGPU(state, 3, tensor, src, mask));
THArgCheck(THClTensor_nElement(state, mask) == THClTensor_nElement(state, src),
2, "sizes do not match");
// Since we are performing a prefix sum of mask, it cannot exceed
// the size allowed in consecutive integers in float32
// THArgCheck(THClTensor_nElement(state, mask) <=
// (long) FLOAT32_MAX_CONSECUTIVE_INT,
// 3, "mask nElements exceeds single-precision float "
// "consecutive integer precision size (2^24)");
THClTensor* contigSrc = THClTensor_newContiguous(state, src);
// Determine our output size
THClTensor* contigMask = THClTensor_newContiguous(state, mask);
long totalElements = (long) THClTensor_sumall(state, contigMask);
cout << "totalElements " << totalElements << endl;
// This should be contiguous already, so no need to make it contig
// for the apply kernel
THClTensor_resize1d(state, tensor, totalElements);
// Use a prefix sum to determine the output locations of the masked elements
// THClTensor* maskPrefixSum = THClTensor_new(state);
// THClTensor_resizeAs(state, maskPrefixSum, contigMask);
// ==== boost compute bit starts ========
EasyCL *cl = src->storage->cl;
boost::compute::context boost_context(*cl->context);
boost::compute::command_queue boost_queue(*cl->queue);
boost::compute::buffer boostData(*contigSrc->storage->wrapper->getDeviceArray());
boost::compute::buffer boostMask(*contigMask->storage->wrapper->getDeviceArray());
boost::compute::buffer boostOut(*tensor->storage->wrapper->getDeviceArray());
transform_if(
make_zip_iterator(
boost::make_tuple(
boost::compute::make_buffer_iterator<float>(boostData, 0),
boost::compute::make_buffer_iterator<float>(boostMask, 0)
)
),
make_zip_iterator(
boost::make_tuple(
boost::compute::make_buffer_iterator<float>(boostData, THClTensor_nElement(state, mask)),
boost::compute::make_buffer_iterator<float>(boostMask, THClTensor_nElement(state, mask))
)
),
boost::compute::make_buffer_iterator<float>(boostOut, 0),
boost::compute::get<0>(), // function that return input value
boost::compute::lambda::get<1>(boost::compute::_1) == 1, // lambda function that checks if mask is 1
boost_queue // command queue (boost::compute::command_queue object)
);
tensor->storage->wrapper->markDeviceDirty();
// ==== boost compute bit ends ========
// thrust::device_ptr<float>
// maskData(THClTensor_data(state, contigMask));
// thrust::device_ptr<float>
// maskPrefixSumData(THClTensor_data(state, maskPrefixSum));
// thrust::exclusive_scan(maskData,
// maskData + THClTensor_nElement(state, contigMask),
// maskPrefixSumData);
// Then copy over the masked elements at their desired output index
// bool status = THClTensor_pointwiseApply3(
// state, contigMask, maskPrefixSum,
// src, TensorMaskedSelectOp(THClTensor_data(state, tensor)));
THClTensor_free(state, contigSrc);
THClTensor_free(state, contigMask);
// THClTensor_free(state, maskPrefixSum);
// THArgCheck(status, 2, CLTORCH_DIM_WARNING);
// THError("Not implemented");
}
void THClTensor_maskedFillByte(THClState* state, THClTensor *tensor, THByteTensor *mask, float value)
{
THAssert(THClTensor_checkGPU(state, 1, tensor));
THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
const int device = tensor->storage->device;
THClTensor* maskCl = THClTensor_newWithSize(state, device, maskSize, NULL);
THLongStorage_free(maskSize);
THClTensor_copyByte(state, maskCl, mask);
THClTensor_maskedFill(state, tensor, maskCl, value);
THClTensor_free(state, maskCl);
}
//void THClTensor_maskedCopyByte(THClState* state, THClTensor *tensor, THByteTensor *mask, THClTensor *src)
//{
// THAssert(THClTensor_checkGPU(state, 2, tensor, src));
// THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
// THClTensor* maskCl = THClTensor_newWithSize(state, maskSize, NULL);
// THLongStorage_free(maskSize);
// THClTensor_copyByte(state, maskCl, mask);
// THClTensor_maskedCopy(state, tensor, maskCl, src);
// THClTensor_free(state, maskCl);
//}
void THClTensor_maskedSelectByte(THClState* state, THClTensor *tensor, THClTensor *src, THByteTensor *mask)
{
THAssert(THClTensor_checkGPU(state, 2, tensor, src));
THLongStorage* maskSize = THByteTensor_newSizeOf(mask);
const int device = src->storage->device;
THClTensor* maskCl = THClTensor_newWithSize(state, device, maskSize, NULL);
THLongStorage_free(maskSize);
THClTensor_copyByte(state, maskCl, mask);
THClTensor_maskedSelect(state, tensor, src, maskCl);
THClTensor_free(state, maskCl);
}
<|endoftext|>
|
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Sergey Lisitsyn
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include "lib/arpack.h"
#ifdef HAVE_ARPACK
#ifdef HAVE_ATLAS
#include "lib/config.h"
#include <cblas.h>
#include "lib/lapack.h"
#include "lib/common.h"
#include "lib/io.h"
#include <string.h>
using namespace shogun;
namespace shogun
{
void arpack_dsaupd(double* matrix, int n, int nev, const char* which,
int mode, double shift, double* eigenvalues,
double* eigenvectors, int& status)
{
// check if nev is greater than n
if (nev>n)
SG_SERROR("Number of required eigenpairs is greater than order of the matrix");
// check specified mode
if (mode!=1 && mode!=3)
SG_SERROR("Unknown mode specified");
// init ARPACK's reverse communication parameter
// (should be zero initially)
int ido = 0;
// specify that non-general eigenproblem will be solved
// (Ax=lGx, where G=I)
char bmat[2] = "I";
// init tolerance (zero means machine precision)
double tol = 0.0;
// allocate array to hold residuals
double* resid = new double[n];
// set number of Lanczos basis vectors to be used
// (with max(4*nev,n) sufficient for most tasks)
int ncv = nev*4>n ? n : nev*4;
// allocate array 'v' for dsaupd routine usage
int ldv = n;
double* v = new double[ldv*ncv];
// init array for i/o params for routine
int* iparam = new int[11];
// specify method for selecting implicit shifts (1 - exact shifts)
iparam[0] = 1;
// specify max number of iterations
iparam[2] = 3*n;
// set the computation mode (1 for regular or 3 for shift-inverse)
iparam[6] = mode;
// init array indicating locations of vectors for routine callback
int* ipntr = new int[11];
// allocate workaround arrays
double* workd = new double[3*n];
int lworkl = ncv*(ncv+8);
double* workl = new double[lworkl];
// init info holding status (should be zero at first call)
int info = 0;
// which eigenpairs to find
char* which_ = strdup(which);
// All
char* all_ = strdup("All");
// main computation loop
// shift-invert mode
if (mode==3)
{
double* workt = new double[n];
int* ipiv = new int[n];
for (int i=0; i<n; i++)
matrix[i*n+i] -= shift;
// cholesky inverse
clapack_dpotri(CblasColMajor,CblasUpper,n,matrix,n);
do
{
dsaupd_(&ido, bmat, &n, which_, &nev, &tol, resid,
&ncv, v, &ldv, iparam, ipntr, workd, workl,
&lworkl, &info);
if ((ido==1)||(ido==-1))
{
// symmetrical matvec
cblas_dsymv(CblasColMajor,CblasUpper,
n,1.0,matrix,n,
workd+ipntr[0]-1,1,
0.0, workd+ipntr[1]-1,1);
}
} while ((ido==1)||(ido==-1));
delete[] workt;
delete[] ipiv;
}
// regular mode
if (mode==1)
{
do
{
dsaupd_(&ido, bmat, &n, which_, &nev, &tol, resid,
&ncv, v, &ldv, iparam, ipntr, workd, workl,
&lworkl, &info);
if ((ido==1)||(ido==-1))
{
// general matvec
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
n, 1, n,
1.0, matrix, n,
(workd+ipntr[0]-1), n,
0.0, (workd+ipntr[1]-1), n);
}
} while ((ido==1)||(ido==-1));
}
// check if DSAUPD failed
if (info<0)
{
if ((info<=-1)&&(info>=-6))
SG_SWARNING("DSAUPD failed. Wrong parameter passed.");
else if (info==-7)
SG_SWARNING("DSAUPD failed. Workaround array size is not sufficient.");
else
SG_SWARNING("DSAUPD failed. Error code: %d.", info);
status = -1;
}
else
{
SG_SDEBUG("DSAUPD finished. Taken %d iterations.\n", iparam[2]);
if (info==1)
SG_SDEBUG("Maximum number of iterations reached.\n");
// allocate select for dseupd
int* select = new int[ncv];
// allocate d to hold eigenvalues
double* d = new double[2*ncv];
// sigma for dseupd
double sigma;
// init ierr indicating dseupd possible errors
int ierr = 0;
// specify that eigenvectors to be computed too
int rvec = 1;
dseupd_(&rvec, all_, select, d, v, &ldv, &sigma, bmat,
&n, which_, &nev, &tol, resid, &ncv, v, &ldv,
iparam, ipntr, workd, workl, &lworkl, &ierr);
if (ierr!=0)
{
SG_SWARNING("DSEUPD failed with status=%d", ierr);
status = -1;
}
else
{
for (int i=0; i<nev; i++)
{
eigenvalues[i] = d[i];
for (int j=0; j<n; j++)
eigenvectors[j*nev+i] = v[i*n+j];
}
}
// cleanup
delete[] select;
delete[] d;
}
// cleanup
delete[] all_;
delete[] which_;
delete[] resid;
delete[] v;
delete[] iparam;
delete[] ipntr;
delete[] workd;
delete[] workl;
};
}
#endif /* HAVE_ATLAS */
#endif /* HAVE_ARPACK */
<commit_msg>Removed junk at arpack wrapper<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2011 Sergey Lisitsyn
* Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
*/
#include "lib/arpack.h"
#ifdef HAVE_ARPACK
#ifdef HAVE_ATLAS
#include "lib/config.h"
#include <cblas.h>
#include "lib/lapack.h"
#include "lib/common.h"
#include "lib/io.h"
#include <string.h>
using namespace shogun;
namespace shogun
{
void arpack_dsaupd(double* matrix, int n, int nev, const char* which,
int mode, double shift, double* eigenvalues,
double* eigenvectors, int& status)
{
// check if nev is greater than n
if (nev>n)
SG_SERROR("Number of required eigenpairs is greater than order of the matrix");
// check specified mode
if (mode!=1 && mode!=3)
SG_SERROR("Unknown mode specified");
// init ARPACK's reverse communication parameter
// (should be zero initially)
int ido = 0;
// specify that non-general eigenproblem will be solved
// (Ax=lGx, where G=I)
char bmat[2] = "I";
// init tolerance (zero means machine precision)
double tol = 0.0;
// allocate array to hold residuals
double* resid = new double[n];
// set number of Lanczos basis vectors to be used
// (with max(4*nev,n) sufficient for most tasks)
int ncv = nev*4>n ? n : nev*4;
// allocate array 'v' for dsaupd routine usage
int ldv = n;
double* v = new double[ldv*ncv];
// init array for i/o params for routine
int* iparam = new int[11];
// specify method for selecting implicit shifts (1 - exact shifts)
iparam[0] = 1;
// specify max number of iterations
iparam[2] = 3*n;
// set the computation mode (1 for regular or 3 for shift-inverse)
iparam[6] = mode;
// init array indicating locations of vectors for routine callback
int* ipntr = new int[11];
// allocate workaround arrays
double* workd = new double[3*n];
int lworkl = ncv*(ncv+8);
double* workl = new double[lworkl];
// init info holding status (should be zero at first call)
int info = 0;
// which eigenpairs to find
char* which_ = strdup(which);
// All
char* all_ = strdup("All");
// main computation loop
// shift-invert mode
if (mode==3)
{
for (int i=0; i<n; i++)
matrix[i*n+i] -= shift;
// cholesky inverse
clapack_dpotri(CblasColMajor,CblasUpper,n,matrix,n);
do
{
dsaupd_(&ido, bmat, &n, which_, &nev, &tol, resid,
&ncv, v, &ldv, iparam, ipntr, workd, workl,
&lworkl, &info);
if ((ido==1)||(ido==-1))
{
// symmetrical matvec
cblas_dsymv(CblasColMajor,CblasUpper,
n,1.0,matrix,n,
workd+ipntr[0]-1,1,
0.0, workd+ipntr[1]-1,1);
}
} while ((ido==1)||(ido==-1));
}
// regular mode
if (mode==1)
{
do
{
dsaupd_(&ido, bmat, &n, which_, &nev, &tol, resid,
&ncv, v, &ldv, iparam, ipntr, workd, workl,
&lworkl, &info);
if ((ido==1)||(ido==-1))
{
// general matvec
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
n, 1, n,
1.0, matrix, n,
(workd+ipntr[0]-1), n,
0.0, (workd+ipntr[1]-1), n);
}
} while ((ido==1)||(ido==-1));
}
// check if DSAUPD failed
if (info<0)
{
if ((info<=-1)&&(info>=-6))
SG_SWARNING("DSAUPD failed. Wrong parameter passed.");
else if (info==-7)
SG_SWARNING("DSAUPD failed. Workaround array size is not sufficient.");
else
SG_SWARNING("DSAUPD failed. Error code: %d.", info);
status = -1;
}
else
{
SG_SDEBUG("DSAUPD finished. Taken %d iterations.\n", iparam[2]);
if (info==1)
SG_SDEBUG("Maximum number of iterations reached.\n");
// allocate select for dseupd
int* select = new int[ncv];
// allocate d to hold eigenvalues
double* d = new double[2*ncv];
// sigma for dseupd
double sigma;
// init ierr indicating dseupd possible errors
int ierr = 0;
// specify that eigenvectors to be computed too
int rvec = 1;
dseupd_(&rvec, all_, select, d, v, &ldv, &sigma, bmat,
&n, which_, &nev, &tol, resid, &ncv, v, &ldv,
iparam, ipntr, workd, workl, &lworkl, &ierr);
if (ierr!=0)
{
SG_SWARNING("DSEUPD failed with status=%d", ierr);
status = -1;
}
else
{
for (int i=0; i<nev; i++)
{
eigenvalues[i] = d[i];
for (int j=0; j<n; j++)
eigenvectors[j*nev+i] = v[i*n+j];
}
}
// cleanup
delete[] select;
delete[] d;
}
// cleanup
delete[] all_;
delete[] which_;
delete[] resid;
delete[] v;
delete[] iparam;
delete[] ipntr;
delete[] workd;
delete[] workl;
};
}
#endif /* HAVE_ATLAS */
#endif /* HAVE_ARPACK */
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "fnord-msg/MessageBuilder.h"
#include "fnord-msg/MessageObject.h"
#include "fnord-msg/MessageEncoder.h"
#include "fnord-msg/MessageDecoder.h"
#include "fnord-msg/MessagePrinter.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "logjoin/LogJoinTarget.h"
#include "common.h"
using namespace fnord;
namespace cm {
LogJoinTarget::LogJoinTarget(
const msg::MessageSchema& joined_sessions_schema,
bool dry_run) :
joined_sessions_schema_(joined_sessions_schema),
dry_run_(dry_run),
num_sessions(0),
cconv_(currencyConversionTable()) {}
void LogJoinTarget::setNormalize(
Function<fnord::String (Language lang, const fnord::String& query)> normalizeCb) {
normalize_ = normalizeCb;
}
void LogJoinTarget::setGetField(
Function<Option<String> (const DocID& docid, const String& feature)> getFieldCb) {
get_field_ = getFieldCb;
}
Buffer LogJoinTarget::trackedSessionToJoinedSession(TrackedSession& session) {
if (!get_field_) {
RAISE(kRuntimeError, "getField has not been initialized");
}
if (!normalize_) {
RAISE(kRuntimeError, "normalize has not been initialized");
}
session.joinEvents(cconv_);
const auto& schema = joined_sessions_schema_;
msg::MessageObject obj;
for (const auto& ci : session.cart_items) {
auto& ci_obj = obj.addChild(schema.id("cart_items"));
ci_obj.addChild(
schema.id("cart_items.time"),
(uint32_t) (ci.time.unixMicros() / kMicrosPerSecond));
ci_obj.addChild(
schema.id("cart_items.item_id"),
ci.item.docID().docid);
ci_obj.addChild(
schema.id("cart_items.quantity"),
ci.quantity);
ci_obj.addChild(
schema.id("cart_items.price_cents"),
ci.price_cents);
ci_obj.addChild(
schema.id("cart_items.currency"),
(uint32_t) currencyFromString(ci.currency));
ci_obj.addChild(
schema.id("cart_items.checkout_step"),
ci.checkout_step);
// FIXPAUL use getFields...
auto docid = ci.item.docID();
auto shopid = get_field_(docid, "shop_id");
if (shopid.isEmpty()) {
fnord::logWarning(
"cm.logjoin",
"item not found in featureindex: $0",
docid.docid);
} else {
ci_obj.addChild(
schema.id("cart_items.shop_id"),
(uint32_t) std::stoull(shopid.get()));
}
auto category1 = get_field_(docid, "category1");
if (!category1.isEmpty()) {
ci_obj.addChild(
schema.id("cart_items.category1"),
(uint32_t) std::stoull(category1.get()));
}
auto category2 = get_field_(docid, "category2");
if (!category2.isEmpty()) {
ci_obj.addChild(
schema.id("cart_items.category2"),
(uint32_t) std::stoull(category2.get()));
}
auto category3 = get_field_(docid, "category3");
if (!category3.isEmpty()) {
ci_obj.addChild(
schema.id("cart_items.category3"),
(uint32_t) std::stoull(category3.get()));
}
}
uint32_t sess_abgrp = 0;
for (const auto& q : session.queries) {
auto& qry_obj = obj.addChild(schema.id("search_queries"));
/* queries.time */
qry_obj.addChild(
schema.id("search_queries.time"),
(uint32_t) (q.time.unixMicros() / kMicrosPerSecond));
/* queries.language */
auto lang = cm::extractLanguage(q.attrs);
qry_obj.addChild(schema.id("search_queries.language"), (uint32_t) lang);
/* queries.query_string */
auto qstr = cm::extractQueryString(q.attrs);
if (!qstr.isEmpty()) {
auto qstr_norm = normalize_(lang, qstr.get());
qry_obj.addChild(schema.id("search_queries.query_string"), qstr.get());
qry_obj.addChild(schema.id("search_queries.query_string_normalized"), qstr_norm);
}
/* queries.shopid */
auto slrid = cm::extractAttr(q.attrs, "slrid");
if (!slrid.isEmpty()) {
uint32_t sid = std::stoul(slrid.get());
qry_obj.addChild(schema.id("search_queries.shop_id"), sid);
}
qry_obj.addChild(schema.id("search_queries.num_result_items"), q.nitems);
qry_obj.addChild(schema.id("search_queries.num_result_items_clicked"), q.nclicks);
qry_obj.addChild(schema.id("search_queries.num_ad_impressions"), q.nads);
qry_obj.addChild(schema.id("search_queries.num_ad_clicks"), q.nadclicks);
qry_obj.addChild(schema.id("search_queries.num_cart_items"), q.num_cart_items);
qry_obj.addChild(schema.id("search_queries.cart_value_eurcents"), q.cart_value_eurcents);
qry_obj.addChild(schema.id("search_queries.num_order_items"), q.num_order_items);
qry_obj.addChild(schema.id("search_queries.gmv_eurcents"), q.gmv_eurcents);
/* queries.page */
auto pg_str = cm::extractAttr(q.attrs, "pg");
if (!pg_str.isEmpty()) {
uint32_t pg = std::stoul(pg_str.get());
qry_obj.addChild(schema.id("search_queries.page"), pg);
}
/* queries.ab_test_group */
auto abgrp = cm::extractABTestGroup(q.attrs);
if (!abgrp.isEmpty()) {
sess_abgrp = abgrp.get();
qry_obj.addChild(schema.id("search_queries.ab_test_group"), abgrp.get());
}
/* queries.experiments */
auto qexps = q.joinedExperiments();
if (qexps.size() > 0) {
qry_obj.addChild(schema.id("search_queries.experiments"), qexps);
}
/* queries.category1 */
auto qcat1 = cm::extractAttr(q.attrs, "q_cat1");
if (!qcat1.isEmpty()) {
uint32_t c = std::stoul(qcat1.get());
qry_obj.addChild(schema.id("search_queries.category1"), c);
}
/* queries.category1 */
auto qcat2 = cm::extractAttr(q.attrs, "q_cat2");
if (!qcat2.isEmpty()) {
uint32_t c = std::stoul(qcat2.get());
qry_obj.addChild(schema.id("search_queries.category2"), c);
}
/* queries.category1 */
auto qcat3 = cm::extractAttr(q.attrs, "q_cat3");
if (!qcat3.isEmpty()) {
uint32_t c = std::stoul(qcat3.get());
qry_obj.addChild(schema.id("search_queries.category3"), c);
}
/* queries.device_type */
qry_obj.addChild(
schema.id("search_queries.device_type"),
(uint32_t) extractDeviceType(q.attrs));
/* queries.page_type */
qry_obj.addChild(
schema.id("search_queries.page_type"),
(uint32_t) extractPageType(q.attrs));
for (const auto& item : q.items) {
auto& item_obj = qry_obj.addChild(
schema.id("search_queries.result_items"));
item_obj.addChild(
schema.id("search_queries.result_items.position"),
(uint32_t) item.position);
item_obj.addChild(
schema.id("search_queries.result_items.item_id"),
item.item.docID().docid);
if (item.clicked) {
item_obj.addChild(
schema.id("search_queries.result_items.clicked"),
msg::TRUE);
} else {
item_obj.addChild(
schema.id("search_queries.result_items.clicked"),
msg::FALSE);
}
auto docid = item.item.docID();
auto shopid = get_field_(docid, "shop_id");
if (shopid.isEmpty()) {
fnord::logWarning(
"cm.logjoin",
"item not found in featureindex: $0",
docid.docid);
} else {
item_obj.addChild(
schema.id("search_queries.result_items.shop_id"),
(uint32_t) std::stoull(shopid.get()));
}
auto category1 = get_field_(docid, "category1");
if (!category1.isEmpty()) {
item_obj.addChild(
schema.id("search_queries.result_items.category1"),
(uint32_t) std::stoull(category1.get()));
}
auto category2 = get_field_(docid, "category2");
if (!category2.isEmpty()) {
item_obj.addChild(
schema.id("search_queries.result_items.category2"),
(uint32_t) std::stoull(category2.get()));
}
auto category3 = get_field_(docid, "category3");
if (!category3.isEmpty()) {
item_obj.addChild(
schema.id("search_queries.result_items.category3"),
(uint32_t) std::stoull(category3.get()));
}
}
}
for (const auto& iv : session.item_visits) {
auto& iv_obj = obj.addChild(schema.id("item_visits"));
iv_obj.addChild(
schema.id("item_visits.time"),
(uint32_t) (iv.time.unixMicros() / kMicrosPerSecond));
iv_obj.addChild(
schema.id("item_visits.item_id"),
iv.item.docID().docid);
auto docid = iv.item.docID();
auto shopid = get_field_(docid, "shop_id");
if (shopid.isEmpty()) {
fnord::logWarning(
"cm.logjoin",
"item not found in featureindex: $0",
docid.docid);
} else {
iv_obj.addChild(
schema.id("item_visits.shop_id"),
(uint32_t) std::stoull(shopid.get()));
}
auto category1 = get_field_(docid, "category1");
if (!category1.isEmpty()) {
iv_obj.addChild(
schema.id("item_visits.category1"),
(uint32_t) std::stoull(category1.get()));
}
auto category2 = get_field_(docid, "category2");
if (!category2.isEmpty()) {
iv_obj.addChild(
schema.id("item_visits.category2"),
(uint32_t) std::stoull(category2.get()));
}
auto category3 = get_field_(docid, "category3");
if (!category3.isEmpty()) {
iv_obj.addChild(
schema.id("item_visits.category3"),
(uint32_t) std::stoull(category3.get()));
}
}
if (sess_abgrp > 0) {
obj.addChild(schema.id("ab_test_group"), sess_abgrp);
}
auto exps = session.joinedExperiments();
if (exps.size() > 0) {
obj.addChild(schema.id("experiments"), exps);
}
if (!session.referrer_url.isEmpty()) {
obj.addChild(schema.id("referrer_url"), session.referrer_url.get());
}
if (!session.referrer_campaign.isEmpty()) {
obj.addChild(schema.id("referrer_campaign"), session.referrer_campaign.get());
}
if (!session.referrer_name.isEmpty()) {
obj.addChild(schema.id("referrer_name"), session.referrer_name.get());
}
obj.addChild(schema.id("num_cart_items"), session.num_cart_items);
obj.addChild(schema.id("cart_value_eurcents"), session.cart_value_eurcents);
obj.addChild(schema.id("num_order_items"), session.num_order_items);
obj.addChild(schema.id("gmv_eurcents"), session.gmv_eurcents);
Buffer msg_buf;
auto first_seen = session.firstSeenTime();
auto last_seen = session.lastSeenTime();
if (first_seen.isEmpty() || last_seen.isEmpty()) {
RAISE(kRuntimeError, "session: time isn't set");
}
obj.addChild(
schema.id("first_seen_time"),
first_seen.get().unixMicros() / kMicrosPerSecond);
obj.addChild(
schema.id("last_seen_time"),
last_seen.get().unixMicros() / kMicrosPerSecond);
msg::MessageEncoder::encode(obj, joined_sessions_schema_, &msg_buf);
return msg_buf;
}
void LogJoinTarget::onSession(
mdb::MDBTransaction* txn,
TrackedSession& session) {
Buffer msg_buf = trackedSessionToJoinedSession(session);
if (dry_run_) {
fnord::logInfo(
"cm.logjoin",
"[DRYRUN] not uploading session: ", 1);
//msg::MessagePrinter::print(obj, joined_sessions_schema_));
} else {
auto first_seen = session.firstSeenTime();
auto time = first_seen.get().unixMicros();
util::BinaryMessageWriter buf;
buf.appendUInt64(time);
buf.appendUInt64(rnd_.random64());
buf.appendVarUInt(msg_buf.size());
buf.append(msg_buf.data(), msg_buf.size());
auto key = StringUtil::format("__uploadq-sessions-$0", rnd_.hex128());
txn->update(key.data(), key.size(), buf.data(), buf.size());
}
++num_sessions;
}
} // namespace cm
<commit_msg>write customer key in logjointarget<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "fnord-msg/MessageBuilder.h"
#include "fnord-msg/MessageObject.h"
#include "fnord-msg/MessageEncoder.h"
#include "fnord-msg/MessageDecoder.h"
#include "fnord-msg/MessagePrinter.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "logjoin/LogJoinTarget.h"
#include "common.h"
using namespace fnord;
namespace cm {
LogJoinTarget::LogJoinTarget(
const msg::MessageSchema& joined_sessions_schema,
bool dry_run) :
joined_sessions_schema_(joined_sessions_schema),
dry_run_(dry_run),
num_sessions(0),
cconv_(currencyConversionTable()) {}
void LogJoinTarget::setNormalize(
Function<fnord::String (Language lang, const fnord::String& query)> normalizeCb) {
normalize_ = normalizeCb;
}
void LogJoinTarget::setGetField(
Function<Option<String> (const DocID& docid, const String& feature)> getFieldCb) {
get_field_ = getFieldCb;
}
Buffer LogJoinTarget::trackedSessionToJoinedSession(TrackedSession& session) {
if (!get_field_) {
RAISE(kRuntimeError, "getField has not been initialized");
}
if (!normalize_) {
RAISE(kRuntimeError, "normalize has not been initialized");
}
session.joinEvents(cconv_);
const auto& schema = joined_sessions_schema_;
msg::MessageObject obj;
for (const auto& ci : session.cart_items) {
auto& ci_obj = obj.addChild(schema.id("cart_items"));
ci_obj.addChild(
schema.id("cart_items.time"),
(uint32_t) (ci.time.unixMicros() / kMicrosPerSecond));
ci_obj.addChild(
schema.id("cart_items.item_id"),
ci.item.docID().docid);
ci_obj.addChild(
schema.id("cart_items.quantity"),
ci.quantity);
ci_obj.addChild(
schema.id("cart_items.price_cents"),
ci.price_cents);
ci_obj.addChild(
schema.id("cart_items.currency"),
(uint32_t) currencyFromString(ci.currency));
ci_obj.addChild(
schema.id("cart_items.checkout_step"),
ci.checkout_step);
// FIXPAUL use getFields...
auto docid = ci.item.docID();
auto shopid = get_field_(docid, "shop_id");
if (shopid.isEmpty()) {
fnord::logWarning(
"cm.logjoin",
"item not found in featureindex: $0",
docid.docid);
} else {
ci_obj.addChild(
schema.id("cart_items.shop_id"),
(uint32_t) std::stoull(shopid.get()));
}
auto category1 = get_field_(docid, "category1");
if (!category1.isEmpty()) {
ci_obj.addChild(
schema.id("cart_items.category1"),
(uint32_t) std::stoull(category1.get()));
}
auto category2 = get_field_(docid, "category2");
if (!category2.isEmpty()) {
ci_obj.addChild(
schema.id("cart_items.category2"),
(uint32_t) std::stoull(category2.get()));
}
auto category3 = get_field_(docid, "category3");
if (!category3.isEmpty()) {
ci_obj.addChild(
schema.id("cart_items.category3"),
(uint32_t) std::stoull(category3.get()));
}
}
uint32_t sess_abgrp = 0;
for (const auto& q : session.queries) {
auto& qry_obj = obj.addChild(schema.id("search_queries"));
/* queries.time */
qry_obj.addChild(
schema.id("search_queries.time"),
(uint32_t) (q.time.unixMicros() / kMicrosPerSecond));
/* queries.language */
auto lang = cm::extractLanguage(q.attrs);
qry_obj.addChild(schema.id("search_queries.language"), (uint32_t) lang);
/* queries.query_string */
auto qstr = cm::extractQueryString(q.attrs);
if (!qstr.isEmpty()) {
auto qstr_norm = normalize_(lang, qstr.get());
qry_obj.addChild(schema.id("search_queries.query_string"), qstr.get());
qry_obj.addChild(schema.id("search_queries.query_string_normalized"), qstr_norm);
}
/* queries.shopid */
auto slrid = cm::extractAttr(q.attrs, "slrid");
if (!slrid.isEmpty()) {
uint32_t sid = std::stoul(slrid.get());
qry_obj.addChild(schema.id("search_queries.shop_id"), sid);
}
qry_obj.addChild(schema.id("search_queries.num_result_items"), q.nitems);
qry_obj.addChild(schema.id("search_queries.num_result_items_clicked"), q.nclicks);
qry_obj.addChild(schema.id("search_queries.num_ad_impressions"), q.nads);
qry_obj.addChild(schema.id("search_queries.num_ad_clicks"), q.nadclicks);
qry_obj.addChild(schema.id("search_queries.num_cart_items"), q.num_cart_items);
qry_obj.addChild(schema.id("search_queries.cart_value_eurcents"), q.cart_value_eurcents);
qry_obj.addChild(schema.id("search_queries.num_order_items"), q.num_order_items);
qry_obj.addChild(schema.id("search_queries.gmv_eurcents"), q.gmv_eurcents);
/* queries.page */
auto pg_str = cm::extractAttr(q.attrs, "pg");
if (!pg_str.isEmpty()) {
uint32_t pg = std::stoul(pg_str.get());
qry_obj.addChild(schema.id("search_queries.page"), pg);
}
/* queries.ab_test_group */
auto abgrp = cm::extractABTestGroup(q.attrs);
if (!abgrp.isEmpty()) {
sess_abgrp = abgrp.get();
qry_obj.addChild(schema.id("search_queries.ab_test_group"), abgrp.get());
}
/* queries.experiments */
auto qexps = q.joinedExperiments();
if (qexps.size() > 0) {
qry_obj.addChild(schema.id("search_queries.experiments"), qexps);
}
/* queries.category1 */
auto qcat1 = cm::extractAttr(q.attrs, "q_cat1");
if (!qcat1.isEmpty()) {
uint32_t c = std::stoul(qcat1.get());
qry_obj.addChild(schema.id("search_queries.category1"), c);
}
/* queries.category1 */
auto qcat2 = cm::extractAttr(q.attrs, "q_cat2");
if (!qcat2.isEmpty()) {
uint32_t c = std::stoul(qcat2.get());
qry_obj.addChild(schema.id("search_queries.category2"), c);
}
/* queries.category1 */
auto qcat3 = cm::extractAttr(q.attrs, "q_cat3");
if (!qcat3.isEmpty()) {
uint32_t c = std::stoul(qcat3.get());
qry_obj.addChild(schema.id("search_queries.category3"), c);
}
/* queries.device_type */
qry_obj.addChild(
schema.id("search_queries.device_type"),
(uint32_t) extractDeviceType(q.attrs));
/* queries.page_type */
qry_obj.addChild(
schema.id("search_queries.page_type"),
(uint32_t) extractPageType(q.attrs));
for (const auto& item : q.items) {
auto& item_obj = qry_obj.addChild(
schema.id("search_queries.result_items"));
item_obj.addChild(
schema.id("search_queries.result_items.position"),
(uint32_t) item.position);
item_obj.addChild(
schema.id("search_queries.result_items.item_id"),
item.item.docID().docid);
if (item.clicked) {
item_obj.addChild(
schema.id("search_queries.result_items.clicked"),
msg::TRUE);
} else {
item_obj.addChild(
schema.id("search_queries.result_items.clicked"),
msg::FALSE);
}
auto docid = item.item.docID();
auto shopid = get_field_(docid, "shop_id");
if (shopid.isEmpty()) {
fnord::logWarning(
"cm.logjoin",
"item not found in featureindex: $0",
docid.docid);
} else {
item_obj.addChild(
schema.id("search_queries.result_items.shop_id"),
(uint32_t) std::stoull(shopid.get()));
}
auto category1 = get_field_(docid, "category1");
if (!category1.isEmpty()) {
item_obj.addChild(
schema.id("search_queries.result_items.category1"),
(uint32_t) std::stoull(category1.get()));
}
auto category2 = get_field_(docid, "category2");
if (!category2.isEmpty()) {
item_obj.addChild(
schema.id("search_queries.result_items.category2"),
(uint32_t) std::stoull(category2.get()));
}
auto category3 = get_field_(docid, "category3");
if (!category3.isEmpty()) {
item_obj.addChild(
schema.id("search_queries.result_items.category3"),
(uint32_t) std::stoull(category3.get()));
}
}
}
for (const auto& iv : session.item_visits) {
auto& iv_obj = obj.addChild(schema.id("item_visits"));
iv_obj.addChild(
schema.id("item_visits.time"),
(uint32_t) (iv.time.unixMicros() / kMicrosPerSecond));
iv_obj.addChild(
schema.id("item_visits.item_id"),
iv.item.docID().docid);
auto docid = iv.item.docID();
auto shopid = get_field_(docid, "shop_id");
if (shopid.isEmpty()) {
fnord::logWarning(
"cm.logjoin",
"item not found in featureindex: $0",
docid.docid);
} else {
iv_obj.addChild(
schema.id("item_visits.shop_id"),
(uint32_t) std::stoull(shopid.get()));
}
auto category1 = get_field_(docid, "category1");
if (!category1.isEmpty()) {
iv_obj.addChild(
schema.id("item_visits.category1"),
(uint32_t) std::stoull(category1.get()));
}
auto category2 = get_field_(docid, "category2");
if (!category2.isEmpty()) {
iv_obj.addChild(
schema.id("item_visits.category2"),
(uint32_t) std::stoull(category2.get()));
}
auto category3 = get_field_(docid, "category3");
if (!category3.isEmpty()) {
iv_obj.addChild(
schema.id("item_visits.category3"),
(uint32_t) std::stoull(category3.get()));
}
}
if (sess_abgrp > 0) {
obj.addChild(schema.id("ab_test_group"), sess_abgrp);
}
auto exps = session.joinedExperiments();
if (exps.size() > 0) {
obj.addChild(schema.id("experiments"), exps);
}
if (!session.referrer_url.isEmpty()) {
obj.addChild(schema.id("referrer_url"), session.referrer_url.get());
}
if (!session.referrer_campaign.isEmpty()) {
obj.addChild(schema.id("referrer_campaign"), session.referrer_campaign.get());
}
if (!session.referrer_name.isEmpty()) {
obj.addChild(schema.id("referrer_name"), session.referrer_name.get());
}
obj.addChild(schema.id("num_cart_items"), session.num_cart_items);
obj.addChild(schema.id("cart_value_eurcents"), session.cart_value_eurcents);
obj.addChild(schema.id("num_order_items"), session.num_order_items);
obj.addChild(schema.id("gmv_eurcents"), session.gmv_eurcents);
obj.addChild(schema.id("customer"), session.customer_key);
Buffer msg_buf;
auto first_seen = session.firstSeenTime();
auto last_seen = session.lastSeenTime();
if (first_seen.isEmpty() || last_seen.isEmpty()) {
RAISE(kRuntimeError, "session: time isn't set");
}
obj.addChild(
schema.id("first_seen_time"),
first_seen.get().unixMicros() / kMicrosPerSecond);
obj.addChild(
schema.id("last_seen_time"),
last_seen.get().unixMicros() / kMicrosPerSecond);
msg::MessageEncoder::encode(obj, joined_sessions_schema_, &msg_buf);
return msg_buf;
}
void LogJoinTarget::onSession(
mdb::MDBTransaction* txn,
TrackedSession& session) {
Buffer msg_buf = trackedSessionToJoinedSession(session);
if (dry_run_) {
fnord::logInfo(
"cm.logjoin",
"[DRYRUN] not uploading session: ", 1);
//msg::MessagePrinter::print(obj, joined_sessions_schema_));
} else {
auto first_seen = session.firstSeenTime();
auto time = first_seen.get().unixMicros();
util::BinaryMessageWriter buf;
buf.appendUInt64(time);
buf.appendUInt64(rnd_.random64());
buf.appendVarUInt(msg_buf.size());
buf.append(msg_buf.data(), msg_buf.size());
auto key = StringUtil::format("__uploadq-sessions-$0", rnd_.hex128());
txn->update(key.data(), key.size(), buf.data(), buf.size());
}
++num_sessions;
}
} // namespace cm
<|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
namespace tensorflow {
namespace {
class CrossOp : public XlaOpKernel {
public:
explicit CrossOp(OpKernelConstruction* context) : XlaOpKernel(context) {}
void Compile(XlaOpKernelContext* ctx) override {
TensorShape in0_shape = ctx->InputShape(0);
TensorShape in1_shape = ctx->InputShape(1);
OP_REQUIRES(ctx, in0_shape == in1_shape,
errors::InvalidArgument("Both inputs must be of same shape: ",
in0_shape.DebugString(), " vs. ",
in1_shape.DebugString()));
OP_REQUIRES(ctx, in0_shape.dims() >= 1,
errors::InvalidArgument("Input must be at least 1D",
in0_shape.DebugString()));
auto inner_dim = in0_shape.dim_size(in0_shape.dims() - 1);
OP_REQUIRES(ctx, inner_dim == 3,
errors::FailedPrecondition(
"Cross-products are only defined for 3-element vectors."));
// in0 is a [...,X,Y,Z,3]
// in1 is the same shape as in0
// So slice 0 is: in0[...,:,:,:,0:1]
// So slice 1 is: in0[...,:,:,:,1:2]
// So slice 2 is: in0[...,:,:,:,2:3]
std::vector<int64_t> starts(in0_shape.dims(), 0);
std::vector<int64_t> limits;
auto dim_sizes = in0_shape.dim_sizes();
limits.reserve(dim_sizes.size());
for (auto dim_size : in0_shape.dim_sizes()) {
limits.push_back(dim_size);
}
std::vector<int64_t> strides(in0_shape.dims(), 1);
xla::XlaBuilder* b = ctx->builder();
auto in0 = ctx->Input(0);
auto in1 = ctx->Input(1);
starts.back() = 0;
limits.back() = 1;
auto u1 = xla::Slice(in0, starts, limits, strides);
auto v1 = xla::Slice(in1, starts, limits, strides);
starts.back() = 1;
limits.back() = 2;
auto u2 = xla::Slice(in0, starts, limits, strides);
auto v2 = xla::Slice(in1, starts, limits, strides);
starts.back() = 2;
limits.back() = 3;
auto u3 = xla::Slice(in0, starts, limits, strides);
auto v3 = xla::Slice(in1, starts, limits, strides);
auto s1 = xla::Sub(xla::Mul(u2, v3), xla::Mul(u3, v2));
auto s2 = xla::Sub(xla::Mul(u3, v1), xla::Mul(u1, v3));
auto s3 = xla::Sub(xla::Mul(u1, v2), xla::Mul(u2, v1));
auto output = xla::ConcatInDim(b, {s1, s2, s3}, in0_shape.dims() - 1);
ctx->SetOutput(0, output);
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(CrossOp);
};
REGISTER_XLA_OP(Name("Cross"), CrossOp);
} // namespace
} // namespace tensorflow
<commit_msg>[tensorflow/compiler/tf2xla/kernels/cross_op.cc] Use `const auto&` instead of `auto`<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
namespace tensorflow {
namespace {
class CrossOp : public XlaOpKernel {
public:
explicit CrossOp(OpKernelConstruction* context) : XlaOpKernel(context) {}
void Compile(XlaOpKernelContext* ctx) override {
TensorShape in0_shape = ctx->InputShape(0);
TensorShape in1_shape = ctx->InputShape(1);
OP_REQUIRES(ctx, in0_shape == in1_shape,
errors::InvalidArgument("Both inputs must be of same shape: ",
in0_shape.DebugString(), " vs. ",
in1_shape.DebugString()));
OP_REQUIRES(ctx, in0_shape.dims() >= 1,
errors::InvalidArgument("Input must be at least 1D",
in0_shape.DebugString()));
auto inner_dim = in0_shape.dim_size(in0_shape.dims() - 1);
OP_REQUIRES(ctx, inner_dim == 3,
errors::FailedPrecondition(
"Cross-products are only defined for 3-element vectors."));
// in0 is a [...,X,Y,Z,3]
// in1 is the same shape as in0
// So slice 0 is: in0[...,:,:,:,0:1]
// So slice 1 is: in0[...,:,:,:,1:2]
// So slice 2 is: in0[...,:,:,:,2:3]
std::vector<int64_t> starts(in0_shape.dims(), 0);
std::vector<int64_t> limits;
const auto& dim_sizes = in0_shape.dim_sizes();
limits.reserve(dim_sizes.size());
for (auto dim_size : in0_shape.dim_sizes()) {
limits.push_back(dim_size);
}
std::vector<int64_t> strides(in0_shape.dims(), 1);
xla::XlaBuilder* b = ctx->builder();
auto in0 = ctx->Input(0);
auto in1 = ctx->Input(1);
starts.back() = 0;
limits.back() = 1;
auto u1 = xla::Slice(in0, starts, limits, strides);
auto v1 = xla::Slice(in1, starts, limits, strides);
starts.back() = 1;
limits.back() = 2;
auto u2 = xla::Slice(in0, starts, limits, strides);
auto v2 = xla::Slice(in1, starts, limits, strides);
starts.back() = 2;
limits.back() = 3;
auto u3 = xla::Slice(in0, starts, limits, strides);
auto v3 = xla::Slice(in1, starts, limits, strides);
auto s1 = xla::Sub(xla::Mul(u2, v3), xla::Mul(u3, v2));
auto s2 = xla::Sub(xla::Mul(u3, v1), xla::Mul(u1, v3));
auto s3 = xla::Sub(xla::Mul(u1, v2), xla::Mul(u2, v1));
auto output = xla::ConcatInDim(b, {s1, s2, s3}, in0_shape.dims() - 1);
ctx->SetOutput(0, output);
}
private:
TF_DISALLOW_COPY_AND_ASSIGN(CrossOp);
};
REGISTER_XLA_OP(Name("Cross"), CrossOp);
} // namespace
} // namespace tensorflow
<|endoftext|>
|
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
// Implementation of Field Interpolants
#ifndef MFEM_FIELD_INTERPOLANT
#define MFEM_FIELD_INTERPOLANT
#include "../config/config.hpp"
#include "../linalg/linalg.hpp"
#include "intrules.hpp"
#include "eltrans.hpp"
#include "coefficient.hpp"
#include "bilininteg.hpp"
#include "lininteg.hpp"
#include "gridfunc.hpp"
#ifdef MFEM_USE_MPI
#include "pgridfunc.hpp"
#endif
namespace mfem
{
class FieldInterpolant
{
private:
bool setup_disc;
Vector m_all_data;
MassIntegrator mass_int;
int NE;
public:
FieldInterpolant(const IntegrationRule* ir) : setup_disc(false) { mass_int.SetIntRule(ir); }
// This function takes a vector quadrature function coefficient and projects it onto a GridFunction that lives
// in L2 space. This function requires tr_fes to be the finite element space that the VectorQuadratureFunctionCoefficient lives on
// and fes is the L2 finite element space that we're projecting onto.
void ProjectQuadratureDiscCoefficient(GridFunction &gf,
VectorQuadratureFunctionCoefficient &vqfc,
FiniteElementSpace &tr_fes,
FiniteElementSpace &fes);
// This function takes a quadrature function coefficient and projects it onto a GridFunction that lives
// in L2 space. This function requires tr_fes to be the finite element space that the QuadratureFunctionCoefficient lives on
// and fes is the L2 finite element space that we're projecting onto.
void ProjectQuadratureDiscCoefficient(GridFunction &gf,
QuadratureFunctionCoefficient &qfc,
FiniteElementSpace &tr_fes,
FiniteElementSpace &fes);
//Parallel versions of the ProjectQuadratureCoefficient will need to be created once the serial version works
// This function takes a vector quadrature function coefficient and projects it onto a GridFunction of the same space as vector
// quadrature function coefficient.
void ProjectQuadratureCoefficient(GridFunction &gf,
VectorQuadratureFunctionCoefficient &vqfc,
FiniteElementSpace &fes);
// This function takes a quadrature function coefficient and projects it onto a GridFunction of the same space as
// quadrature function coefficient.
void ProjectQuadratureCoefficient(GridFunction &gf,
QuadratureFunctionCoefficient &qfc,
FiniteElementSpace &fes);
#ifdef MFEM_USE_MPI
// This function takes a vector quadrature function coefficient and projects it onto a GridFunction of the same space as vector
// quadrature function coefficient.
void ProjectQuadratureCoefficient(ParGridFunction &gf,
VectorQuadratureFunctionCoefficient &vqfc,
ParFiniteElementSpace &fes);
// This function takes a quadrature function coefficient and projects it onto a GridFunction of the same space as
// quadrature function coefficient.
void ProjectQuadratureCoefficient(ParGridFunction &gf,
QuadratureFunctionCoefficient &qfc,
ParFiniteElementSpace &fes);
#endif
//Tells the ProjectQuadratureDiscCoefficient that they need to recalculate the data.
void SetupDiscReset() { setup_disc = false; }
~FieldInterpolant() {}
};
class VectorQuadratureIntegrator : public LinearFormIntegrator
{
private:
VectorQuadratureFunctionCoefficient &vqfc;
public:
VectorQuadratureIntegrator(VectorQuadratureFunctionCoefficient &vqfc) : vqfc(
vqfc) { }
VectorQuadratureIntegrator(VectorQuadratureFunctionCoefficient &vqfc,
const IntegrationRule *ir) : vqfc(
vqfc), LinearFormIntegrator(ir) { }
using LinearFormIntegrator::AssembleRHSElementVect;
void AssembleRHSElementVect(const FiniteElement &fe,
ElementTransformation &Tr,
Vector &elvect);
};
class QuadratureIntegrator : public LinearFormIntegrator
{
private:
QuadratureFunctionCoefficient &qfc;
public:
QuadratureIntegrator(QuadratureFunctionCoefficient &qfc) : qfc(qfc) { }
QuadratureIntegrator(QuadratureFunctionCoefficient &qfc,
const IntegrationRule *ir) : qfc(qfc), LinearFormIntegrator(ir) { }
using LinearFormIntegrator::AssembleRHSElementVect;
void AssembleRHSElementVect(const FiniteElement &fe,
ElementTransformation &Tr,
Vector &elvect);
};
}
#endif<commit_msg>Get rid of reorder warning<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
// Implementation of Field Interpolants
#ifndef MFEM_FIELD_INTERPOLANT
#define MFEM_FIELD_INTERPOLANT
#include "../config/config.hpp"
#include "../linalg/linalg.hpp"
#include "intrules.hpp"
#include "eltrans.hpp"
#include "coefficient.hpp"
#include "bilininteg.hpp"
#include "lininteg.hpp"
#include "gridfunc.hpp"
#ifdef MFEM_USE_MPI
#include "pgridfunc.hpp"
#endif
namespace mfem
{
class FieldInterpolant
{
private:
bool setup_disc;
Vector m_all_data;
MassIntegrator mass_int;
int NE;
public:
FieldInterpolant(const IntegrationRule* ir) : setup_disc(false) { mass_int.SetIntRule(ir); }
// This function takes a vector quadrature function coefficient and projects it onto a GridFunction that lives
// in L2 space. This function requires tr_fes to be the finite element space that the VectorQuadratureFunctionCoefficient lives on
// and fes is the L2 finite element space that we're projecting onto.
void ProjectQuadratureDiscCoefficient(GridFunction &gf,
VectorQuadratureFunctionCoefficient &vqfc,
FiniteElementSpace &tr_fes,
FiniteElementSpace &fes);
// This function takes a quadrature function coefficient and projects it onto a GridFunction that lives
// in L2 space. This function requires tr_fes to be the finite element space that the QuadratureFunctionCoefficient lives on
// and fes is the L2 finite element space that we're projecting onto.
void ProjectQuadratureDiscCoefficient(GridFunction &gf,
QuadratureFunctionCoefficient &qfc,
FiniteElementSpace &tr_fes,
FiniteElementSpace &fes);
//Parallel versions of the ProjectQuadratureCoefficient will need to be created once the serial version works
// This function takes a vector quadrature function coefficient and projects it onto a GridFunction of the same space as vector
// quadrature function coefficient.
void ProjectQuadratureCoefficient(GridFunction &gf,
VectorQuadratureFunctionCoefficient &vqfc,
FiniteElementSpace &fes);
// This function takes a quadrature function coefficient and projects it onto a GridFunction of the same space as
// quadrature function coefficient.
void ProjectQuadratureCoefficient(GridFunction &gf,
QuadratureFunctionCoefficient &qfc,
FiniteElementSpace &fes);
#ifdef MFEM_USE_MPI
// This function takes a vector quadrature function coefficient and projects it onto a GridFunction of the same space as vector
// quadrature function coefficient.
void ProjectQuadratureCoefficient(ParGridFunction &gf,
VectorQuadratureFunctionCoefficient &vqfc,
ParFiniteElementSpace &fes);
// This function takes a quadrature function coefficient and projects it onto a GridFunction of the same space as
// quadrature function coefficient.
void ProjectQuadratureCoefficient(ParGridFunction &gf,
QuadratureFunctionCoefficient &qfc,
ParFiniteElementSpace &fes);
#endif
//Tells the ProjectQuadratureDiscCoefficient that they need to recalculate the data.
void SetupDiscReset() { setup_disc = false; }
~FieldInterpolant() {}
};
class VectorQuadratureIntegrator : public LinearFormIntegrator
{
private:
VectorQuadratureFunctionCoefficient &vqfc;
public:
VectorQuadratureIntegrator(VectorQuadratureFunctionCoefficient &vqfc) : vqfc(
vqfc) { }
VectorQuadratureIntegrator(VectorQuadratureFunctionCoefficient &vqfc,
const IntegrationRule *ir) : LinearFormIntegrator(ir), vqfc(
vqfc) { }
using LinearFormIntegrator::AssembleRHSElementVect;
void AssembleRHSElementVect(const FiniteElement &fe,
ElementTransformation &Tr,
Vector &elvect);
};
class QuadratureIntegrator : public LinearFormIntegrator
{
private:
QuadratureFunctionCoefficient &qfc;
public:
QuadratureIntegrator(QuadratureFunctionCoefficient &qfc) : qfc(qfc) { }
QuadratureIntegrator(QuadratureFunctionCoefficient &qfc,
const IntegrationRule *ir) : LinearFormIntegrator(ir), qfc(qfc) { }
using LinearFormIntegrator::AssembleRHSElementVect;
void AssembleRHSElementVect(const FiniteElement &fe,
ElementTransformation &Tr,
Vector &elvect);
};
}
#endif<|endoftext|>
|
<commit_before>/**
* \ file GainMaxColoredExpanderFilter.cpp
*/
#include <ATK/Dynamic/GainMaxColoredExpanderFilter.h>
#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
constexpr gsl::index PROCESSSIZE = 64;
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_softness_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_softness(0.5);
BOOST_CHECK_EQUAL(filter.get_softness(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_softness_range_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
BOOST_CHECK_THROW(filter.set_softness(-0.000001), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_color_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_color(0.5);
BOOST_CHECK_EQUAL(filter.get_color(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_quality_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_quality(0.5);
BOOST_CHECK_EQUAL(filter.get_quality(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_quality_range_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
BOOST_CHECK_THROW(filter.set_quality(0), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_maxreduc_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_max_reduction(0.5);
BOOST_CHECK_EQUAL(filter.get_max_reduction(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_maxreduc_db_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_max_reduction_db(20);
BOOST_CHECK_EQUAL(filter.get_max_reduction(), 100);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_maxreduc_range_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
BOOST_CHECK_THROW(filter.set_max_reduction(-0.000001), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_1_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(10);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(1, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_0_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 0;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_SMALL(outdata[i], 0.001);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_1_threshold_2_ratio_2_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(2);
filter.set_ratio(2);
filter.set_softness(1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(0.700553358, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_1_threshold_2_ratio_4_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(2);
filter.set_ratio(4);
filter.set_softness(1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(0.389224231, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_always_more_1_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = i/1024.;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(1);
filter.set_quality(.1);
filter.set_color(.1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 1; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_GE(outdata[i], 1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_always_less_1_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = i/1024.;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(1);
filter.set_quality(.1);
filter.set_color(-.1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_LE(outdata[i], 1 + std::numeric_limits<float>::epsilon());
}
}
<commit_msg>Force setting softness and max_reduction<commit_after>/**
* \ file GainMaxColoredExpanderFilter.cpp
*/
#include <ATK/Dynamic/GainMaxColoredExpanderFilter.h>
#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
constexpr gsl::index PROCESSSIZE = 64;
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_softness_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_softness(0.5);
BOOST_CHECK_EQUAL(filter.get_softness(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_softness_range_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
BOOST_CHECK_THROW(filter.set_softness(-0.000001), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_color_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_color(0.5);
BOOST_CHECK_EQUAL(filter.get_color(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_quality_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_quality(0.5);
BOOST_CHECK_EQUAL(filter.get_quality(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_quality_range_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
BOOST_CHECK_THROW(filter.set_quality(0), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_maxreduc_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_max_reduction(0.5);
BOOST_CHECK_EQUAL(filter.get_max_reduction(), 0.5);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_maxreduc_db_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
filter.set_max_reduction_db(20);
BOOST_CHECK_EQUAL(filter.get_max_reduction(), 100);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_maxreduc_range_test )
{
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter;
BOOST_CHECK_THROW(filter.set_max_reduction(-0.000001), std::out_of_range);
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_1_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(10);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(1, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_0_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 0;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_SMALL(outdata[i], 0.001);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_1_threshold_2_ratio_2_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(2);
filter.set_ratio(2);
filter.set_softness(1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(0.700553358, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_const_1_threshold_2_ratio_4_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(2);
filter.set_ratio(4);
filter.set_softness(1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(0.389224231, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_always_more_1_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = i/1024.;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(1);
filter.set_softness(0.0001);
filter.set_max_reduction(0.01);
filter.set_quality(.1);
filter.set_color(.1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 1; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_GE(outdata[i], 1);
}
}
BOOST_AUTO_TEST_CASE( GainMaxColoredExpanderFilter_always_less_1_test )
{
std::array<double, PROCESSSIZE> data;
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
data[i] = i/1024.;
}
ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
std::array<double, PROCESSSIZE> outdata;
ATK::GainFilter<ATK::GainMaxColoredExpanderFilter<double>> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(1);
filter.set_softness(0.0001);
filter.set_max_reduction(0.01);
filter.set_quality(.1);
filter.set_color(-.1);
ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(gsl::index i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_LE(outdata[i], 1 + std::numeric_limits<float>::epsilon());
}
}
<|endoftext|>
|
<commit_before>#include "Chunk.h"
#include <iostream>
/*
Chunk::Chunk(ChunkMap* parent, const u32 cx, const u32 cz)
: parent(parent),
cx(cx),
cz(cz)
{
//ctor
}
Chunk::Chunk()
: parent(0),
cx(0),
cz(0) {
std::cout << "hello" << std::endl;
}
*/
Chunk::Chunk() {
}
void Chunk::printSomething() {
std::cout << "something" << std::endl;
}
ChunkMap::ChunkMap(const u32 sizeX, const u32 sizeZ)
: sizeX(sizeX),
sizeZ(sizeZ) {
chunkMapArray = new Chunk**[5];
for(u32 i = 5; i < 5; ++ i) {chunkMapArray[i] = new Chunk*[5];}
std::cout << "aaaaa" << std::endl;
chunkMapArray[1][1] = new Chunk();
std::cout << "bbbbb" << std::endl;
chunkMapArray[1][1]->printSomething();
/*
fooMapArray = new Foo**[7];
for(int i = 0; i < 7; ++ i) {
}
*/
/*
for(u32 cz = 0; cz < sizeZ; ++ cz) {
Chunk** row = chunkMapArray[cz];
for(u32 cx = 0; cx < sizeX; ++ cx) {
row[cx] = new Chunk();
}
}
*/
}
Chunk* ChunkMap::getChunk(u32 cx, u32 cz) {
return 0;//chunkMapArray[cx][cz];
}
ChunkMap::~ChunkMap() {
/*
for(u32 cx = 0; cx < sizeX; ++ cx) {
for(u32 cz = 0; cz < sizeZ; ++ cz) {
delete chunkMapArray[cx][cz];
}
}
delete[] chunkMapArray;
*/
}
<commit_msg>I am confused<commit_after>#include "Chunk.h"
#include <iostream>
/*
Chunk::Chunk(ChunkMap* parent, const u32 cx, const u32 cz)
: parent(parent),
cx(cx),
cz(cz)
{
//ctor
}
Chunk::Chunk()
: parent(0),
cx(0),
cz(0) {
std::cout << "hello" << std::endl;
}
*/
Chunk::Chunk() {
}
void Chunk::printSomething() {
std::cout << "something" << std::endl;
}
ChunkMap::ChunkMap(const u32 sizeX, const u32 sizeZ)
: sizeX(sizeX),
sizeZ(sizeZ) {
fooMapArray = new Foo**[5];
for(u32 i = 5; i < 5; ++ i) {fooMapArray[i] = new Foo*[5];}
std::cout << "aaaaa" << std::endl;
for(u32 cz = 0; cz < 5; ++ cz) {
for(u32 cx = 0; cx < 5; ++ cx) {
fooMapArray[cx][cz] = new Foo(cx * 100 + cz);
std::cout << fooMapArray[cx][cz]->getBar() << std::endl;
}
}
std::cout << "abbbbbb" << std::endl;
}
Chunk* ChunkMap::getChunk(u32 cx, u32 cz) {
return 0;//chunkMapArray[cx][cz];
}
ChunkMap::~ChunkMap() {
/*
for(u32 cx = 0; cx < sizeX; ++ cx) {
for(u32 cz = 0; cz < sizeZ; ++ cz) {
delete chunkMapArray[cx][cz];
}
}
delete[] chunkMapArray;
*/
}
<|endoftext|>
|
<commit_before>/*
This file is part of the clazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
Author: Sérgio Martins <sergio.martins@kdab.com>
Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "Utils.h"
#include "Clazy.h"
#include "StringUtils.h"
#include "clazy_stl.h"
#include "checkbase.h"
#include "checkmanager.h"
#include "AccessSpecifierManager.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Rewrite/Frontend/FixItRewriter.h"
#include "clang/AST/ParentMap.h"
#include <llvm/Config/llvm-config.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
using namespace clang;
using namespace std;
using namespace clang::ast_matchers;
namespace {
class MyFixItOptions : public FixItOptions
{
public:
MyFixItOptions(const MyFixItOptions &other) = delete;
MyFixItOptions(bool inplace)
{
InPlace = inplace;
FixWhatYouCan = true;
FixOnlyWarnings = true;
Silent = false;
}
std::string RewriteFilename(const std::string &filename, int &fd) override
{
fd = -1;
return InPlace ? filename : filename + "_fixed.cpp";
}
};
static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
if (!s)
return;
for (Stmt *child : s->children()) {
llvm::errs() << "Patching " << child->getStmtClassName() << "\n";
map->setParent(child, s);
manuallyPopulateParentMap(map, child);
}
}
class LazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<LazyASTConsumer>
{
LazyASTConsumer(const LazyASTConsumer &) = delete;
public:
LazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager,
const RegisteredCheck::List &requestedChecks, bool inplaceFixits)
: m_ci(ci)
, m_sm(ci.getSourceManager())
, m_rewriter(nullptr)
, m_parentMap(nullptr)
, m_checkManager(checkManager)
{
m_createdChecks = checkManager->createChecks(requestedChecks, ci);
if (checkManager->fixitsEnabled())
m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));
// Check if any of our checks uses ast matchers, and register them
for (CheckBase *check : m_createdChecks)
check->registerASTMatchers(m_matchFinder);
}
~LazyASTConsumer()
{
if (m_rewriter) {
m_rewriter->WriteFixedFiles();
delete m_rewriter;
}
delete m_parentMap;
}
void setParentMap(ParentMap *map)
{
assert(map && !m_parentMap);
m_parentMap = map;
for (CheckBase *check : m_createdChecks)
check->setParentMap(map);
}
bool VisitDecl(Decl *decl)
{
const bool isInSystemHeader = m_sm.isInSystemHeader(decl->getLocStart());
if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager())
a->VisitDeclaration(decl);
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitDeclaration(decl);
}
return true;
}
bool VisitStmt(Stmt *stm)
{
if (!m_parentMap) {
if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred())
return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.
setParentMap(new ParentMap(stm));
}
// Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) {
m_parentMap->setParent(stm, lastStm);
manuallyPopulateParentMap(m_parentMap, stm);
}
lastStm = stm;
// clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
// So add to parent map each time we go into a different hierarchy
if (!m_parentMap->hasParent(stm))
m_parentMap->addStmt(stm);
const bool isInSystemHeader = m_sm.isInSystemHeader(stm->getLocStart());
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitStatement(stm);
}
return true;
}
void HandleTranslationUnit(ASTContext &ctx) override
{
// Run our RecursiveAstVisitor based checks:
TraverseDecl(ctx.getTranslationUnitDecl());
// Run our AstMatcher base checks:
m_matchFinder.matchAST(ctx);
}
Stmt *lastStm = nullptr;
CompilerInstance &m_ci;
const SourceManager &m_sm;
FixItRewriter *m_rewriter;
ParentMap *m_parentMap;
CheckBase::List m_createdChecks;
CheckManager *const m_checkManager;
MatchFinder m_matchFinder;
};
}
static bool parseArgument(const string &arg, vector<string> &args)
{
auto it = clazy_std::find(args, arg);
if (it != args.end()) {
args.erase(it, it + 1);
return true;
}
return false;
}
static CheckLevel parseLevel(vector<std::string> &args)
{
static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
const int numLevels = levels.size();
for (int i = 0; i < numLevels; ++i) {
if (parseArgument(levels.at(i), args)) {
return static_cast<CheckLevel>(i);
}
}
return CheckLevelUndefined;
}
static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
return c1.name < c2.name;
}
static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
if (c1.level == c2.level)
return checkLessThan(c1, c2);
return c1.level < c2.level;
}
ClazyASTAction::ClazyASTAction()
: PluginASTAction()
, m_checkManager(CheckManager::instance())
{
}
std::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
{
return llvm::make_unique<LazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits);
}
bool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)
{
std::vector<std::string> args = args_;
if (parseArgument("help", args)) {
PrintHelp(llvm::errs());
return true;
}
if (parseArgument("no-inplace-fixits", args)) {
// Unit-tests don't use inplace fixits
m_inplaceFixits = false;
}
// This argument is for debugging purposes
const bool printRequestedChecks = parseArgument("print-requested-checks", args);
const CheckLevel requestedLevel = parseLevel(/*by-ref*/args);
if (requestedLevel != CheckLevelUndefined) {
m_checkManager->setRequestedLevel(requestedLevel);
}
if (parseArgument("enable-all-fixits", args)) {
// This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
m_checkManager->enableAllFixIts();
}
if (args.size() > 1) {
// Too many arguments.
llvm::errs() << "Too many arguments: ";
for (const std::string &a : args)
llvm::errs() << a << ' ';
llvm::errs() << "\n";
PrintHelp(llvm::errs());
return false;
} else if (args.size() == 1) {
vector<string> userDisabledChecks;
m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks);
if (m_checks.empty()) {
llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
PrintHelp(llvm::errs());
return false;
}
}
vector<string> userDisabledChecks;
// Append checks specified from env variable
RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks);
copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));
if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {
// No check or level specified, lets use the default level
m_checkManager->setRequestedLevel(DefaultCheckLevel);
}
// Add checks from requested level
auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();
clazy_std::append(checksFromRequestedLevel, m_checks);
clazy_std::sort_and_remove_dups(m_checks, checkLessThan);
CheckManager::removeChecksFromList(m_checks, userDisabledChecks);
if (printRequestedChecks) {
llvm::errs() << "Requested checks: ";
const unsigned int numChecks = m_checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
llvm::errs() << m_checks.at(i).name;
const bool isLast = i == numChecks - 1;
if (!isLast) {
llvm::errs() << ", ";
}
}
llvm::errs() << "\n";
}
return true;
}
void ClazyASTAction::PrintHelp(llvm::raw_ostream &ros)
{
RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);
clazy_std::sort(checks, checkLessThanByLevel);
ros << "Available checks and FixIts:\n\n";
const bool useMarkdown = getenv("CLAZY_HELP_USE_MARKDOWN");
int lastPrintedLevel = -1;
const auto numChecks = checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
const RegisteredCheck &check = checks[i];
const string levelStr = "level" + to_string(check.level);
if (lastPrintedLevel < check.level) {
lastPrintedLevel = check.level;
if (check.level > 0)
ros << "\n";
ros << "- Checks from " << levelStr << ":\n";
}
const string relativeReadmePath = "src/checks/" + levelStr + "/README-" + check.name + ".md";
auto padded = check.name;
padded.insert(padded.end(), 39 - padded.size(), ' ');
ros << " - " << (useMarkdown ? "[" : "") << check.name << (useMarkdown ? "](" + relativeReadmePath + ")" : "");
auto fixits = m_checkManager->availableFixIts(check.name);
if (!fixits.empty()) {
ros << " (";
bool isFirst = true;
for (const auto& fixit : fixits) {
if (isFirst) {
isFirst = false;
} else {
ros << ',';
}
ros << fixit.name;
}
ros << ')';
}
ros << "\n";
}
ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n";
ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
ros << " export CLAZY_CHECKS=\"level0\"\n";
ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n";
ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n";
ros << "or pass as compiler arguments, for example:\n";
ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n";
ros << "\n";
ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n";
}
static FrontendPluginRegistry::Add<ClazyASTAction>
X("clang-lazy", "clang lazy plugin");
<commit_msg>Rename LazyASTConsumer to ClazyASTConsumer<commit_after>/*
This file is part of the clazy static checker.
Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
Author: Sérgio Martins <sergio.martins@kdab.com>
Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "Utils.h"
#include "Clazy.h"
#include "StringUtils.h"
#include "clazy_stl.h"
#include "checkbase.h"
#include "checkmanager.h"
#include "AccessSpecifierManager.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Rewrite/Frontend/FixItRewriter.h"
#include "clang/AST/ParentMap.h"
#include <llvm/Config/llvm-config.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
using namespace clang;
using namespace std;
using namespace clang::ast_matchers;
namespace {
class MyFixItOptions : public FixItOptions
{
public:
MyFixItOptions(const MyFixItOptions &other) = delete;
MyFixItOptions(bool inplace)
{
InPlace = inplace;
FixWhatYouCan = true;
FixOnlyWarnings = true;
Silent = false;
}
std::string RewriteFilename(const std::string &filename, int &fd) override
{
fd = -1;
return InPlace ? filename : filename + "_fixed.cpp";
}
};
static void manuallyPopulateParentMap(ParentMap *map, Stmt *s)
{
if (!s)
return;
for (Stmt *child : s->children()) {
llvm::errs() << "Patching " << child->getStmtClassName() << "\n";
map->setParent(child, s);
manuallyPopulateParentMap(map, child);
}
}
class ClazyASTConsumer : public ASTConsumer, public RecursiveASTVisitor<ClazyASTConsumer>
{
ClazyASTConsumer(const ClazyASTConsumer &) = delete;
public:
ClazyASTConsumer(CompilerInstance &ci, CheckManager *checkManager,
const RegisteredCheck::List &requestedChecks, bool inplaceFixits)
: m_ci(ci)
, m_sm(ci.getSourceManager())
, m_rewriter(nullptr)
, m_parentMap(nullptr)
, m_checkManager(checkManager)
{
m_createdChecks = checkManager->createChecks(requestedChecks, ci);
if (checkManager->fixitsEnabled())
m_rewriter = new FixItRewriter(ci.getDiagnostics(), m_ci.getSourceManager(), m_ci.getLangOpts(), new MyFixItOptions(inplaceFixits));
// Check if any of our checks uses ast matchers, and register them
for (CheckBase *check : m_createdChecks)
check->registerASTMatchers(m_matchFinder);
}
~ClazyASTConsumer()
{
if (m_rewriter) {
m_rewriter->WriteFixedFiles();
delete m_rewriter;
}
delete m_parentMap;
}
void setParentMap(ParentMap *map)
{
assert(map && !m_parentMap);
m_parentMap = map;
for (CheckBase *check : m_createdChecks)
check->setParentMap(map);
}
bool VisitDecl(Decl *decl)
{
const bool isInSystemHeader = m_sm.isInSystemHeader(decl->getLocStart());
if (AccessSpecifierManager *a = m_checkManager->accessSpecifierManager())
a->VisitDeclaration(decl);
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitDeclaration(decl);
}
return true;
}
bool VisitStmt(Stmt *stm)
{
if (!m_parentMap) {
if (m_ci.getDiagnostics().hasUnrecoverableErrorOccurred())
return false; // ParentMap sometimes crashes when there were errors. Doesn't like a botched AST.
setParentMap(new ParentMap(stm));
}
// Workaround llvm bug: Crashes creating a parent map when encountering Catch Statements.
if (lastStm && isa<CXXCatchStmt>(lastStm) && !m_parentMap->hasParent(stm)) {
m_parentMap->setParent(stm, lastStm);
manuallyPopulateParentMap(m_parentMap, stm);
}
lastStm = stm;
// clang::ParentMap takes a root statement, but there's no root statement in the AST, the root is a declaration
// So add to parent map each time we go into a different hierarchy
if (!m_parentMap->hasParent(stm))
m_parentMap->addStmt(stm);
const bool isInSystemHeader = m_sm.isInSystemHeader(stm->getLocStart());
for (CheckBase *check : m_createdChecks) {
if (!(isInSystemHeader && check->ignoresAstNodesInSystemHeaders()))
check->VisitStatement(stm);
}
return true;
}
void HandleTranslationUnit(ASTContext &ctx) override
{
// Run our RecursiveAstVisitor based checks:
TraverseDecl(ctx.getTranslationUnitDecl());
// Run our AstMatcher base checks:
m_matchFinder.matchAST(ctx);
}
Stmt *lastStm = nullptr;
CompilerInstance &m_ci;
const SourceManager &m_sm;
FixItRewriter *m_rewriter;
ParentMap *m_parentMap;
CheckBase::List m_createdChecks;
CheckManager *const m_checkManager;
MatchFinder m_matchFinder;
};
}
static bool parseArgument(const string &arg, vector<string> &args)
{
auto it = clazy_std::find(args, arg);
if (it != args.end()) {
args.erase(it, it + 1);
return true;
}
return false;
}
static CheckLevel parseLevel(vector<std::string> &args)
{
static const vector<string> levels = { "level0", "level1", "level2", "level3", "level4" };
const int numLevels = levels.size();
for (int i = 0; i < numLevels; ++i) {
if (parseArgument(levels.at(i), args)) {
return static_cast<CheckLevel>(i);
}
}
return CheckLevelUndefined;
}
static bool checkLessThan(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
return c1.name < c2.name;
}
static bool checkLessThanByLevel(const RegisteredCheck &c1, const RegisteredCheck &c2)
{
if (c1.level == c2.level)
return checkLessThan(c1, c2);
return c1.level < c2.level;
}
ClazyASTAction::ClazyASTAction()
: PluginASTAction()
, m_checkManager(CheckManager::instance())
{
}
std::unique_ptr<clang::ASTConsumer> ClazyASTAction::CreateASTConsumer(CompilerInstance &ci, llvm::StringRef)
{
return llvm::make_unique<ClazyASTConsumer>(ci, m_checkManager, m_checks, m_inplaceFixits);
}
bool ClazyASTAction::ParseArgs(const CompilerInstance &, const std::vector<std::string> &args_)
{
std::vector<std::string> args = args_;
if (parseArgument("help", args)) {
PrintHelp(llvm::errs());
return true;
}
if (parseArgument("no-inplace-fixits", args)) {
// Unit-tests don't use inplace fixits
m_inplaceFixits = false;
}
// This argument is for debugging purposes
const bool printRequestedChecks = parseArgument("print-requested-checks", args);
const CheckLevel requestedLevel = parseLevel(/*by-ref*/args);
if (requestedLevel != CheckLevelUndefined) {
m_checkManager->setRequestedLevel(requestedLevel);
}
if (parseArgument("enable-all-fixits", args)) {
// This is useful for unit-tests, where we also want to run fixits. Don't use it otherwise.
m_checkManager->enableAllFixIts();
}
if (args.size() > 1) {
// Too many arguments.
llvm::errs() << "Too many arguments: ";
for (const std::string &a : args)
llvm::errs() << a << ' ';
llvm::errs() << "\n";
PrintHelp(llvm::errs());
return false;
} else if (args.size() == 1) {
vector<string> userDisabledChecks;
m_checks = m_checkManager->checksForCommaSeparatedString(args[0], /*by-ref=*/userDisabledChecks);
if (m_checks.empty()) {
llvm::errs() << "Could not find checks in comma separated string " + args[0] + "\n";
PrintHelp(llvm::errs());
return false;
}
}
vector<string> userDisabledChecks;
// Append checks specified from env variable
RegisteredCheck::List checksFromEnv = m_checkManager->requestedChecksThroughEnv(/*by-ref*/userDisabledChecks);
copy(checksFromEnv.cbegin(), checksFromEnv.cend(), back_inserter(m_checks));
if (m_checks.empty() && requestedLevel == CheckLevelUndefined) {
// No check or level specified, lets use the default level
m_checkManager->setRequestedLevel(DefaultCheckLevel);
}
// Add checks from requested level
auto checksFromRequestedLevel = m_checkManager->checksFromRequestedLevel();
clazy_std::append(checksFromRequestedLevel, m_checks);
clazy_std::sort_and_remove_dups(m_checks, checkLessThan);
CheckManager::removeChecksFromList(m_checks, userDisabledChecks);
if (printRequestedChecks) {
llvm::errs() << "Requested checks: ";
const unsigned int numChecks = m_checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
llvm::errs() << m_checks.at(i).name;
const bool isLast = i == numChecks - 1;
if (!isLast) {
llvm::errs() << ", ";
}
}
llvm::errs() << "\n";
}
return true;
}
void ClazyASTAction::PrintHelp(llvm::raw_ostream &ros)
{
RegisteredCheck::List checks = m_checkManager->availableChecks(MaxCheckLevel);
clazy_std::sort(checks, checkLessThanByLevel);
ros << "Available checks and FixIts:\n\n";
const bool useMarkdown = getenv("CLAZY_HELP_USE_MARKDOWN");
int lastPrintedLevel = -1;
const auto numChecks = checks.size();
for (unsigned int i = 0; i < numChecks; ++i) {
const RegisteredCheck &check = checks[i];
const string levelStr = "level" + to_string(check.level);
if (lastPrintedLevel < check.level) {
lastPrintedLevel = check.level;
if (check.level > 0)
ros << "\n";
ros << "- Checks from " << levelStr << ":\n";
}
const string relativeReadmePath = "src/checks/" + levelStr + "/README-" + check.name + ".md";
auto padded = check.name;
padded.insert(padded.end(), 39 - padded.size(), ' ');
ros << " - " << (useMarkdown ? "[" : "") << check.name << (useMarkdown ? "](" + relativeReadmePath + ")" : "");
auto fixits = m_checkManager->availableFixIts(check.name);
if (!fixits.empty()) {
ros << " (";
bool isFirst = true;
for (const auto& fixit : fixits) {
if (isFirst) {
isFirst = false;
} else {
ros << ',';
}
ros << fixit.name;
}
ros << ')';
}
ros << "\n";
}
ros << "\nIf nothing is specified, all checks from level0 and level1 will be run.\n\n";
ros << "To specify which checks to enable set the CLAZY_CHECKS env variable, for example:\n";
ros << " export CLAZY_CHECKS=\"level0\"\n";
ros << " export CLAZY_CHECKS=\"level0,reserve-candidates,qstring-allocations\"\n";
ros << " export CLAZY_CHECKS=\"reserve-candidates\"\n\n";
ros << "or pass as compiler arguments, for example:\n";
ros << " -Xclang -plugin-arg-clang-lazy -Xclang reserve-candidates,qstring-allocations\n";
ros << "\n";
ros << "To enable FixIts for a check, also set the env variable CLAZY_FIXIT, for example:\n";
ros << " export CLAZY_FIXIT=\"fix-qlatin1string-allocations\"\n\n";
ros << "FixIts are experimental and rewrite your code therefore only one FixIt is allowed per build.\nSpecifying a list of different FixIts is not supported.\nBackup your code before running them.\n";
}
static FrontendPluginRegistry::Add<ClazyASTAction>
X("clang-lazy", "clang lazy plugin");
<|endoftext|>
|
<commit_before>/**
* Notes.CC
*
* MIT/X11 License
* Copyright (c) 2014 Qball Cow <qball@gmpclient.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <Project.h>
#include <Note.h>
#include <Filter.h>
NotesFilter::NotesFilter( std::vector< Note *> notes )
{
// Copy the list!
start_notes = std::list<Note *>( notes.begin (), notes.end () );
}
void NotesFilter::add_filter ( std::string value )
{
for ( auto iter = start_notes.begin (); iter != start_notes.end (); iter++ ) {
Note *note = *iter;
// Skip empty elements.
if ( note == nullptr ) {
continue;
}
bool remove = true;
if ( note->get_title ().rfind ( value ) != std::string::npos ) {
remove = false;
}
if ( remove && note->get_project_name ().rfind ( value ) != std::string::npos ) {
remove =
false;
}
if ( remove ) {
*iter = nullptr;
}
}
// Remove empty items.
start_notes.remove ( nullptr );
}
<commit_msg>Filter case insensitive.<commit_after>/**
* Notes.CC
*
* MIT/X11 License
* Copyright (c) 2014 Qball Cow <qball@gmpclient.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <Project.h>
#include <Note.h>
#include <Filter.h>
NotesFilter::NotesFilter( std::vector< Note *> notes )
{
// Copy the list!
start_notes = std::list<Note *>( notes.begin (), notes.end () );
}
void NotesFilter::add_filter ( std::string value )
{
const char *val_cstr = value.c_str();
for ( auto iter = start_notes.begin (); iter != start_notes.end (); iter++ ) {
Note *note = *iter;
// Skip empty elements.
if ( note == nullptr ) {
continue;
}
bool remove = true;
if ( strcasestr(note->get_title ().c_str(), val_cstr) != NULL ) {
remove = false;
} else
if ( strcasestr(note->get_project_name ().c_str(), val_cstr) != NULL ) {
remove = false;
}
if ( remove ) {
*iter = nullptr;
}
}
// Remove empty items.
start_notes.remove ( nullptr );
}
<|endoftext|>
|
<commit_before>#include "Graph.h"
#include <algorithm>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>
#include <map>
#include <functional>
/////////////////////////////////////////////////////
// Node of Graph
/////////////////////////////////////////////////////
void GraphNode::removeNeighbor(int to)
{
auto neighborIt = std::find(neighbors.begin(), neighbors.end(), to);
auto edgeWeightIt = edgeWeights.begin() + (neighborIt - neighbors.begin());
std::swap(*neighborIt, *neighbors.rbegin());
std::swap(*edgeWeightIt, *edgeWeights.rbegin());
neighbors.erase(neighbors.end() - 1, neighbors.end());
edgeWeights.erase(edgeWeights.end() - 1, edgeWeights.end());
}
void GraphNode::addNeighbor(int to, double weight)
{
auto it = std::lower_bound(neighbors.begin(), neighbors.end(), to);
if (it != neighbors.end() && *it == to)
return;
edgeWeights.insert(edgeWeights.begin() + (it - neighbors.begin()), weight);
neighbors.insert(it, to);
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Graph
/////////////////////////////////////////////////////
void Graph::resize(int newNodes)
{
if (newNodes < int(nodes.size()))
throw("Graph::resize - cannot decrease size");
if (newNodes == nodes.size())
return;
nodes.resize(newNodes);
}
int Graph::addNode(double weight)
{
nodes.emplace_back(weight);
return int(nodes.size()) - 1;
}
void Graph::addEdge(int from, int to, double weight)
{
nodes[from].addNeighbor(to, weight);
if (!directed)
{
nodes[to].addNeighbor(from, weight);
}
}
void Graph::removeEdge(int from, int to)
{
nodes[from].removeNeighbor(to);
if (!directed)
{
nodes[to].removeNeighbor(from);
}
}
void Graph::clear()
{
nodes.clear();
}
std::vector<GraphEdge> Graph::getEdges() const
{
std::vector<GraphEdge> ret;
for (size_t nodeIdx = 0; nodeIdx < nodes.size(); ++nodeIdx)
{
auto &node = nodes[nodeIdx];
for (size_t neighborIdx = 0; neighborIdx < node.neighbors.size(); ++neighborIdx)
{
if (directed || node.neighbors[neighborIdx] >= int(nodeIdx))
{
ret.emplace_back(node.edgeWeights[neighborIdx], int(nodeIdx), node.neighbors[neighborIdx]);
}
}
}
return ret;
}
/////////////////////////////////////////////////////
// Input / Output
/////////////////////////////////////////////////////
//
// Format:
// NumberOfNodes NumberOfEdges
// DirectedFlag WeightedNodesFlag WeightedEdgesFlag
// If WeightedNodesFlag == 1, the node weights follow, NumberOfNodes numbers
// else this section is omitted
// NumberOfEdges edges follow:
// From To [Weight]
// Wight is omitted if NumberOfEdges == 0
// Flags are 0 or 1
// All weights are floating point numbers
// Everything is whitespace separated
// Indexes are 1 based.
// e.g
// 3 2
// 1 1 0
// 5.4
// 0.6
// 1
// 2 3
// 3 1
// 2 ----> 3 ----> 1
// 0.6 1 5.4
std::istream &operator>>(std::istream &is, Graph &g)
{
g.clear();
int n, m;
int directedFlag, weightedNodesFlag, weightedEdgesFlag;
is >> n >> m;
is >> directedFlag >> weightedNodesFlag >> weightedEdgesFlag;
g.resize(n);
g.setDirected(directedFlag != 0);
g.setWeightedNodes(weightedNodesFlag != 0);
g.setWeightedEdges(weightedEdgesFlag != 0);
if (g.hasWeightedNodes())
{
for (auto &node : g)
{
double w;
is >> w;
node.setWeight(w);
}
}
for (int i = 0; i < m; ++i)
{
int from, to;
is >> from >> to;
double weight = 0.0;
if (g.hasWeightedEdges())
{
is >> weight;
}
g.addEdge(from - 1, to - 1, weight);
}
return is;
}
std::ostream &operator<<(std::ostream &os, const Graph &g)
{
os << g.getNodeCount() << " ";
size_t edgesCount = 0;
for (auto &node : g)
{
edgesCount += node.getNeighborCount();
}
if (g.isDirected())
{
os << edgesCount << "\n";
}
else
{
os << edgesCount / 2 << "\n";
}
os << g.isDirected() << " " << g.hasWeightedNodes() << " " << g.hasWeightedEdges() << "\n";
if (g.hasWeightedNodes())
{
for (auto &node : g)
{
os << node.getWeight() << "\n";
}
}
for (int nodeIdx = 0; nodeIdx < g.getNodeCount(); ++nodeIdx)
{
auto &node = g.getNode(nodeIdx);
for (int i = 0; i < node.getNeighborCount(); ++i)
{
if (g.isDirected() || nodeIdx < node.getNeighbor(i))
{
os << nodeIdx + 1 << " " << node.getNeighbor(i) + 1;
}
if (g.hasWeightedEdges())
{
os << " " << node.getEdgeWeight(int(i));
}
os << "\n";
}
}
os << std::flush;
return os;
}
<commit_msg>Fixed undirected graph saving<commit_after>#include "Graph.h"
#include <algorithm>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>
#include <map>
#include <functional>
/////////////////////////////////////////////////////
// Node of Graph
/////////////////////////////////////////////////////
void GraphNode::removeNeighbor(int to)
{
auto neighborIt = std::find(neighbors.begin(), neighbors.end(), to);
auto edgeWeightIt = edgeWeights.begin() + (neighborIt - neighbors.begin());
std::swap(*neighborIt, *neighbors.rbegin());
std::swap(*edgeWeightIt, *edgeWeights.rbegin());
neighbors.erase(neighbors.end() - 1, neighbors.end());
edgeWeights.erase(edgeWeights.end() - 1, edgeWeights.end());
}
void GraphNode::addNeighbor(int to, double weight)
{
auto it = std::lower_bound(neighbors.begin(), neighbors.end(), to);
if (it != neighbors.end() && *it == to)
return;
edgeWeights.insert(edgeWeights.begin() + (it - neighbors.begin()), weight);
neighbors.insert(it, to);
}
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Graph
/////////////////////////////////////////////////////
void Graph::resize(int newNodes)
{
if (newNodes < int(nodes.size()))
throw("Graph::resize - cannot decrease size");
if (newNodes == nodes.size())
return;
nodes.resize(newNodes);
}
int Graph::addNode(double weight)
{
nodes.emplace_back(weight);
return int(nodes.size()) - 1;
}
void Graph::addEdge(int from, int to, double weight)
{
nodes[from].addNeighbor(to, weight);
if (!directed)
{
nodes[to].addNeighbor(from, weight);
}
}
void Graph::removeEdge(int from, int to)
{
nodes[from].removeNeighbor(to);
if (!directed)
{
nodes[to].removeNeighbor(from);
}
}
void Graph::clear()
{
nodes.clear();
}
std::vector<GraphEdge> Graph::getEdges() const
{
std::vector<GraphEdge> ret;
for (size_t nodeIdx = 0; nodeIdx < nodes.size(); ++nodeIdx)
{
auto &node = nodes[nodeIdx];
for (size_t neighborIdx = 0; neighborIdx < node.neighbors.size(); ++neighborIdx)
{
if (directed || node.neighbors[neighborIdx] >= int(nodeIdx))
{
ret.emplace_back(node.edgeWeights[neighborIdx], int(nodeIdx), node.neighbors[neighborIdx]);
}
}
}
return ret;
}
/////////////////////////////////////////////////////
// Input / Output
/////////////////////////////////////////////////////
//
// Format:
// NumberOfNodes NumberOfEdges
// DirectedFlag WeightedNodesFlag WeightedEdgesFlag
// If WeightedNodesFlag == 1, the node weights follow, NumberOfNodes numbers
// else this section is omitted
// NumberOfEdges edges follow:
// From To [Weight]
// Wight is omitted if NumberOfEdges == 0
// Flags are 0 or 1
// All weights are floating point numbers
// Everything is whitespace separated
// Indexes are 1 based.
// e.g
// 3 2
// 1 1 0
// 5.4
// 0.6
// 1
// 2 3
// 3 1
// 2 ----> 3 ----> 1
// 0.6 1 5.4
std::istream &operator>>(std::istream &is, Graph &g)
{
g.clear();
int n, m;
int directedFlag, weightedNodesFlag, weightedEdgesFlag;
is >> n >> m;
is >> directedFlag >> weightedNodesFlag >> weightedEdgesFlag;
g.resize(n);
g.setDirected(directedFlag != 0);
g.setWeightedNodes(weightedNodesFlag != 0);
g.setWeightedEdges(weightedEdgesFlag != 0);
if (g.hasWeightedNodes())
{
for (auto &node : g)
{
double w;
is >> w;
node.setWeight(w);
}
}
for (int i = 0; i < m; ++i)
{
int from, to;
is >> from >> to;
double weight = 0.0;
if (g.hasWeightedEdges())
{
is >> weight;
}
g.addEdge(from - 1, to - 1, weight);
}
return is;
}
std::ostream &operator<<(std::ostream &os, const Graph &g)
{
os << g.getNodeCount() << " ";
size_t edgesCount = 0;
for (auto &node : g)
{
edgesCount += node.getNeighborCount();
}
if (g.isDirected())
{
os << edgesCount << "\n";
}
else
{
os << edgesCount / 2 << "\n";
}
os << g.isDirected() << " " << g.hasWeightedNodes() << " " << g.hasWeightedEdges() << "\n";
if (g.hasWeightedNodes())
{
for (auto &node : g)
{
os << node.getWeight() << "\n";
}
}
for (int nodeIdx = 0; nodeIdx < g.getNodeCount(); ++nodeIdx)
{
auto &node = g.getNode(nodeIdx);
for (int i = 0; i < node.getNeighborCount(); ++i)
{
if (g.isDirected() || nodeIdx < node.getNeighbor(i))
{
os << nodeIdx + 1 << " " << node.getNeighbor(i) + 1;
if (g.hasWeightedEdges())
{
os << " " << node.getEdgeWeight(int(i));
}
os << "\n";
}
}
}
os << std::flush;
return os;
}
<|endoftext|>
|
<commit_before>#include "Guess.h"
Guess::Guess()
{
}
Guess::Guess(uint32_t uiPerson,
uint32_t uiPlace,
uint32_t uiWeapon,
const std::string &sGuesserName,
const std::string &sStopper)
:m_uiPerson(uiPerson)
,m_uiPlace(uiPlace)
,m_uiWeapon(uiWeapon)
,m_sGuesserName(sGuesserName)
,m_sStopper(sStopper)
{
}
Guess::~Guess()
{
}
void Guess::clear()
{
m_uiPerson = 0;
m_uiPlace = 0;
m_uiWeapon = 0;
m_sGuesserName.clear();
m_sStopper.clear();
m_svPasses.empty();
}
void Guess::addCard(uint32_t uiCard, Rules::eCardType eCardType)
{
switch (eCardType) {
case Rules::ePerson:
m_uiPerson = uiCard;
break;
case Rules::eWeapon:
m_uiWeapon = uiCard;
break;
case Rules::ePlace:
m_uiPlace = uiCard;
break;
default:
//TODO: Throw exception
break;
};
}
<commit_msg>Fixed a TINY NASTY LITTLE EVIL BUG where I did a boolean empty check instead of clearing the vector<commit_after>#include "Guess.h"
Guess::Guess()
{
}
Guess::Guess(uint32_t uiPerson,
uint32_t uiPlace,
uint32_t uiWeapon,
const std::string &sGuesserName,
const std::string &sStopper)
:m_uiPerson(uiPerson)
,m_uiPlace(uiPlace)
,m_uiWeapon(uiWeapon)
,m_sGuesserName(sGuesserName)
,m_sStopper(sStopper)
{
}
Guess::~Guess()
{
}
void Guess::clear()
{
m_uiPerson = 0;
m_uiPlace = 0;
m_uiWeapon = 0;
m_sGuesserName.clear();
m_sStopper.clear();
m_svPasses.clear();
}
void Guess::addCard(uint32_t uiCard, Rules::eCardType eCardType)
{
switch (eCardType) {
case Rules::ePerson:
m_uiPerson = uiCard;
break;
case Rules::eWeapon:
m_uiWeapon = uiCard;
break;
case Rules::ePlace:
m_uiPlace = uiCard;
break;
default:
//TODO: Throw exception
break;
};
}
<|endoftext|>
|
<commit_before>#include "Lexer.hpp"
#define TAB_LENGTH 2
//utility func to parse escaped chars, e.g. 'n' -> '\n'
char getEscapedChar(char ident);
struct CodeStream
{
CodeStream(string& srcIn, vector<Token*>& toksIn) : src(srcIn), toks(toksIn)
{
iter = 0;
//no error can happen with iter at 0,
//so prev position doesn't matter (no chars read yet)
prevLine = 0;
prevCol = 0;
line = 1;
col = 1;
}
char getNext()
{
prevCol = col;
prevLine = line;
if(iter >= src.length())
return '\0';
char c = src[iter];
if(c == '\n')
{
line++;
col = 1;
}
else if(c == '\t')
{
col += TAB_LENGTH;
}
else
{
col++;
}
iter++;
return c;
}
char peek(int ahead = 0)
{
if(iter + ahead >= src.length())
return '\0';
return src[iter + ahead];
}
void addToken(Token* tok)
{
toks.push_back(tok);
toks.back()->line = line;
toks.back()->col = col;
}
//bool value is "eof?"
operator bool()
{
return iter < src.length() && src[iter];
}
bool operator!()
{
return iter >= src.length() || !src[iter];
}
void err(string msg)
{
string fullMsg = string("Lexical error at line ") + to_string(prevLine) +
", col " + to_string(prevCol) + ": " + msg;
ERR_MSG(fullMsg);
}
string& src;
vector<Token*>& toks;
size_t iter;
int line;
int col;
int prevLine;
int prevCol;
};
void lex(string& code, vector<Token*>& tokList)
{
CodeStream cs(code, tokList);
vector<Token*> tokens;
//note: i is incremented various amounts depending on the tokens
while(cs)
{
char c = cs.getNext();
if(c == ' ' || c == '\t' || c == '\n')
{
continue;
}
else if(c == '"')
{
//string literal
int stringStart = cs.iter;
while(true)
{
char next = cs.getNext();
if(next == '\\')
{
//eat an additional character no matter what it is
cs.getNext();
}
else if(next == '"')
{
//end of string
break;
}
}
//stringEnd is index of the closing quotations
int stringEnd = cs.iter - 1;
//get string literal between stringStart and stringEnd
vector<char> strLit;
strLit.reserve(stringEnd - stringStart + 1);
for(int i = stringStart; i < stringEnd; i++)
{
if(code[i] == '\\')
{
i++;
strLit.push_back(getEscapedChar(code[i]));
}
else
{
strLit.push_back(code[i]);
}
}
strLit.push_back('\0');
string s(&strLit[0]);
cs.addToken(new StrLit(s));
}
else if(c == '/' && cs.peek() == '*')
{
int commentDepth = 1;
cs.getNext();
while(cs && commentDepth)
{
//get next char
char next = cs.getNext();
if(next == '/' && cs.peek() == '*')
{
cs.getNext();
commentDepth++;
}
else if(next == '*' && cs.peek() == '/')
{
cs.getNext();
commentDepth--;
}
}
//EOF with non-terminated block comment is an error
if(!cs && commentDepth)
{
cs.err("non-terminated block comment (missing */)");
}
}
else if(c == '\'')
{
char charVal = cs.getNext();
if(charVal == '\\')
{
cs.addToken(new CharLit(getEscapedChar(cs.getNext())));
}
else
{
cs.addToken(new CharLit(charVal));
}
//finally, expect closing quote
if(cs.getNext() != '\'')
{
cs.err("non-terminated character literal");
}
}
else if(c == '/' && cs.peek() == '/')
{
cs.getNext();
while(cs.getNext() != '\n');
}
else if(isalpha(c) || c == '_')
{
//keyword or identifier
//scan all following alphanumeric/underscore chars to classify
//c would be the start of the identifier, but iter is one past that now
int identStart = cs.iter - 1;
while(1)
{
char identChar = cs.peek();
if(isalnum(identChar) || identChar == '_')
cs.getNext();
else
break;
}
int identEnd = cs.iter;
string ident = code.substr(identStart, identEnd - identStart);
if(ident[ident.length() - 1] == '_')
{
cs.err("identifier can't end with an underscore.");
}
//check if keyword
auto kwIter = keywordMap.find(ident);
if(kwIter == keywordMap.end())
cs.addToken(new Ident(ident));
else
cs.addToken(new Keyword(kwIter->second));
}
else if(c == '0' && tolower(cs.peek(0)) == 'x' && isxdigit(cs.peek(1)))
{
//hex int literal, OR int 0 followed by ??? (if not valid hex num)
cs.getNext();
char* numEnd;
unsigned long long val = strtoull(code.c_str() + cs.iter, &numEnd, 16);
cs.addToken(new IntLit(val));
while(isxdigit(cs.peek(0)))
cs.getNext();
}
else if(c == '0' && tolower(cs.peek(1)) == 'b' &&
(cs.peek(2) == '0' || cs.peek(2) == '1'))
{
//binary int literal, OR int 0 followed by ??? (if not valid bin num)
cs.getNext();
char* numEnd;
unsigned long long val = strtoull(code.c_str() + cs.iter, &numEnd, 2);
cs.addToken(new IntLit(val));
while(cs.peek(0) == '0' || cs.peek(0) == '1')
cs.getNext();
for(const char* i = code.c_str() + cs.iter; i != numEnd; i++)
{
cs.getNext();
}
}
else if(isdigit(c))
{
//decimal integer or float literal
uint64_t intVal = 0;
//take the integer conversion, or the double conversion if it uses more chars
const char* numStart = code.c_str() + cs.iter - 1;
char* intEnd;
char* floatEnd;
//note: int/float literals are always positive
//'-' handled as arithmetic unary operator
//so IntLit holds an unsigned 64-bit value to cover all cases
intVal = strtoull(numStart, &intEnd, 10);
double floatVal = strtod(numStart, &floatEnd);
if(floatEnd > intEnd)
{
//use float
cs.addToken(new FloatLit(floatVal));
//advance the char stream by floatEnd - code.c_str() chars
for(const char* i = code.c_str() + cs.iter; i != floatEnd; i++)
{
cs.getNext();
}
}
else
{
//use int
cs.addToken(new IntLit(intVal));
for(const char* i = code.c_str() + cs.iter; i != intEnd; i++)
{
cs.getNext();
}
}
}
else if(ispunct(c))
{
//check for punctuation first (only 1 char)
auto punctIter = punctMap.find(c);
if(punctIter == punctMap.end())
{
//operator, not punct
//some operators are 2 chars long, use them if valid, otherwise 1 char
string oper1 = string("") + c;
string oper2 = oper1 + cs.peek();
auto oper2Iter = operatorMap.find(oper2);
if(oper2Iter == operatorMap.end())
{
//must be 1-char operator
auto oper1Iter = operatorMap.find(oper1);
if(oper1Iter == operatorMap.end())
{
cs.err(string("symbol character '") + oper1 + "' neither valid operator nor punctuation.");
}
else
{
cs.addToken(new Oper(oper1Iter->second));
}
}
else
{
cs.addToken(new Oper(oper2Iter->second));
cs.getNext();
}
}
else
{
//c is punct char
cs.addToken(new Punct(punctIter->second));
}
}
else
{
ERR_MSG("unexpected character: '" << c << "'\n");
}
}
}
char getEscapedChar(char ident)
{
if(ident == 'n')
return '\n';
if(ident == 't')
return '\t';
if(ident == '0')
return 0;
if(ident == '\\')
return '\\';
if(ident == 'r')
return '\r';
ERR_MSG(string("Unknown escape sequence: \\") + ident);
return ' ';
}
<commit_msg>Actually fixed binary literal lexing<commit_after>#include "Lexer.hpp"
#define TAB_LENGTH 2
//utility func to parse escaped chars, e.g. 'n' -> '\n'
char getEscapedChar(char ident);
struct CodeStream
{
CodeStream(string& srcIn, vector<Token*>& toksIn) : src(srcIn), toks(toksIn)
{
iter = 0;
//no error can happen with iter at 0,
//so prev position doesn't matter (no chars read yet)
prevLine = 0;
prevCol = 0;
line = 1;
col = 1;
}
char getNext()
{
prevCol = col;
prevLine = line;
if(iter >= src.length())
return '\0';
char c = src[iter];
if(c == '\n')
{
line++;
col = 1;
}
else if(c == '\t')
{
col += TAB_LENGTH;
}
else
{
col++;
}
iter++;
return c;
}
char peek(int ahead = 0)
{
if(iter + ahead >= src.length())
return '\0';
return src[iter + ahead];
}
void addToken(Token* tok)
{
toks.push_back(tok);
toks.back()->line = line;
toks.back()->col = col;
}
//bool value is "eof?"
operator bool()
{
return iter < src.length() && src[iter];
}
bool operator!()
{
return iter >= src.length() || !src[iter];
}
void err(string msg)
{
string fullMsg = string("Lexical error at line ") + to_string(prevLine) +
", col " + to_string(prevCol) + ": " + msg;
ERR_MSG(fullMsg);
}
string& src;
vector<Token*>& toks;
size_t iter;
int line;
int col;
int prevLine;
int prevCol;
};
void lex(string& code, vector<Token*>& tokList)
{
CodeStream cs(code, tokList);
vector<Token*> tokens;
//note: i is incremented various amounts depending on the tokens
while(cs)
{
char c = cs.getNext();
if(c == ' ' || c == '\t' || c == '\n')
{
continue;
}
else if(c == '"')
{
//string literal
int stringStart = cs.iter;
while(true)
{
char next = cs.getNext();
if(next == '\\')
{
//eat an additional character no matter what it is
cs.getNext();
}
else if(next == '"')
{
//end of string
break;
}
}
//stringEnd is index of the closing quotations
int stringEnd = cs.iter - 1;
//get string literal between stringStart and stringEnd
vector<char> strLit;
strLit.reserve(stringEnd - stringStart + 1);
for(int i = stringStart; i < stringEnd; i++)
{
if(code[i] == '\\')
{
i++;
strLit.push_back(getEscapedChar(code[i]));
}
else
{
strLit.push_back(code[i]);
}
}
strLit.push_back('\0');
string s(&strLit[0]);
cs.addToken(new StrLit(s));
}
else if(c == '/' && cs.peek() == '*')
{
int commentDepth = 1;
cs.getNext();
while(cs && commentDepth)
{
//get next char
char next = cs.getNext();
if(next == '/' && cs.peek() == '*')
{
cs.getNext();
commentDepth++;
}
else if(next == '*' && cs.peek() == '/')
{
cs.getNext();
commentDepth--;
}
}
//EOF with non-terminated block comment is an error
if(!cs && commentDepth)
{
cs.err("non-terminated block comment (missing */)");
}
}
else if(c == '\'')
{
char charVal = cs.getNext();
if(charVal == '\\')
{
cs.addToken(new CharLit(getEscapedChar(cs.getNext())));
}
else
{
cs.addToken(new CharLit(charVal));
}
//finally, expect closing quote
if(cs.getNext() != '\'')
{
cs.err("non-terminated character literal");
}
}
else if(c == '/' && cs.peek() == '/')
{
cs.getNext();
while(cs.getNext() != '\n');
}
else if(isalpha(c) || c == '_')
{
//keyword or identifier
//scan all following alphanumeric/underscore chars to classify
//c would be the start of the identifier, but iter is one past that now
int identStart = cs.iter - 1;
while(1)
{
char identChar = cs.peek();
if(isalnum(identChar) || identChar == '_')
cs.getNext();
else
break;
}
int identEnd = cs.iter;
string ident = code.substr(identStart, identEnd - identStart);
if(ident[ident.length() - 1] == '_')
{
cs.err("identifier can't end with an underscore.");
}
//check if keyword
auto kwIter = keywordMap.find(ident);
if(kwIter == keywordMap.end())
cs.addToken(new Ident(ident));
else
cs.addToken(new Keyword(kwIter->second));
}
else if(c == '0' && tolower(cs.peek(0)) == 'x' && isxdigit(cs.peek(1)))
{
//hex int literal, OR int 0 followed by ??? (if not valid hex num)
cs.getNext();
char* numEnd;
unsigned long long val = strtoull(code.c_str() + cs.iter, &numEnd, 16);
cs.addToken(new IntLit(val));
while(isxdigit(cs.peek(0)))
cs.getNext();
}
else if(c == '0' && tolower(cs.peek(0)) == 'b' &&
(cs.peek(1) == '0' || cs.peek(1) == '1'))
{
//binary int literal, OR int 0 followed by ??? (if not valid bin num)
cs.getNext();
char* numEnd;
unsigned long long val = strtoull(code.c_str() + cs.iter, &numEnd, 2);
cs.addToken(new IntLit(val));
while(cs.peek(0) == '0' || cs.peek(0) == '1')
cs.getNext();
}
else if(isdigit(c))
{
//decimal integer or float literal
uint64_t intVal = 0;
//take the integer conversion, or the double conversion if it uses more chars
const char* numStart = code.c_str() + cs.iter - 1;
char* intEnd;
char* floatEnd;
//note: int/float literals are always positive
//'-' handled as arithmetic unary operator
//so IntLit holds an unsigned 64-bit value to cover all cases
intVal = strtoull(numStart, &intEnd, 10);
double floatVal = strtod(numStart, &floatEnd);
if(floatEnd > intEnd)
{
//use float
cs.addToken(new FloatLit(floatVal));
//advance the char stream by floatEnd - code.c_str() chars
for(const char* i = code.c_str() + cs.iter; i != floatEnd; i++)
{
cs.getNext();
}
}
else
{
//use int
cs.addToken(new IntLit(intVal));
for(const char* i = code.c_str() + cs.iter; i != intEnd; i++)
{
cs.getNext();
}
}
}
else if(ispunct(c))
{
//check for punctuation first (only 1 char)
auto punctIter = punctMap.find(c);
if(punctIter == punctMap.end())
{
//operator, not punct
//some operators are 2 chars long, use them if valid, otherwise 1 char
string oper1 = string("") + c;
string oper2 = oper1 + cs.peek();
auto oper2Iter = operatorMap.find(oper2);
if(oper2Iter == operatorMap.end())
{
//must be 1-char operator
auto oper1Iter = operatorMap.find(oper1);
if(oper1Iter == operatorMap.end())
{
cs.err(string("symbol character '") + oper1 + "' neither valid operator nor punctuation.");
}
else
{
cs.addToken(new Oper(oper1Iter->second));
}
}
else
{
cs.addToken(new Oper(oper2Iter->second));
cs.getNext();
}
}
else
{
//c is punct char
cs.addToken(new Punct(punctIter->second));
}
}
else
{
ERR_MSG("unexpected character: '" << c << "'\n");
}
}
}
char getEscapedChar(char ident)
{
if(ident == 'n')
return '\n';
if(ident == 't')
return '\t';
if(ident == '0')
return 0;
if(ident == '\\')
return '\\';
if(ident == 'r')
return '\r';
ERR_MSG(string("Unknown escape sequence: \\") + ident);
return ' ';
}
<|endoftext|>
|
<commit_before>#include "MFont.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
char* readFile(const char* path,const char* mode,long& size)
{
FILE* f;
fopen_s(&f,path,mode);
fseek(f,0,SEEK_END);
size = ftell(f);
fseek(f,0,SEEK_SET);
char* data=new char[size];
fread(data,1,size,f);
fclose(f);
return data;
}
#define FT_CEIL(X) (((X+63)&-64)/64)
#define FT_FLOOR(X) ((X&-64)/64)
void makeBitmap(MBitMap* bm,int w,int h)
{
bm->w=w;
bm->h=h;
bm->data=new uint[w*h];
memset(bm->data,0,bm->w*bm->h*sizeof(uint));
}
MFont::MFont()
{
mUsePo2=false;
for(int i=0;i<256;++i){
mChars[i].bm.data=0;
}
}
MFont::~MFont()
{
close();
}
bool MFont::load(const char* path,int size,uint color,MCOLORFORMAT format)
{
long s;
unsigned char* buffer=(unsigned char*)readFile(path,"rb",s);
bool r=loadFromMemory(buffer,s,size,color,format);
delete[]buffer;
return r;
}
bool MFont::loadFromMemory(const unsigned char* data,long dataSize,int size,uint color,MCOLORFORMAT format)
{
FT_Library library;
FT_Face face;
FT_GlyphSlot slot;
FT_Error error;
error = FT_Init_FreeType( &library );
if(error)
{
return false;
}
error=FT_New_Memory_Face(library,data,dataSize,0, &face );
if(error)
{
return false;
}
error = FT_Set_Char_Size(face,size*64,0,0,0);
slot = face->glyph;
FT_Fixed scale = face->size->metrics.y_scale;
int ascent=FT_CEIL(FT_MulFix(face->ascender, scale));
int descent=FT_CEIL(FT_MulFix(face->descender, scale));
mHeight=ascent-descent;
int n=0;
for ( n = 32; n < 128; n++ )
{
error =FT_Load_Glyph(face,FT_Get_Char_Index(face,n),FT_LOAD_DEFAULT);
FT_Render_Glyph(slot,FT_RENDER_MODE_NORMAL);
if ( error )
continue;
MChar& c=mChars[n];
c.xAdvance=FT_CEIL(slot->metrics.horiAdvance);
c.yoff=ascent-FT_FLOOR(slot->metrics.horiBearingY);
makeBitmap(&c.bm,slot->bitmap.width,slot->bitmap.rows);
if(format==M_BGR)
color=color& 0x00FFFFFF;
else color=color&0xFFFFFF00;
for(int i=0;i<c.bm.h;++i)
{
for(int j=0;j<c.bm.w;++j)
{
int id=i*c.bm.w+j;
if(format==M_BGR){
unsigned int y=0xFFFFFFFF&slot->bitmap.buffer[id];
y=y<<24;
c.bm.data[id]=y;
}
else
{
c.bm.data[id]=slot->bitmap.buffer[id];
}
}
}
}
mColor=color;
FT_Done_Face(face);
FT_Done_FreeType( library );
return true;
}
void MFont::setPowerOf2Sizes(bool usePo2)
{
mUsePo2=usePo2;
}
static int po2(int x)
{
int z = 1;
while ( z < x ) {
z <<= 1;
}
return z;
}
void MFont::makeText(const char* text,MBitMap* out)
{
int w=0;
unsigned int l=strlen(text);
for(unsigned int i=0;i<l;++i)
{
MChar &h=mChars[text[i]];
w+=h.bm.w>h.xAdvance?h.bm.w:h.xAdvance;
}
int h=mHeight;
if(mUsePo2){
w=po2(w);
h=po2(mHeight);
}
makeBitmap(out,w,h);
w=0;
for(unsigned i=0;i<l;++i)
{
MChar &h=mChars[text[i]];
fillBitmap(h.bm,*out,w,h.yoff);
w+=h.xAdvance;
}
}
void MFont::generateAtlas(MBitMap* atlas,int firstChar,int lastChar)
{
++lastChar;
int w=0;
int y=0;
int targetW=1024;
int targetY=mHeight;
bool b=false;
int yy=mChars[firstChar].bm.h;
for(int i=firstChar;i<lastChar;++i)
{
MChar &h=mChars[i];
w+=h.bm.w;
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w>=targetW)
{
w=0;
targetY+=yy;
b=true;
}
}
if(!b)
targetW=w;
if(mUsePo2)
{
targetW=po2(targetW);
targetY=po2(targetY);
}
makeBitmap(atlas,targetW,targetY);
w=0;
y=0;
yy=mChars[firstChar].bm.h;
for(int i=firstChar;i<lastChar;++i)
{
MChar &h=mChars[i];
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w+h.bm.w>=targetW)
{
w=0;
y+=yy;
}
h.x=w;
h.y=y;
h.uv.u0=(float)w/targetW;
h.uv.v0=(float)y/targetY;
h.uv.u1=(float)(w+h.bm.w)/targetW;
h.uv.v1=(float)(y+h.bm.h)/targetY;
fillBitmap(mChars[i].bm,*atlas,w,y);
w+=h.bm.w;
}
}
void MFont::generateAtlas(MBitMap* atlas,const char* atlasChars)
{
int w=0;
int y=0;
int targetW=1024;
int targetY=mHeight;
bool b=false;
int l=strlen(atlasChars);
int yy=mChars[atlasChars[0]].bm.h;
for(int i=0;i<l;++i)
{
MChar &h=mChars[atlasChars[i]];
w+=h.bm.w;
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w>=targetW)
{
w=0;
targetY+=yy;
b=true;
}
}
if(!b)
targetW=w;
if(mUsePo2)
{
targetW=po2(targetW);
targetY=po2(targetY);
}
makeBitmap(atlas,targetW,targetY);
w=0;
y=0;
yy=mChars[atlasChars[0]].bm.h;
for(int i=0;i<l;++i)
{
MChar &h=mChars[atlasChars[i]];
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w+h.bm.w>=targetW)
{
w=0;
y+=yy;
}
h.x=w;
h.y=y;
h.uv.u0=(float)w/targetW;
h.uv.v0=(float)y/targetY;
h.uv.u1=(float)(w+h.bm.w)/targetW;
h.uv.v1=(float)(y+h.bm.h)/targetY;
fillBitmap(mChars[atlasChars[i]].bm,*atlas,w,y);
w+=h.bm.w;
}
}
void MFont::getUv(char c,float& u0,float& v0
,float& u1,float& v1)
{
MChar&h= mChars[c];
u0=h.uv.u0;
u1=h.uv.u1;
v0=h.uv.v0;
v1=h.uv.v1;
}
void MFont::getCharRect(char c,int& x,int& y
,int& w,int& h)
{
MChar& hr= mChars[c];
x=hr.x;
y=hr.y;
w=hr.bm.w;
h=hr.bm.h;
}
inline void MFont::setColor(uint color)
{
mColor=color;
}
unsigned int MFont::Mrgb(int r,int g,int b)
{
return ((r<<24)|(g<<16)|b<<8|0);
}
unsigned int MFont::Mbgr(int g,int b,int r)
{
return (0|g<<16|b<<8|r);
}
int MFont::textWidth(const char* text)
{
int w=0;
int l=strlen(text);
for(int i=0;i<l;++i)
{
w+=mChars[text[i]].xAdvance;
}
return w;
}
void MFont::freeBm(MBitMap* bm)
{
if(bm->data){
delete bm->data;
bm->data=0;
}
}
void MFont::close()
{
for(int i=32;i<128;++i){
freeBm(&mChars[i].bm);
}
}
void MFont::fillBitmap(const MBitMap& src,MBitMap& dst,int x,int y)
{
for(int i=0;i<src.h;++i)
{
for(int j=0;j<src.w;++j)
{
unsigned int & d=dst.data[(i+y)*dst.w+j+x];
unsigned int & s=src.data[i*src.w+j];
if(x+j>=dst.w)
break;
if(s){
d|=(s|mColor);
}
}
}
}
<commit_msg>Update MFont.cpp<commit_after>#include "MFont.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include FT_OUTLINE_H
#include FT_STROKER_H
char* readFile(const char* path,const char* mode,long& size)
{
FILE* f;
fopen_s(&f,path,mode);
fseek(f,0,SEEK_END);
size = ftell(f);
fseek(f,0,SEEK_SET);
char* data=new char[size];
fread(data,1,size,f);
fclose(f);
return data;
}
#define FT_CEIL(X) (((X+63)&-64)/64)
#define FT_FLOOR(X) ((X&-64)/64)
void makeBitmap(MBitMap* bm,int w,int h)
{
bm->w=w;
bm->h=h;
bm->data=new uint[w*h];
memset(bm->data,0,bm->w*bm->h*sizeof(uint));
}
MFont::MFont()
{
mUsePo2=false;
for(int i=0;i<256;++i){
mChars[i].bm.data=0;
}
mBold=mItalic=mOutline=false;
}
MFont::~MFont()
{
close();
}
bool MFont::load(const char* path,int size,uint color,MCOLORFORMAT format)
{
long s;
unsigned char* buffer=(unsigned char*)readFile(path,"rb",s);
bool r=loadFromMemory(buffer,s,size,color,format);
delete[]buffer;
return r;
}
bool MFont::loadFromMemory(const unsigned char* data,long dataSize,int size,uint color,MCOLORFORMAT format)
{
FT_Library library;
FT_Face face;
FT_GlyphSlot slot;
FT_Error error;
error = FT_Init_FreeType( &library );
if(error)
{
return false;
}
error=FT_New_Memory_Face(library,data,dataSize,0, &face );
if(error)
{
return false;
}
error = FT_Set_Char_Size(face,size*64,0,0,0);
slot = face->glyph;
FT_Fixed scale = face->size->metrics.y_scale;
int ascent=FT_CEIL(FT_MulFix(face->ascender, scale));
int descent=FT_CEIL(FT_MulFix(face->descender, scale));
mHeight=ascent-descent;
FT_Matrix shear;
if(mItalic){
shear.xx = 1 << 16;
shear.xy = (int) ( 0.207f*mHeight* ( 1 << 16 ) ) / mHeight;
shear.yx = 0;
shear.yy = 1 << 16;
}
int n=0;
for ( n = 32; n < 128; n++ )
{
error =FT_Load_Glyph(face,FT_Get_Char_Index(face,n),FT_LOAD_DEFAULT);
if(mItalic)
FT_Outline_Transform(&slot->outline, &shear );
if(mOutline)
{
FT_Stroker stroker;
FT_Glyph bitmap_glyph;
FT_Get_Glyph( slot, &bitmap_glyph );
error = FT_Stroker_New( library, &stroker );
if ( error ) {
return false;
}
FT_Stroker_Set(stroker,1*64,FT_STROKER_LINECAP_BUTT,FT_STROKER_LINEJOIN_BEVEL, 0 );
FT_Glyph_Stroke(&bitmap_glyph,stroker,1);
FT_Stroker_Done(stroker);
FT_Glyph_To_Bitmap(&bitmap_glyph,ft_render_mode_normal, 0, 1 );
slot->bitmap=((FT_BitmapGlyph)(bitmap_glyph))->bitmap;
}
else {
error=FT_Render_Glyph(slot,FT_RENDER_MODE_NORMAL);
}
if ( error )
continue;
MChar& c=mChars[n];
c.xAdvance=FT_CEIL(slot->metrics.horiAdvance);
c.yoff=ascent-FT_FLOOR(slot->metrics.horiBearingY);
makeBitmap(&c.bm,slot->bitmap.width,slot->bitmap.rows);
if(format==M_BGR)
color=color& 0x00FFFFFF;
else color=color&0xFFFFFF00;
for(int i=0;i<c.bm.h;++i)
{
for(int j=0;j<c.bm.w;++j)
{
int id=i*c.bm.w+j;
if(format==M_BGR){
unsigned int y=0xFFFFFFFF&slot->bitmap.buffer[id];
y=y<<24;
c.bm.data[id]=y;
}
else
{
c.bm.data[id]=slot->bitmap.buffer[id];
}
}
}
}
mColor=color;
FT_Done_Face(face);
FT_Done_FreeType( library );
return true;
}
void MFont::setPowerOf2Sizes(bool usePo2)
{
mUsePo2=usePo2;
}
static int po2(int x)
{
int z = 1;
while ( z < x ) {
z <<= 1;
}
return z;
}
void MFont::makeText(const char* text,MBitMap* out)
{
int w=0;
unsigned int l=strlen(text);
for(unsigned int i=0;i<l;++i)
{
MChar &h=mChars[text[i]];
w+=h.bm.w>h.xAdvance?h.bm.w:h.xAdvance;
}
int h=mHeight;
if(mUsePo2){
w=po2(w);
h=po2(mHeight);
}
makeBitmap(out,w,h);
w=0;
for(unsigned i=0;i<l;++i)
{
MChar &h=mChars[text[i]];
fillBitmap(h.bm,*out,w,h.yoff);
w+=h.xAdvance;
}
}
void MFont::generateAtlas(MBitMap* atlas,int firstChar,int lastChar)
{
++lastChar;
int w=0;
int y=0;
int targetW=1024;
int targetY=mHeight;
bool b=false;
int yy=mChars[firstChar].bm.h;
for(int i=firstChar;i<lastChar;++i)
{
MChar &h=mChars[i];
w+=h.bm.w;
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w>=targetW)
{
w=0;
targetY+=yy;
b=true;
}
}
if(!b)
targetW=w;
if(mUsePo2)
{
targetW=po2(targetW);
targetY=po2(targetY);
}
makeBitmap(atlas,targetW,targetY);
w=0;
y=0;
yy=mChars[firstChar].bm.h;
for(int i=firstChar;i<lastChar;++i)
{
MChar &h=mChars[i];
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w+h.bm.w>=targetW)
{
w=0;
y+=yy;
}
h.x=w;
h.y=y;
h.uv.u0=(float)w/targetW;
h.uv.v0=(float)y/targetY;
h.uv.u1=(float)(w+h.bm.w)/targetW;
h.uv.v1=(float)(y+h.bm.h)/targetY;
fillBitmap(mChars[i].bm,*atlas,w,y);
w+=h.bm.w;
}
}
void MFont::generateAtlas(MBitMap* atlas,const char* atlasChars)
{
int w=0;
int y=0;
int targetW=1024;
int targetY=mHeight;
bool b=false;
int l=strlen(atlasChars);
int yy=mChars[atlasChars[0]].bm.h;
for(int i=0;i<l;++i)
{
MChar &h=mChars[atlasChars[i]];
w+=h.bm.w;
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w>=targetW)
{
w=0;
targetY+=yy;
b=true;
}
}
if(!b)
targetW=w;
if(mUsePo2)
{
targetW=po2(targetW);
targetY=po2(targetY);
}
makeBitmap(atlas,targetW,targetY);
w=0;
y=0;
yy=mChars[atlasChars[0]].bm.h;
for(int i=0;i<l;++i)
{
MChar &h=mChars[atlasChars[i]];
if(yy<h.bm.h){
yy=h.bm.h;
}
if(w+h.bm.w>=targetW)
{
w=0;
y+=yy;
}
h.x=w;
h.y=y;
h.uv.u0=(float)w/targetW;
h.uv.v0=(float)y/targetY;
h.uv.u1=(float)(w+h.bm.w)/targetW;
h.uv.v1=(float)(y+h.bm.h)/targetY;
fillBitmap(mChars[atlasChars[i]].bm,*atlas,w,y);
w+=h.bm.w;
}
}
void MFont::getUv(char c,float& u0,float& v0
,float& u1,float& v1)
{
MChar&h= mChars[c];
u0=h.uv.u0;
u1=h.uv.u1;
v0=h.uv.v0;
v1=h.uv.v1;
}
void MFont::getCharRect(char c,int& x,int& y
,int& w,int& h)
{
MChar& hr= mChars[c];
x=hr.x;
y=hr.y;
w=hr.bm.w;
h=hr.bm.h;
}
inline void MFont::setColor(uint color)
{
mColor=color;
}
unsigned int MFont::Mrgb(int r,int g,int b)
{
return ((r<<24)|(g<<16)|b<<8|0);
}
unsigned int MFont::Mbgr(int g,int b,int r)
{
return (0|g<<16|b<<8|r);
}
int MFont::textWidth(const char* text)
{
int w=0;
int l=strlen(text);
for(int i=0;i<l;++i)
{
w+=mChars[text[i]].xAdvance;
}
return w;
}
void MFont::freeBm(MBitMap* bm)
{
if(bm->data){
delete bm->data;
bm->data=0;
}
}
void MFont::close()
{
for(int i=32;i<128;++i){
freeBm(&mChars[i].bm);
}
}
void MFont::fillBitmap(const MBitMap& src,MBitMap& dst,int x,int y)
{
for(int i=0;i<src.h;++i)
{
for(int j=0;j<src.w;++j)
{
unsigned int & d=dst.data[(i+y)*dst.w+j+x];
unsigned int & s=src.data[i*src.w+j];
if(x+j>=dst.w)
break;
if(s){
d|=(s|mColor);
}
}
}
}
void MFont::setStyle(bool italic,bool outline)
{
mOutline=outline;
mItalic=italic;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 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)
//=======================================================================
#include "Nodes.hpp"
#include "StringPool.hpp"
#include "Options.hpp"
#include "AssemblyFileWriter.hpp"
#include "Context.hpp"
#include "Functions.hpp"
#include <cassert>
using std::string;
using std::endl;
using std::map;
using namespace eddic;
void Program::addFunction(std::shared_ptr<Function> function){
functions[function->mangledName()] = function;
addLast(function);
}
bool Program::exists(string function){
return functions.find(function) != functions.end();
}
void Program::write(AssemblyFileWriter& writer){
ParseNode::write(writer);
//Write the global variables
context()->write(writer);
}
static void writePrintString(std::ofstream& m_stream) {
m_stream << std::endl;
m_stream << "print_string:" << std::endl;
m_stream << "pushl %ebp" << std::endl;
m_stream << "movl %esp, %ebp" << std::endl;
m_stream << "movl $0, %esi" << std::endl;
m_stream << "movl $4, %eax" << std::endl;
m_stream << "movl $1, %ebx" << std::endl;
m_stream << "movl 12(%ebp), %ecx" << std::endl;
m_stream << "movl 8(%ebp), %edx" << std::endl;
m_stream << "int $0x80" << std::endl;
m_stream << "leave" << std::endl;
m_stream << "ret" << std::endl;
}
static void writePrintLine(std::ofstream& m_stream) {
m_stream << std::endl;
m_stream << "print_line:" << std::endl;
m_stream << "pushl %ebp" << std::endl;
m_stream << "movl %esp, %ebp" << std::endl;
m_stream << "pushl $S1" << endl;
m_stream << "pushl $1" << endl;
m_stream << "call print_string" << endl;
m_stream << "addl $8, %esp" << endl;
m_stream << "leave" << std::endl;
m_stream << "ret" << std::endl;
}
static void writePrintInteger(std::ofstream& m_stream) {
m_stream << std::endl;
m_stream << "print_integer:" << std::endl
<< "pushl %ebp" << std::endl
<< "movl %esp, %ebp" << std::endl
<< "movl 8(%ebp), %eax" << std::endl
<< "xorl %esi, %esi" << std::endl
<< "loop:" << std::endl
<< "movl $0, %edx" << std::endl
<< "movl $10, %ebx" << std::endl
<< "divl %ebx" << std::endl
<< "addl $48, %edx" << std::endl
<< "pushl %edx" << std::endl
<< "incl %esi" << std::endl
<< "cmpl $0, %eax" << std::endl
<< "jz next" << std::endl
<< "jmp loop" << std::endl
<< "next:" << std::endl
<< "cmpl $0, %esi" << std::endl
<< "jz exit" << std::endl
<< "decl %esi" << std::endl
<< "movl $4, %eax" << std::endl
<< "movl %esp, %ecx" << std::endl
<< "movl $1, %ebx" << std::endl
<< "movl $1, %edx" << std::endl
<< "int $0x80" << std::endl
<< "addl $4, %esp" << std::endl
<< "jmp next" << std::endl
<< "exit:" << std::endl
<< "leave" << std::endl
<< "ret" << std::endl;
}
static void writeConcat(std::ofstream& m_stream){
m_stream << std::endl;
m_stream << "concat:" << std::endl
<< "pushl %ebp" << std::endl
<< "movl %esp, %ebp" << std::endl
<< "movl 16(%ebp), %edx" << std::endl
<< "movl 8(%ebp), %ecx" << std::endl
<< "addl %ecx, %edx" << std::endl
<< "pushl %edx" << std::endl
<< "call malloc" << std::endl
<< "addl $4, %esp" << std::endl
<< "movl %eax, -4(%ebp)" << std::endl
<< "movl %eax, %ecx" << std::endl
<< "movl $0, %eax" << std::endl
<< "movl 16(%ebp), %ebx" << std::endl
<< "movl 20(%ebp), %edx" << std::endl
<< "copy_concat_1:" << std::endl
<< "cmpl $0, %ebx" << std::endl
<< "je end_concat_1" << std::endl
<< "movb (%edx), %al" << std::endl
<< "movb %al, (%ecx)" << std::endl
<< "addl $1, %ecx" << std::endl
<< "addl $1, %edx" << std::endl
<< "subl $1, %ebx" << std::endl
<< "jmp copy_concat_1" << std::endl
<< "end_concat_1" << ":" << std::endl
<< "movl 8(%ebp), %ebx" << std::endl
<< "movl 12(%ebp), %edx" << std::endl
<< "copy_concat_2:" << std::endl
<< "cmpl $0, %ebx" << std::endl
<< "je end_concat_2" << std::endl
<< "movb (%edx), %al" << std::endl
<< "movb %al, (%ecx)" << std::endl
<< "addl $1, %ecx" << std::endl
<< "addl $1, %edx" << std::endl
<< "subl $1, %ebx" << std::endl
<< "jmp copy_concat_2" << std::endl
<< "end_concat_2:" << std::endl
<< "movl 16(%ebp), %edx" << std::endl
<< "movl 8(%ebp), %ecx" << std::endl
<< "addl %ecx, %edx" << std::endl
<< "movl -4(%ebp), %eax" << std::endl
<< "leave" << std::endl
<< "ret" << std::endl;
}
void Methods::write(AssemblyFileWriter& writer) {
writePrintString(writer.stream());
writePrintInteger(writer.stream());
writePrintLine(writer.stream());
writeConcat(writer.stream());
}
void Declaration::checkVariables() {
if (context()->exists(m_variable)) {
throw CompilerException("Variable has already been declared", token());
}
m_var = context()->addVariable(m_variable, m_type);
value->checkVariables();
if (value->type() != m_type) {
throw CompilerException("Incompatible type", token());
}
}
void VariableOperation::checkStrings(StringPool& pool) {
value->checkStrings(pool);
}
void Assignment::checkVariables() {
if (!context()->exists(m_variable)) {
throw CompilerException("Variable has not been declared", token());
}
m_var = context()->getVariable(m_variable);
value->checkVariables();
if (value->type() != m_var->type()) {
throw CompilerException("Incompatible type", token());
}
}
void Swap::checkVariables() {
if (m_lhs == m_rhs) {
throw CompilerException("Cannot swap a variable with itself", token());
}
if (!context()->exists(m_lhs) || !context()->exists(m_rhs)) {
throw CompilerException("Variable has not been declared", token());
}
m_lhs_var = context()->getVariable(m_lhs);
m_rhs_var = context()->getVariable(m_rhs);
if (m_lhs_var->type() != m_rhs_var->type()) {
throw CompilerException("Incompatible type", token());
}
m_type = m_lhs_var->type();
}
void VariableValue::checkVariables() {
if (!context()->exists(m_variable)) {
throw CompilerException("Variable has not been declared", token());
}
m_var = context()->getVariable(m_variable);
m_type = m_var->type();
}
void Litteral::checkStrings(StringPool& pool) {
m_label = pool.label(m_litteral);
}
void VariableOperation::write(AssemblyFileWriter& writer) {
value->write(writer);
m_var->popFromStack(writer);
}
void Swap::write(AssemblyFileWriter& writer) {
switch (m_type) {
case INT:
m_lhs_var->moveToRegister(writer, "%eax");
m_rhs_var->moveToRegister(writer, "%ebx");
m_lhs_var->moveFromRegister(writer, "%ebx");
m_rhs_var->moveFromRegister(writer, "%eax");
break;
case STRING:
m_lhs_var->moveToRegister(writer, "%eax", "%ebx");
m_rhs_var->moveToRegister(writer, "%ecx", "%edx");
m_lhs_var->moveFromRegister(writer, "%ecx", "%edx");
m_rhs_var->moveFromRegister(writer, "%eax", "%ebx");
break;
}
}
void Print::write(AssemblyFileWriter& writer) {
value->write(writer);
switch (value->type()) {
case INT:
writer.stream() << "call print_integer" << endl;
writer.stream() << "addl $4, %esp" << endl;
break;
case STRING:
writer.stream() << "call print_string" << endl;
writer.stream() << "addl $8, %esp" << endl;
break;
}
}
void Println::write(AssemblyFileWriter& writer) {
Print::write(writer);
writer.stream() << "call print_line" << endl;
}
void Print::checkStrings(StringPool& pool) {
value->checkStrings(pool);
}
void Print::checkVariables() {
value->checkVariables();
}
void Integer::write(AssemblyFileWriter& writer) {
writer.stream() << "pushl $" << m_value << std::endl;
}
void VariableValue::write(AssemblyFileWriter& writer) {
m_var->pushToStack(writer);
}
void Litteral::write(AssemblyFileWriter& writer) {
writer.stream() << "pushl $" << m_label << std::endl;
writer.stream() << "pushl $" << (m_litteral.size() - 2) << std::endl;
}
//Constantness
bool Value::isConstant() {
return false;
}
bool Litteral::isConstant() {
return true;
}
bool Integer::isConstant() {
return true;
}
bool VariableValue::isConstant() {
return false;
}
//Values
string Value::getStringValue() {
throw "Not constant";
}
int Value::getIntValue() {
throw "Not constant";
}
int Integer::getIntValue() {
return m_value;
}
string Litteral::getStringValue() {
return m_litteral;
}
<commit_msg>Remove tabs<commit_after>//=======================================================================
// Copyright Baptiste Wicht 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)
//=======================================================================
#include "Nodes.hpp"
#include "StringPool.hpp"
#include "Options.hpp"
#include "AssemblyFileWriter.hpp"
#include "Context.hpp"
#include "Functions.hpp"
#include <cassert>
using std::string;
using std::endl;
using std::map;
using namespace eddic;
void Program::addFunction(std::shared_ptr<Function> function){
functions[function->mangledName()] = function;
addLast(function);
}
bool Program::exists(string function){
return functions.find(function) != functions.end();
}
void Program::write(AssemblyFileWriter& writer){
ParseNode::write(writer);
//Write the global variables
context()->write(writer);
}
static void writePrintString(std::ofstream& m_stream) {
m_stream << std::endl;
m_stream << "print_string:" << std::endl;
m_stream << "pushl %ebp" << std::endl;
m_stream << "movl %esp, %ebp" << std::endl;
m_stream << "movl $0, %esi" << std::endl;
m_stream << "movl $4, %eax" << std::endl;
m_stream << "movl $1, %ebx" << std::endl;
m_stream << "movl 12(%ebp), %ecx" << std::endl;
m_stream << "movl 8(%ebp), %edx" << std::endl;
m_stream << "int $0x80" << std::endl;
m_stream << "leave" << std::endl;
m_stream << "ret" << std::endl;
}
static void writePrintLine(std::ofstream& m_stream) {
m_stream << std::endl;
m_stream << "print_line:" << std::endl;
m_stream << "pushl %ebp" << std::endl;
m_stream << "movl %esp, %ebp" << std::endl;
m_stream << "pushl $S1" << endl;
m_stream << "pushl $1" << endl;
m_stream << "call print_string" << endl;
m_stream << "addl $8, %esp" << endl;
m_stream << "leave" << std::endl;
m_stream << "ret" << std::endl;
}
static void writePrintInteger(std::ofstream& m_stream) {
m_stream << std::endl;
m_stream << "print_integer:" << std::endl
<< "pushl %ebp" << std::endl
<< "movl %esp, %ebp" << std::endl
<< "movl 8(%ebp), %eax" << std::endl
<< "xorl %esi, %esi" << std::endl
<< "loop:" << std::endl
<< "movl $0, %edx" << std::endl
<< "movl $10, %ebx" << std::endl
<< "divl %ebx" << std::endl
<< "addl $48, %edx" << std::endl
<< "pushl %edx" << std::endl
<< "incl %esi" << std::endl
<< "cmpl $0, %eax" << std::endl
<< "jz next" << std::endl
<< "jmp loop" << std::endl
<< "next:" << std::endl
<< "cmpl $0, %esi" << std::endl
<< "jz exit" << std::endl
<< "decl %esi" << std::endl
<< "movl $4, %eax" << std::endl
<< "movl %esp, %ecx" << std::endl
<< "movl $1, %ebx" << std::endl
<< "movl $1, %edx" << std::endl
<< "int $0x80" << std::endl
<< "addl $4, %esp" << std::endl
<< "jmp next" << std::endl
<< "exit:" << std::endl
<< "leave" << std::endl
<< "ret" << std::endl;
}
static void writeConcat(std::ofstream& m_stream){
m_stream << std::endl;
m_stream << "concat:" << std::endl
<< "pushl %ebp" << std::endl
<< "movl %esp, %ebp" << std::endl
<< "movl 16(%ebp), %edx" << std::endl
<< "movl 8(%ebp), %ecx" << std::endl
<< "addl %ecx, %edx" << std::endl
<< "pushl %edx" << std::endl
<< "call malloc" << std::endl
<< "addl $4, %esp" << std::endl
<< "movl %eax, -4(%ebp)" << std::endl
<< "movl %eax, %ecx" << std::endl
<< "movl $0, %eax" << std::endl
<< "movl 16(%ebp), %ebx" << std::endl
<< "movl 20(%ebp), %edx" << std::endl
<< "copy_concat_1:" << std::endl
<< "cmpl $0, %ebx" << std::endl
<< "je end_concat_1" << std::endl
<< "movb (%edx), %al" << std::endl
<< "movb %al, (%ecx)" << std::endl
<< "addl $1, %ecx" << std::endl
<< "addl $1, %edx" << std::endl
<< "subl $1, %ebx" << std::endl
<< "jmp copy_concat_1" << std::endl
<< "end_concat_1" << ":" << std::endl
<< "movl 8(%ebp), %ebx" << std::endl
<< "movl 12(%ebp), %edx" << std::endl
<< "copy_concat_2:" << std::endl
<< "cmpl $0, %ebx" << std::endl
<< "je end_concat_2" << std::endl
<< "movb (%edx), %al" << std::endl
<< "movb %al, (%ecx)" << std::endl
<< "addl $1, %ecx" << std::endl
<< "addl $1, %edx" << std::endl
<< "subl $1, %ebx" << std::endl
<< "jmp copy_concat_2" << std::endl
<< "end_concat_2:" << std::endl
<< "movl 16(%ebp), %edx" << std::endl
<< "movl 8(%ebp), %ecx" << std::endl
<< "addl %ecx, %edx" << std::endl
<< "movl -4(%ebp), %eax" << std::endl
<< "leave" << std::endl
<< "ret" << std::endl;
}
void Methods::write(AssemblyFileWriter& writer) {
writePrintString(writer.stream());
writePrintInteger(writer.stream());
writePrintLine(writer.stream());
writeConcat(writer.stream());
}
void Declaration::checkVariables() {
if (context()->exists(m_variable)) {
throw CompilerException("Variable has already been declared", token());
}
m_var = context()->addVariable(m_variable, m_type);
value->checkVariables();
if (value->type() != m_type) {
throw CompilerException("Incompatible type", token());
}
}
void VariableOperation::checkStrings(StringPool& pool) {
value->checkStrings(pool);
}
void Assignment::checkVariables() {
if (!context()->exists(m_variable)) {
throw CompilerException("Variable has not been declared", token());
}
m_var = context()->getVariable(m_variable);
value->checkVariables();
if (value->type() != m_var->type()) {
throw CompilerException("Incompatible type", token());
}
}
void Swap::checkVariables() {
if (m_lhs == m_rhs) {
throw CompilerException("Cannot swap a variable with itself", token());
}
if (!context()->exists(m_lhs) || !context()->exists(m_rhs)) {
throw CompilerException("Variable has not been declared", token());
}
m_lhs_var = context()->getVariable(m_lhs);
m_rhs_var = context()->getVariable(m_rhs);
if (m_lhs_var->type() != m_rhs_var->type()) {
throw CompilerException("Incompatible type", token());
}
m_type = m_lhs_var->type();
}
void VariableValue::checkVariables() {
if (!context()->exists(m_variable)) {
throw CompilerException("Variable has not been declared", token());
}
m_var = context()->getVariable(m_variable);
m_type = m_var->type();
}
void Litteral::checkStrings(StringPool& pool) {
m_label = pool.label(m_litteral);
}
void VariableOperation::write(AssemblyFileWriter& writer) {
value->write(writer);
m_var->popFromStack(writer);
}
void Swap::write(AssemblyFileWriter& writer) {
switch (m_type) {
case INT:
m_lhs_var->moveToRegister(writer, "%eax");
m_rhs_var->moveToRegister(writer, "%ebx");
m_lhs_var->moveFromRegister(writer, "%ebx");
m_rhs_var->moveFromRegister(writer, "%eax");
break;
case STRING:
m_lhs_var->moveToRegister(writer, "%eax", "%ebx");
m_rhs_var->moveToRegister(writer, "%ecx", "%edx");
m_lhs_var->moveFromRegister(writer, "%ecx", "%edx");
m_rhs_var->moveFromRegister(writer, "%eax", "%ebx");
break;
}
}
void Print::write(AssemblyFileWriter& writer) {
value->write(writer);
switch (value->type()) {
case INT:
writer.stream() << "call print_integer" << endl;
writer.stream() << "addl $4, %esp" << endl;
break;
case STRING:
writer.stream() << "call print_string" << endl;
writer.stream() << "addl $8, %esp" << endl;
break;
}
}
void Println::write(AssemblyFileWriter& writer) {
Print::write(writer);
writer.stream() << "call print_line" << endl;
}
void Print::checkStrings(StringPool& pool) {
value->checkStrings(pool);
}
void Print::checkVariables() {
value->checkVariables();
}
void Integer::write(AssemblyFileWriter& writer) {
writer.stream() << "pushl $" << m_value << std::endl;
}
void VariableValue::write(AssemblyFileWriter& writer) {
m_var->pushToStack(writer);
}
void Litteral::write(AssemblyFileWriter& writer) {
writer.stream() << "pushl $" << m_label << std::endl;
writer.stream() << "pushl $" << (m_litteral.size() - 2) << std::endl;
}
//Constantness
bool Value::isConstant() {
return false;
}
bool Litteral::isConstant() {
return true;
}
bool Integer::isConstant() {
return true;
}
bool VariableValue::isConstant() {
return false;
}
//Values
string Value::getStringValue() {
throw "Not constant";
}
int Value::getIntValue() {
throw "Not constant";
}
int Integer::getIntValue() {
return m_value;
}
string Litteral::getStringValue() {
return m_litteral;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ids.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:57:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#include "ids.hxx"
IMPLEMENT_IMPLEMENTATIONID_HELPER(frm, OImplementationIds)
<commit_msg>INTEGRATION: CWS changefileheader (1.3.134); FILE MERGED 2008/03/31 13:11:39 rt 1.3.134.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ids.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#include "ids.hxx"
IMPLEMENT_IMPLEMENTATIONID_HELPER(frm, OImplementationIds)
<|endoftext|>
|
<commit_before>#include "Scene.h"
#include "Mesh.h"
#include "Sound.h"
#include "Light.h"
#include "Material.h"
#include "kit/meta/meta.h"
using namespace std;
Scene :: Scene(const string& fn, Cache<Resource, std::string>* cache):
//Resource(fn),
m_pConfig(make_shared<Meta>(fn)),
m_Filename(fn),
m_pCache(cache),
m_pRoot(make_shared<Node>())
//m_pData(make_shared<Meta>(fn))
{
load();
}
void Scene :: iterate_data(const std::shared_ptr<Meta>& doc)
{
string name = doc->at<string>("name", string());
string type = doc->at<string>("type", string());
//LOGf("data: %s: %s", name % type);
try{
if(type == "mesh")
m_pCache->cache_cast<Mesh::Data>(m_Filename + ":" + doc->at<string>("name"));
else if(type == "material")
m_pCache->cache_cast<Material>(doc->at<string>("image"));
}catch(const Error& e){
}catch(const std::exception& e){
WARNING(e.what());
}
}
glm::mat4 Scene :: deserialize_matrix(const std::shared_ptr<Meta>& mat)
{
//if(not mat->empty())
return glm::mat4(
mat->at<double>(0),
mat->at<double>(1),
mat->at<double>(2),
mat->at<double>(3),
mat->at<double>(4),
mat->at<double>(5),
mat->at<double>(6),
mat->at<double>(7),
mat->at<double>(8),
mat->at<double>(9),
mat->at<double>(10),
mat->at<double>(11),
mat->at<double>(12),
mat->at<double>(13),
mat->at<double>(14),
mat->at<double>(15)
);
//else
// return glm::mat4(1.0f);
}
void Scene :: deserialize_node(std::shared_ptr<Node>& node, const std::shared_ptr<Meta>& doc)
{
string name = doc->at<string>("name", string());
node->name(name);
auto mat = doc->at<shared_ptr<Meta>>("matrix");
*node->matrix() = deserialize_matrix(mat);
}
void Scene :: iterate_node(const std::shared_ptr<Node>& parent, const std::shared_ptr<Meta>& doc)
{
shared_ptr<Node> node;
string name = doc->at<string>("name", string());
string type = doc->at<string>("type", string());
//LOGf("node: %s: %s", name % type);
//int light_count = 0;
// based on node type, create the node
if(type == "empty")
node = make_shared<Node>();
else if(type == "mesh")
{
//LOGf("mesh fn %s name %s", m_Filename % name);
auto data = doc->at<string>("data", string());
//if(name.find(":") != string::npos)
// return;
if(not data.empty())
node = make_shared<Mesh>(m_Filename + ":" + data, m_pCache);
}
else if(type == "sound")
{
string fn = doc->at<string>("sound", string());
if(not fn.empty()){
//LOGf("sound: %s", fn);
auto snd = make_shared<Sound>(fn, m_pCache);
node = snd;
}else{
//WARNINGf("Object %s has no sound file.");
}
}
else if(type == "light")
{
//if(++light_count <= 2)
//{
auto light = make_shared<Light>(doc);
auto color = doc->at<shared_ptr<Meta>>("color", make_shared<Meta>());
if(not color->empty())
{
light->diffuse(Color(
(float)color->at<double>(0),
(float)color->at<double>(1),
(float)color->at<double>(2)
));
light->specular(glm::vec3(1.0f, 1.0f, 1.0f));
}
node = light;
//}
}
if(not node)
node = make_shared<Node>();
try{
deserialize_node(node, doc);
//LOGf("matrix %s", Matrix::to_string(*node->matrix()));
parent->add(node);
node->pend();
}catch(const out_of_range&){}
try{
for(auto& e: *doc->meta("nodes"))
{
try{
iterate_node(node, e.as<std::shared_ptr<Meta>>());
}catch(const boost::bad_any_cast&){}
}
}catch(const out_of_range&){}
}
void Scene :: load()
{
auto grav = m_pConfig->meta("gravity", make_shared<Meta>(
MetaFormat::JSON, "[0.0, -9.8, 0.0]"
));
m_Gravity = glm::vec3(
grav->at<double>(0),
grav->at<double>(1),
grav->at<double>(2)
);
//for(auto& e: *m_pConfig->meta("data"))
//{
// try{
// iterate_data(e.as<std::shared_ptr<Meta>>());
// }catch(const boost::bad_any_cast&){}
//}
//m_pRoot = make_shared<Node>();
for(auto& e: *m_pConfig->meta("nodes"))
{
try{
iterate_node(m_pRoot, e.as<std::shared_ptr<Meta>>());
}catch(const boost::bad_any_cast&){}
}
}
<commit_msg>remove temp light location markers in scene<commit_after>#include "Scene.h"
#include "Mesh.h"
#include "Sound.h"
#include "Light.h"
#include "Material.h"
#include "Particle.h"
#include "kit/meta/meta.h"
using namespace std;
Scene :: Scene(const string& fn, Cache<Resource, std::string>* cache):
//Resource(fn),
m_pConfig(make_shared<Meta>(fn)),
m_Filename(fn),
m_pCache(cache),
m_pRoot(make_shared<Node>())
//m_pData(make_shared<Meta>(fn))
{
load();
}
void Scene :: iterate_data(const std::shared_ptr<Meta>& doc)
{
string name = doc->at<string>("name", string());
string type = doc->at<string>("type", string());
//LOGf("data: %s: %s", name % type);
try{
if(type == "mesh")
m_pCache->cache_cast<Mesh::Data>(m_Filename + ":" + doc->at<string>("name"));
else if(type == "material")
m_pCache->cache_cast<Material>(doc->at<string>("image"));
}catch(const Error& e){
}catch(const std::exception& e){
WARNING(e.what());
}
}
glm::mat4 Scene :: deserialize_matrix(const std::shared_ptr<Meta>& mat)
{
//if(not mat->empty())
return glm::mat4(
mat->at<double>(0),
mat->at<double>(1),
mat->at<double>(2),
mat->at<double>(3),
mat->at<double>(4),
mat->at<double>(5),
mat->at<double>(6),
mat->at<double>(7),
mat->at<double>(8),
mat->at<double>(9),
mat->at<double>(10),
mat->at<double>(11),
mat->at<double>(12),
mat->at<double>(13),
mat->at<double>(14),
mat->at<double>(15)
);
//else
// return glm::mat4(1.0f);
}
void Scene :: deserialize_node(std::shared_ptr<Node>& node, const std::shared_ptr<Meta>& doc)
{
string name = doc->at<string>("name", string());
node->name(name);
auto mat = doc->at<shared_ptr<Meta>>("matrix");
*node->matrix() = deserialize_matrix(mat);
}
void Scene :: iterate_node(const std::shared_ptr<Node>& parent, const std::shared_ptr<Meta>& doc)
{
shared_ptr<Node> node;
string name = doc->at<string>("name", string());
string type = doc->at<string>("type", string());
//LOGf("node: %s: %s", name % type);
//int light_count = 0;
// based on node type, create the node
if(type == "empty")
node = make_shared<Node>();
else if(type == "mesh")
{
//LOGf("mesh fn %s name %s", m_Filename % name);
auto data = doc->at<string>("data", string());
//if(name.find(":") != string::npos)
// return;
if(not data.empty())
node = make_shared<Mesh>(m_Filename + ":" + data, m_pCache);
}
else if(type == "sound")
{
string fn = doc->at<string>("sound", string());
if(not fn.empty()){
//LOGf("sound: %s", fn);
auto snd = make_shared<Sound>(fn, m_pCache);
node = snd;
}else{
//WARNINGf("Object %s has no sound file.");
}
}
else if(type == "light")
{
//if(++light_count <= 2)
//{
auto light = make_shared<Light>(doc);
auto color = doc->at<shared_ptr<Meta>>("color", make_shared<Meta>());
if(not color->empty())
{
light->diffuse(Color(
(float)color->at<double>(0),
(float)color->at<double>(1),
(float)color->at<double>(2)
));
light->specular(glm::vec3(1.0f, 1.0f, 1.0f));
}
node = light;
//light->add(make_shared<Particle>("particle.png", m_pCache)); // test light locations
//}
}
if(not node)
node = make_shared<Node>();
try{
deserialize_node(node, doc);
//LOGf("matrix %s", Matrix::to_string(*node->matrix()));
parent->add(node);
node->pend();
}catch(const out_of_range&){}
try{
for(auto& e: *doc->meta("nodes"))
{
try{
iterate_node(node, e.as<std::shared_ptr<Meta>>());
}catch(const boost::bad_any_cast&){}
}
}catch(const out_of_range&){}
}
void Scene :: load()
{
auto grav = m_pConfig->meta("gravity", make_shared<Meta>(
MetaFormat::JSON, "[0.0, -9.8, 0.0]"
));
m_Gravity = glm::vec3(
grav->at<double>(0),
grav->at<double>(1),
grav->at<double>(2)
);
//for(auto& e: *m_pConfig->meta("data"))
//{
// try{
// iterate_data(e.as<std::shared_ptr<Meta>>());
// }catch(const boost::bad_any_cast&){}
//}
//m_pRoot = make_shared<Node>();
for(auto& e: *m_pConfig->meta("nodes"))
{
try{
iterate_node(m_pRoot, e.as<std::shared_ptr<Meta>>());
}catch(const boost::bad_any_cast&){}
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <stdlib.h>
template<typename T>
class Stack {
public:
// Create empty stack
Stack();
// insert new item to stack
void insert(const T& item) {};
// remove and return most recently added item
T pop() {};
// check if stack is empty
bool isEmpty() {};
private:
struct Node {
T item_;
Node* next_;
Node(const T& item, Node* next):
item_(item),
next_(next)
{};
};
Node* first_ = nullptr;
size_t size = 0;
// Forbid copy and assignment
Stack(const Stack&);
Stack& operator=(const Stack&);
};
template<typename T>
Stack::Stack():
first_(nullptr)
{
}
<commit_msg>additional changes to Stack class<commit_after>#pragma once
#include <stdlib.h>
#include <stdexcept>
template<typename T>
class Stack {
public:
// Create empty stack
Stack() {};
~Stack();
// insert new item to stack
void insert(const T& item);
// remove and return most recently added item
T pop();
// check if stack is empty
bool isEmpty() { return first_ == nullptr;};
private:
// internal data container
struct Node {
T item_;
Node* next_;
Node(const T& item, Node* next):
item_(item),
next_(next)
{};
};
Node* first_ = nullptr;
size_t size_ = 0;
// Forbid copy and assignment
Stack(const Stack&);
Stack& operator=(const Stack&);
};
template<typename T>
void Stack<T>::insert(const T& item) {
first_ = new Node(item, first_);
++size_;
}
template<typename T>
T Stack<T>::pop() {
if(isEmpty()) throw std::runtime_error("Empty stack.");
Node* tmpNode = first_;
T tmpItem(tmpNode->item_);
delete tmpNode;
first_ = first_->next_;
--size_;
return tmpItem;
}
template<typename T>
Stack<T>::~Stack() {
Node* nextNode;
for (Node* tmpNode = first_; tmpNode != nullptr; tmpNode = nextNode) {
nextNode = tmpNode->next_;
delete tmpNode;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <Timer.hpp>
namespace isa {
namespace utils {
Timer::Timer() : stats(Stats< double >()), starting(std::chrono::high_resolution_clock::time_point()), totalTime(0.0), time(0.0) {}
void Timer::start() {
starting = std::chrono::high_resolution_clock::now();
}
void Timer::stop() {
time = (std::chrono::duration_cast< std::chrono::duration< double > >(std::chrono::high_resolution_clock::now() - starting)).count();
totalTime += time;
stats.addElement(time);
}
void Timer::reset() {
starting = std::chrono::high_resolution_clock::time_point();
totalTime = 0.0;
time = 0.0;
}
inline unsigned int Timer::getNrRuns() const {
return stats.getNrElements();
}
inline double Timer::getTotalTime() const {
return totalTime;
}
inline double Timer::getLastRunTime() const {
return time;
}
inline double Timer::getAverageTime() const {
return stats.getMean();
}
inline double Timer::getStandardDeviation() const {
return stats.getStandardDeviation();
}
inline double Timer::getCoefficientOfVariation() const {
return stats.getCoefficientOfVariation();
}
} // utils
} // isa
<commit_msg>Forgot a file.<commit_after>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <Timer.hpp>
namespace isa {
namespace utils {
Timer::Timer() : stats(Stats< double >()), starting(std::chrono::high_resolution_clock::time_point()), totalTime(0.0), time(0.0) {}
void Timer::start() {
starting = std::chrono::high_resolution_clock::now();
}
void Timer::stop() {
time = (std::chrono::duration_cast< std::chrono::duration< double > >(std::chrono::high_resolution_clock::now() - starting)).count();
totalTime += time;
stats.addElement(time);
}
void Timer::reset() {
starting = std::chrono::high_resolution_clock::time_point();
totalTime = 0.0;
time = 0.0;
}
} // utils
} // isa
<|endoftext|>
|
<commit_before>// ===================================================================
/**
* Implements robust overlap methods for convex bounding volumes.
* Also includes parser for processed trajectory files.
*/
// ===================================================================
/*
* Utils.cpp: Version 1.0
* Created 26/07/2016 by Maxime Tortora
*/
// ===================================================================
#include <fstream>
#include "Utils.hpp"
// ============================
/* Wrapper for MPI datatypes */
// ============================
template<> Utils<float> ::Utils(): MPI_type(MPI_FLOAT) {}
template<> Utils<double>::Utils(): MPI_type(MPI_DOUBLE) {}
template<> Utils<uint> ::Utils(): MPI_type(MPI_UNSIGNED) {}
template<> Utils<ullint>::Utils(): MPI_type(MPI_UNSIGNED_LONG_LONG) {}
// ============================
/* Bounding spherocylinders overlap test */
// ============================
template<typename number>
bool Utils<number>::OverlapBoundSC(const Vector3<number>& R_cm, BNode<number>* Node1, BNode<number>* Node2)
{
number xlambda;
number xmu;
number aux1;
number aux2;
number rm2;
Vector3<number> R_sep;
// Root spherocylinders centers are forced to the particle center of mass
if ( Node1->is_root && Node2->is_root ) R_sep = R_cm;
else if ( Node1->is_root ) R_sep = R_cm + Node2->Center;
else if ( Node2->is_root ) R_sep = R_cm - Node1->Center;
else R_sep = R_cm + Node2->Center - Node1->Center;
number rEo1 = Node1->Axis.dot(R_sep);
number rEo2 = Node2->Axis.dot(R_sep);;
number o1Eo2 = Node1->Axis.dot(Node2->Axis);
number rsqr = SQR(Node1->l_cr + Node2->l_cr);
number cc = 1. - SQR(o1Eo2);
/* VEGA ET AL., A FAST ALGORITHM TO EVALUATE THE SHORTEST DISTANCE BETWEEN RODS */
// Case Axis1, Axis2 colinear
if ( cc < TOL_SC )
{
if ( std::abs(rEo1) > TOL_SC )
{
xlambda = copysign(Node1->l_ch, rEo1);
xmu = xlambda*o1Eo2 - rEo2;
if ( std::abs(xmu) > Node2->l_ch ) xmu = copysign(Node2->l_ch, xmu);
}
else
{
xlambda = 0.;
xmu = 0.;
}
}
// General case
else
{
xlambda = ( rEo1 - o1Eo2*rEo2) / cc;
xmu = (-rEo2 + o1Eo2*rEo1) / cc;
if ( std::abs(xlambda) > Node1->l_ch || std::abs(xmu) > Node2->l_ch )
{
aux1 = std::abs(xlambda) - Node1->l_ch;
aux2 = std::abs(xmu) - Node2->l_ch;
if ( aux1 > aux2 )
{
xlambda = copysign(Node1->l_ch, xlambda);
xmu = xlambda*o1Eo2 - rEo2;
if ( std::abs(xmu) > Node2->l_ch ) xmu = copysign(Node2->l_ch, xmu);
}
else
{
xmu = copysign(Node2->l_ch, xmu);
xlambda = xmu*o1Eo2 + rEo1;
if ( std::abs(xlambda) > Node1->l_ch ) xlambda = copysign(Node1->l_ch, xlambda);
}
}
}
// Minimum line-to-line distance
rm2 = R_sep.squaredNorm() + SQR(xlambda) + SQR(xmu)
- 2.*xlambda*xmu*o1Eo2 - 2.*xlambda*rEo1 + 2.*xmu*rEo2;
return (rm2 < rsqr);
}
// ============================
/* OBB overlap test */
// ============================
template<typename number>
bool Utils<number>::OverlapBoundOB(const Vector3<number>& R_cm, BNode<number>* Node1, BNode<number>* Node2)
{
number r1;
number r2;
Vector3<number> E1;
Vector3<number> E2;
Vector3<number> T;
Matrix33<number> Rot;
Matrix33<number> Abs_rot;
Vector3<number> R_sep = R_cm + Node2->Center - Node1->Center;
/* ADAPTED FROM C. ERICSON, REAL-TIME COLLISION DETECTION */
// Node half-dimensions
E1 << Node1->l_xh, Node1->l_yh, Node1->l_zh;
E2 << Node2->l_xh, Node2->l_yh, Node2->l_zh;
// Rotation matrix projecting the frame of Node2 onto Node1
Rot = Node1->Orientation.transpose() * Node2->Orientation;
Abs_rot = Rot.array().abs() + TOL_OB;
// Project separation vector in the frame of Node1
T = Node1->Orientation.transpose() * R_sep;
// Test axes L = Node1.x, L = Node1.y, L = Node1.z
for ( uint i = 0; i < 3; ++i )
{
r1 = E1(i);
r2 = E2.dot(Abs_rot.row(i));
if ( std::abs(T(i)) > r1 + r2 ) return false;
}
// Test axes L = Node2.x, L = Node2.y, L = Node2.z
for ( uint i = 0; i < 3; ++i )
{
r1 = E1.dot(Abs_rot.col(i));
r2 = E2(i);
if ( std::abs(T.dot(Rot.col(i))) > r1 + r2 ) return false;
}
// Test axis L = (Node1.x).cross(Node2.x)
r1 = E1(1)*Abs_rot(2,0) + E1(2)*Abs_rot(1,0);
r2 = E2(1)*Abs_rot(0,2) + E2(2)*Abs_rot(0,1);
if ( std::abs(T(2)*Rot(1,0) - T(1)*Rot(2,0)) > r1 + r2 ) return false;
// Test axis L = (Node1.x).cross(Node2.y)
r1 = E1(1)*Abs_rot(2,1) + E1(2)*Abs_rot(1,1);
r2 = E2(0)*Abs_rot(0,2) + E2(2)*Abs_rot(0,0);
if ( std::abs(T(2)*Rot(1,1) - T(1)*Rot(2,1)) > r1 + r2 ) return false;
// Test axis L = (Node1.x).cross(Node2.z)
r1 = E1(1)*Abs_rot(2,2) + E1(2)*Abs_rot(1,2);
r2 = E2(0)*Abs_rot(0,1) + E2(1)*Abs_rot(0,0);
if ( std::abs(T(2)*Rot(1,2) - T(1)*Rot(2,2)) > r1 + r2 ) return false;
// Test axis L = (Node1.y).cross(Node2.x)
r1 = E1(0)*Abs_rot(2,0) + E1(2)*Abs_rot(0,0);
r2 = E2(1)*Abs_rot(1,2) + E2(2)*Abs_rot(1,1);
if ( std::abs(T(0)*Rot(2,0) - T(2)*Rot(0,0)) > r1 + r2 ) return false;
// Test axis L = (Node1.y).cross(Node2.y)
r1 = E1(0)*Abs_rot(2,1) + E1(2)*Abs_rot(0,1);
r2 = E2(0)*Abs_rot(1,2) + E2(2)*Abs_rot(1,0);
if ( std::abs(T(0)*Rot(2,1) - T(2)*Rot(0,1)) > r1 + r2 ) return false;
// Test axis L = (Node1.y).cross(Node2.z)
r1 = E1(0)*Abs_rot(2,2) + E1(2)*Abs_rot(0,2);
r2 = E2(0)*Abs_rot(1,1) + E2(1)*Abs_rot(1,0);
if ( std::abs(T(0)*Rot(2,2) - T(2)*Rot(0,2)) > r1 + r2 ) return false;
// Test axis L = (Node1.z).cross(Node2.x)
r1 = E1(0)*Abs_rot(1,0) + E1(1)*Abs_rot(0,0);
r2 = E2(1)*Abs_rot(2,2) + E2(2)*Abs_rot(2,1);
if ( std::abs(T(1)*Rot(0,0) - T(0)*Rot(1,0)) > r1 + r2 ) return false;
// Test axis L = (Node1.z).cross(Node2.y)
r1 = E1(0)*Abs_rot(1,1) + E1(1)*Abs_rot(0,1);
r2 = E2(0)*Abs_rot(2,2) + E2(2)*Abs_rot(2,0);
if ( std::abs(T(1)*Rot(0,1) - T(0)*Rot(1,1)) > r1 + r2 ) return false;
// Test axis L = (Node1.z).cross(Node2.z)
r1 = E1(0)*Abs_rot(1,2) + E1(1)*Abs_rot(0,2);
r2 = E2(0)*Abs_rot(2,1) + E2(1)*Abs_rot(2,0);
if ( std::abs(T(1)*Rot(0,2) - T(0)*Rot(1,2)) > r1 + r2 ) return false;
return true;
}
// ============================
/* Vertex Principal Component Analysis (PCA) by Singular Value Decomposition (SVD) */
// ============================
template<typename number>
Matrix33<number> Utils<number>::PCA(const Matrix3X<number>& Vertices_in)
{
// Set vertex center of mass to the origin if needed
Vector3<number> Center_of_mass = Vertices_in.rowwise().mean();
Matrix3X<number> Vertices_cm = Vertices_in.colwise() - Center_of_mass;
Eigen::JacobiSVD<Matrix3X<number> > SVD(Vertices_cm, Eigen::ComputeThinU);
Matrix33<number> Rot = SVD.matrixU();
// Swap axes so that Rot.y and Rot.z correspond to the directions of minimal and maximal spread, respectively
Rot.col(0).swap(Rot.col(1));
Rot.col(1).swap(Rot.col(2));
// Enforce right-handedness of node frame
if ( Rot.determinant() < 0. ) Rot.col(2) *= -1.;
return Rot;
}
// ============================
/* Configuration file parser with Eigen format conversion */
// ============================
template<typename number>
void Utils<number>::Load(const std::string& filename, Matrix3X<number>* Vertices, ArrayX<uint>* Sizes)
{
number coeff;
bool is_first_line(false);
// Size counters
uint rows (0);
uint cols (0);
uint rows_t(0);
std::string line;
std::ifstream input_file(filename);
if ( !input_file.good() ) throw std::runtime_error("Couldn't open input file " + filename);
// Store unkown number of configurations into std::vector containers
std::vector<number> data_buffer;
std::vector<uint> size_buffer;
while ( std::getline(input_file, line) )
{
if ( !line.empty() )
{
is_first_line = true;
std::istringstream stream(line);
rows += 1;
while ( stream >> coeff )
{
if ( rows == 1 ) cols += 1;
data_buffer.push_back(coeff);
}
}
else
{
if ( is_first_line )
{
is_first_line = false;
size_buffer.push_back(rows - rows_t);
rows_t = rows;
}
}
}
input_file.close();
if ( size_buffer.size() < 1 ) size_buffer.push_back(rows);
// Map std::vector to Matrix3X<number> in column-major default order
*Vertices = Matrix3X<number>::Map(&data_buffer[0], cols, rows);
*Sizes = ArrayX<uint>::Map(&size_buffer[0], size_buffer.size());
}
template struct Utils<float>;
template struct Utils<double>;
<commit_msg>Templated all objects for float support<commit_after>// ===================================================================
/**
* Implements robust overlap methods for convex bounding volumes.
* Also includes parser for processed trajectory files.
*/
// ===================================================================
/*
* Utils.cpp: Version 1.0
* Created 26/07/2016 by Maxime Tortora
*/
// ===================================================================
#include <fstream>
#include "Utils.hpp"
// ============================
/* Wrappers for MPI datatypes */
// ============================
template<> Utils<float> ::Utils(): MPI_type(MPI_FLOAT) {}
template<> Utils<double>::Utils(): MPI_type(MPI_DOUBLE) {}
template<> Utils<int> ::Utils(): MPI_type(MPI_INT) {}
template<> Utils<uint> ::Utils(): MPI_type(MPI_UNSIGNED) {}
template<> Utils<ullint>::Utils(): MPI_type(MPI_UNSIGNED_LONG_LONG) {}
// ============================
/* Bounding spherocylinders overlap test */
// ============================
template<typename number>
bool Utils<number>::OverlapBoundSC(const Vector3<number>& R_cm, BNode<number>* Node1, BNode<number>* Node2)
{
number xlambda;
number xmu;
number aux1;
number aux2;
number rm2;
Vector3<number> R_sep;
// Root spherocylinders centers are forced to the particle center of mass
if ( Node1->is_root && Node2->is_root ) R_sep = R_cm;
else if ( Node1->is_root ) R_sep = R_cm + Node2->Center;
else if ( Node2->is_root ) R_sep = R_cm - Node1->Center;
else R_sep = R_cm + Node2->Center - Node1->Center;
number rEo1 = Node1->Axis.dot(R_sep);
number rEo2 = Node2->Axis.dot(R_sep);;
number o1Eo2 = Node1->Axis.dot(Node2->Axis);
number rsqr = SQR(Node1->l_cr + Node2->l_cr);
number cc = 1. - SQR(o1Eo2);
/* VEGA ET AL., A FAST ALGORITHM TO EVALUATE THE SHORTEST DISTANCE BETWEEN RODS */
// Case Axis1, Axis2 colinear
if ( cc < TOL_SC )
{
if ( std::abs(rEo1) > TOL_SC )
{
xlambda = copysign(Node1->l_ch, rEo1);
xmu = xlambda*o1Eo2 - rEo2;
if ( std::abs(xmu) > Node2->l_ch ) xmu = copysign(Node2->l_ch, xmu);
}
else
{
xlambda = 0.;
xmu = 0.;
}
}
// General case
else
{
xlambda = ( rEo1 - o1Eo2*rEo2) / cc;
xmu = (-rEo2 + o1Eo2*rEo1) / cc;
if ( std::abs(xlambda) > Node1->l_ch || std::abs(xmu) > Node2->l_ch )
{
aux1 = std::abs(xlambda) - Node1->l_ch;
aux2 = std::abs(xmu) - Node2->l_ch;
if ( aux1 > aux2 )
{
xlambda = copysign(Node1->l_ch, xlambda);
xmu = xlambda*o1Eo2 - rEo2;
if ( std::abs(xmu) > Node2->l_ch ) xmu = copysign(Node2->l_ch, xmu);
}
else
{
xmu = copysign(Node2->l_ch, xmu);
xlambda = xmu*o1Eo2 + rEo1;
if ( std::abs(xlambda) > Node1->l_ch ) xlambda = copysign(Node1->l_ch, xlambda);
}
}
}
// Minimum line-to-line distance
rm2 = R_sep.squaredNorm() + SQR(xlambda) + SQR(xmu)
- 2.*xlambda*xmu*o1Eo2 - 2.*xlambda*rEo1 + 2.*xmu*rEo2;
return (rm2 < rsqr);
}
// ============================
/* OBB overlap test */
// ============================
template<typename number>
bool Utils<number>::OverlapBoundOB(const Vector3<number>& R_cm, BNode<number>* Node1, BNode<number>* Node2)
{
number r1;
number r2;
Vector3<number> E1;
Vector3<number> E2;
Vector3<number> T;
Matrix33<number> Rot;
Matrix33<number> Abs_rot;
Vector3<number> R_sep = R_cm + Node2->Center - Node1->Center;
/* ADAPTED FROM C. ERICSON, REAL-TIME COLLISION DETECTION */
// Node half-dimensions
E1 << Node1->l_xh, Node1->l_yh, Node1->l_zh;
E2 << Node2->l_xh, Node2->l_yh, Node2->l_zh;
// Rotation matrix projecting the frame of Node2 onto Node1
Rot = Node1->Orientation.transpose() * Node2->Orientation;
Abs_rot = Rot.array().abs() + TOL_OB;
// Project separation vector in the frame of Node1
T = Node1->Orientation.transpose() * R_sep;
// Test axes L = Node1.x, L = Node1.y, L = Node1.z
for ( uint i = 0; i < 3; ++i )
{
r1 = E1(i);
r2 = E2.dot(Abs_rot.row(i));
if ( std::abs(T(i)) > r1 + r2 ) return false;
}
// Test axes L = Node2.x, L = Node2.y, L = Node2.z
for ( uint i = 0; i < 3; ++i )
{
r1 = E1.dot(Abs_rot.col(i));
r2 = E2(i);
if ( std::abs(T.dot(Rot.col(i))) > r1 + r2 ) return false;
}
// Test axis L = (Node1.x).cross(Node2.x)
r1 = E1(1)*Abs_rot(2,0) + E1(2)*Abs_rot(1,0);
r2 = E2(1)*Abs_rot(0,2) + E2(2)*Abs_rot(0,1);
if ( std::abs(T(2)*Rot(1,0) - T(1)*Rot(2,0)) > r1 + r2 ) return false;
// Test axis L = (Node1.x).cross(Node2.y)
r1 = E1(1)*Abs_rot(2,1) + E1(2)*Abs_rot(1,1);
r2 = E2(0)*Abs_rot(0,2) + E2(2)*Abs_rot(0,0);
if ( std::abs(T(2)*Rot(1,1) - T(1)*Rot(2,1)) > r1 + r2 ) return false;
// Test axis L = (Node1.x).cross(Node2.z)
r1 = E1(1)*Abs_rot(2,2) + E1(2)*Abs_rot(1,2);
r2 = E2(0)*Abs_rot(0,1) + E2(1)*Abs_rot(0,0);
if ( std::abs(T(2)*Rot(1,2) - T(1)*Rot(2,2)) > r1 + r2 ) return false;
// Test axis L = (Node1.y).cross(Node2.x)
r1 = E1(0)*Abs_rot(2,0) + E1(2)*Abs_rot(0,0);
r2 = E2(1)*Abs_rot(1,2) + E2(2)*Abs_rot(1,1);
if ( std::abs(T(0)*Rot(2,0) - T(2)*Rot(0,0)) > r1 + r2 ) return false;
// Test axis L = (Node1.y).cross(Node2.y)
r1 = E1(0)*Abs_rot(2,1) + E1(2)*Abs_rot(0,1);
r2 = E2(0)*Abs_rot(1,2) + E2(2)*Abs_rot(1,0);
if ( std::abs(T(0)*Rot(2,1) - T(2)*Rot(0,1)) > r1 + r2 ) return false;
// Test axis L = (Node1.y).cross(Node2.z)
r1 = E1(0)*Abs_rot(2,2) + E1(2)*Abs_rot(0,2);
r2 = E2(0)*Abs_rot(1,1) + E2(1)*Abs_rot(1,0);
if ( std::abs(T(0)*Rot(2,2) - T(2)*Rot(0,2)) > r1 + r2 ) return false;
// Test axis L = (Node1.z).cross(Node2.x)
r1 = E1(0)*Abs_rot(1,0) + E1(1)*Abs_rot(0,0);
r2 = E2(1)*Abs_rot(2,2) + E2(2)*Abs_rot(2,1);
if ( std::abs(T(1)*Rot(0,0) - T(0)*Rot(1,0)) > r1 + r2 ) return false;
// Test axis L = (Node1.z).cross(Node2.y)
r1 = E1(0)*Abs_rot(1,1) + E1(1)*Abs_rot(0,1);
r2 = E2(0)*Abs_rot(2,2) + E2(2)*Abs_rot(2,0);
if ( std::abs(T(1)*Rot(0,1) - T(0)*Rot(1,1)) > r1 + r2 ) return false;
// Test axis L = (Node1.z).cross(Node2.z)
r1 = E1(0)*Abs_rot(1,2) + E1(1)*Abs_rot(0,2);
r2 = E2(0)*Abs_rot(2,1) + E2(1)*Abs_rot(2,0);
if ( std::abs(T(1)*Rot(0,2) - T(0)*Rot(1,2)) > r1 + r2 ) return false;
return true;
}
// ============================
/* Vertex Principal Component Analysis (PCA) by Singular Value Decomposition (SVD) */
// ============================
template<typename number>
Matrix33<number> Utils<number>::PCA(const Matrix3X<number>& Vertices_in)
{
// Set vertex center of mass to the origin if needed
Vector3<number> Center_of_mass = Vertices_in.rowwise().mean();
Matrix3X<number> Vertices_cm = Vertices_in.colwise() - Center_of_mass;
Eigen::JacobiSVD<Matrix3X<number> > SVD(Vertices_cm, Eigen::ComputeThinU);
Matrix33<number> Rot = SVD.matrixU();
// Swap axes so that Rot.y and Rot.z correspond to the directions of minimal and maximal spread, respectively
Rot.col(0).swap(Rot.col(1));
Rot.col(1).swap(Rot.col(2));
// Enforce right-handedness of node frame
if ( Rot.determinant() < 0. ) Rot.col(2) *= -1.;
return Rot;
}
// ============================
/* Configuration file parser with Eigen format conversion */
// ============================
template<typename number>
void Utils<number>::Load(const std::string& filename, Matrix3X<number>* Vertices, ArrayX<uint>* Sizes)
{
number coeff;
bool is_first_line(false);
// Size counters
uint rows (0);
uint cols (0);
uint rows_t(0);
std::string line;
std::ifstream input_file(filename);
if ( !input_file.good() ) throw std::runtime_error("Couldn't open input file " + filename);
// Store unkown number of configurations into std::vector containers
std::vector<number> data_buffer;
std::vector<uint> size_buffer;
while ( std::getline(input_file, line) )
{
if ( !line.empty() )
{
is_first_line = true;
std::istringstream stream(line);
rows += 1;
while ( stream >> coeff )
{
if ( rows == 1 ) cols += 1;
data_buffer.push_back(coeff);
}
}
else
{
if ( is_first_line )
{
is_first_line = false;
size_buffer.push_back(rows - rows_t);
rows_t = rows;
}
}
}
input_file.close();
if ( size_buffer.size() < 1 ) size_buffer.push_back(rows);
// Map std::vector to Matrix3X<number> in column-major default order
*Vertices = Matrix3X<number>::Map(&data_buffer[0], cols, rows);
*Sizes = ArrayX<uint>::Map(&size_buffer[0], size_buffer.size());
}
template struct Utils<float>;
template struct Utils<double>;
<|endoftext|>
|
<commit_before>/*
* Write.cpp
*
* Created on: Nov 13, 2015
* Author: Remo Diethelm
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include "point_cloud_io/Write.hpp"
//PCL
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/ply_io.h>
#include <pcl/io/pcd_io.h>
#include <pcl_conversions/pcl_conversions.h>
using namespace std;
using namespace ros;
using namespace pcl;
using namespace pcl::io;
namespace point_cloud_io {
Write::Write(ros::NodeHandle& nodeHandle)
: nodeHandle_(nodeHandle),
filePrefix_("point_cloud"),
fileEnding_("ply")
{
if (!readParameters()) ros::requestShutdown();
pointCloudSubscriber_ = nodeHandle_.subscribe(pointCloudTopic_, 1, &Write::pointCloudCallback, this);
ROS_INFO_STREAM("Subscribed to topic \"" << pointCloudTopic_ << "\".");
}
Write::~Write()
{
}
bool Write::readParameters()
{
bool allParametersRead = true;
if (!nodeHandle_.getParam("topic", pointCloudTopic_)) allParametersRead = false;
if (!nodeHandle_.getParam("folder_path", folderPath_)) allParametersRead = false;
nodeHandle_.getParam("file_prefix", filePrefix_);
nodeHandle_.getParam("file_ending", fileEnding_);
nodeHandle_.getParam("add_counter_to_path", addCounterToPath_);
nodeHandle_.getParam("add_frame_id_to_path", addFrameIdToPath_);
nodeHandle_.getParam("add_stamp_sec_to_path", addStampSecToPath_);
nodeHandle_.getParam("add_stamp_nsec_to_path", addStampNSecToPath_);
if (!allParametersRead)
{
ROS_WARN("Could not read all parameters. Typical command-line usage:\n"
"rosrun point_cloud_io write"
" _topic:=/my_topic"
" _folder_path:=/home/user/my_point_clouds"
" (optional: _file_prefix:=my_prefix"
" _file_ending:=my_ending"
" _add_counter_to_path:=true/false"
" _add_frame_id_to_path:=true/false"
" _add_stamp_sec_to_path:=true/false"
" _add_stamp_nsec_to_path:=true/false)");
return false;
}
return true;
}
void Write::pointCloudCallback(const sensor_msgs::PointCloud2ConstPtr& cloud)
{
ROS_INFO_STREAM("Received point cloud with " << cloud->height*cloud->width << " points.");
std::cout << folderPath_ << std::endl;
stringstream filePath;
filePath << folderPath_ << "/";
if (!filePrefix_.empty()) {
filePath << filePrefix_;
}
if (addCounterToPath_) {
filePath << "_" << counter_;
counter_++;
}
if (addFrameIdToPath_) {
filePath << "_" << cloud->header.frame_id;
}
if (addStampSecToPath_) {
filePath << "_" << cloud->header.stamp.sec;
}
if (addStampNSecToPath_) {
filePath << "_" << cloud->header.stamp.nsec;
}
filePath << ".";
filePath << fileEnding_;
if (fileEnding_ == "ply") {
// Write .ply file.
PointCloud<PointXYZRGBNormal> pclCloud;
fromROSMsg(*cloud, pclCloud);
PLYWriter writer;
bool binary = false;
bool use_camera = false;
if (writer.write(filePath.str(), pclCloud, binary, use_camera) != 0) {
ROS_ERROR("Something went wrong when trying to write the point cloud file.");
return;
}
}
else if(fileEnding_ == "pcd"){
//Write pcd file
PointCloud<PointXYZRGBNormal> pclCloud;
fromROSMsg(*cloud, pclCloud);
pcl::io::savePCDFile (filePath.str(),pclCloud);
}
else {
ROS_ERROR_STREAM("Data format not supported.");
return;
}
ROS_INFO_STREAM("Saved point cloud to " << filePath.str() << ".");
}
} /* namespace */
<commit_msg>fix spacing and remove namespace<commit_after>/*
* Write.cpp
*
* Created on: Nov 13, 2015
* Author: Remo Diethelm
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include "point_cloud_io/Write.hpp"
//PCL
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/ply_io.h>
#include <pcl/io/pcd_io.h>
#include <pcl_conversions/pcl_conversions.h>
using namespace std;
using namespace ros;
using namespace pcl;
using namespace pcl::io;
namespace point_cloud_io {
Write::Write(ros::NodeHandle& nodeHandle)
: nodeHandle_(nodeHandle),
filePrefix_("point_cloud"),
fileEnding_("ply")
{
if (!readParameters()) ros::requestShutdown();
pointCloudSubscriber_ = nodeHandle_.subscribe(pointCloudTopic_, 1, &Write::pointCloudCallback, this);
ROS_INFO_STREAM("Subscribed to topic \"" << pointCloudTopic_ << "\".");
}
Write::~Write()
{
}
bool Write::readParameters()
{
bool allParametersRead = true;
if (!nodeHandle_.getParam("topic", pointCloudTopic_)) allParametersRead = false;
if (!nodeHandle_.getParam("folder_path", folderPath_)) allParametersRead = false;
nodeHandle_.getParam("file_prefix", filePrefix_);
nodeHandle_.getParam("file_ending", fileEnding_);
nodeHandle_.getParam("add_counter_to_path", addCounterToPath_);
nodeHandle_.getParam("add_frame_id_to_path", addFrameIdToPath_);
nodeHandle_.getParam("add_stamp_sec_to_path", addStampSecToPath_);
nodeHandle_.getParam("add_stamp_nsec_to_path", addStampNSecToPath_);
if (!allParametersRead)
{
ROS_WARN("Could not read all parameters. Typical command-line usage:\n"
"rosrun point_cloud_io write"
" _topic:=/my_topic"
" _folder_path:=/home/user/my_point_clouds"
" (optional: _file_prefix:=my_prefix"
" _file_ending:=my_ending"
" _add_counter_to_path:=true/false"
" _add_frame_id_to_path:=true/false"
" _add_stamp_sec_to_path:=true/false"
" _add_stamp_nsec_to_path:=true/false)");
return false;
}
return true;
}
void Write::pointCloudCallback(const sensor_msgs::PointCloud2ConstPtr& cloud)
{
ROS_INFO_STREAM("Received point cloud with " << cloud->height*cloud->width << " points.");
std::cout << folderPath_ << std::endl;
stringstream filePath;
filePath << folderPath_ << "/";
if (!filePrefix_.empty()) {
filePath << filePrefix_;
}
if (addCounterToPath_) {
filePath << "_" << counter_;
counter_++;
}
if (addFrameIdToPath_) {
filePath << "_" << cloud->header.frame_id;
}
if (addStampSecToPath_) {
filePath << "_" << cloud->header.stamp.sec;
}
if (addStampNSecToPath_) {
filePath << "_" << cloud->header.stamp.nsec;
}
filePath << ".";
filePath << fileEnding_;
if (fileEnding_ == "ply") {
// Write .ply file.
PointCloud<PointXYZRGBNormal> pclCloud;
fromROSMsg(*cloud, pclCloud);
PLYWriter writer;
bool binary = false;
bool use_camera = false;
if (writer.write(filePath.str(), pclCloud, binary, use_camera) != 0) {
ROS_ERROR("Something went wrong when trying to write the point cloud file.");
return;
}
}
else if(fileEnding_ == "pcd"){
//Write pcd file
PointCloud<PointXYZRGBNormal> pclCloud;
fromROSMsg(*cloud, pclCloud);
savePCDFile (filePath.str(), pclCloud);
}
else {
ROS_ERROR_STREAM("Data format not supported.");
return;
}
ROS_INFO_STREAM("Saved point cloud to " << filePath.str() << ".");
}
} /* namespace */
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg, Daniel Wallin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 "libtorrent/pch.hpp"
#include "libtorrent/alert.hpp"
#include <boost/thread/xtime.hpp>
enum { queue_size_limit = 1000 };
namespace libtorrent {
alert::alert() : m_timestamp(time_now()) {}
alert::~alert() {}
ptime alert::timestamp() const { return m_timestamp; }
alert_manager::alert_manager()
: m_alert_mask(alert::error_notification)
{}
alert_manager::~alert_manager()
{
while (!m_alerts.empty())
{
delete m_alerts.front();
m_alerts.pop();
}
}
alert const* alert_manager::wait_for_alert(time_duration max_wait)
{
boost::mutex::scoped_lock lock(m_mutex);
if (!m_alerts.empty()) return m_alerts.front();
int secs = total_seconds(max_wait);
max_wait -= seconds(secs);
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += secs;
boost::int64_t nsec = xt.nsec + total_microseconds(max_wait) * 1000;
if (nsec > 1000000000)
{
nsec -= 1000000000;
xt.sec += 1;
}
xt.nsec = boost::xtime::xtime_nsec_t(nsec);
if (!m_condition.timed_wait(lock, xt)) return 0;
TORRENT_ASSERT(!m_alerts.empty());
if (m_alerts.empty()) return 0;
return m_alerts.front();
}
void alert_manager::post_alert(const alert& alert_)
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_alerts.size() >= queue_size_limit) return;
m_alerts.push(alert_.clone().release());
m_condition.notify_all();
}
std::auto_ptr<alert> alert_manager::get()
{
boost::mutex::scoped_lock lock(m_mutex);
TORRENT_ASSERT(!m_alerts.empty());
alert* result = m_alerts.front();
m_alerts.pop();
return std::auto_ptr<alert>(result);
}
bool alert_manager::pending() const
{
boost::mutex::scoped_lock lock(m_mutex);
return !m_alerts.empty();
}
} // namespace libtorrent
<commit_msg>removed invalid assert<commit_after>/*
Copyright (c) 2003, Arvid Norberg, Daniel Wallin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 "libtorrent/pch.hpp"
#include "libtorrent/alert.hpp"
#include <boost/thread/xtime.hpp>
enum { queue_size_limit = 1000 };
namespace libtorrent {
alert::alert() : m_timestamp(time_now()) {}
alert::~alert() {}
ptime alert::timestamp() const { return m_timestamp; }
alert_manager::alert_manager()
: m_alert_mask(alert::error_notification)
{}
alert_manager::~alert_manager()
{
while (!m_alerts.empty())
{
delete m_alerts.front();
m_alerts.pop();
}
}
alert const* alert_manager::wait_for_alert(time_duration max_wait)
{
boost::mutex::scoped_lock lock(m_mutex);
if (!m_alerts.empty()) return m_alerts.front();
int secs = total_seconds(max_wait);
max_wait -= seconds(secs);
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += secs;
boost::int64_t nsec = xt.nsec + total_microseconds(max_wait) * 1000;
if (nsec > 1000000000)
{
nsec -= 1000000000;
xt.sec += 1;
}
xt.nsec = boost::xtime::xtime_nsec_t(nsec);
// apparently this call can be interrupted
// prematurely if there are other signals
if (!m_condition.timed_wait(lock, xt)) return 0;
if (m_alerts.empty()) return 0;
return m_alerts.front();
}
void alert_manager::post_alert(const alert& alert_)
{
boost::mutex::scoped_lock lock(m_mutex);
if (m_alerts.size() >= queue_size_limit) return;
m_alerts.push(alert_.clone().release());
m_condition.notify_all();
}
std::auto_ptr<alert> alert_manager::get()
{
boost::mutex::scoped_lock lock(m_mutex);
TORRENT_ASSERT(!m_alerts.empty());
alert* result = m_alerts.front();
m_alerts.pop();
return std::auto_ptr<alert>(result);
}
bool alert_manager::pending() const
{
boost::mutex::scoped_lock lock(m_mutex);
return !m_alerts.empty();
}
} // namespace libtorrent
<|endoftext|>
|
<commit_before>#include "entitysystem.h"
#include "systems/movementsystem.h"
#include "systems/updatesystem.h"
#include "systems/chatsystem.h"
#include "systems/inventorysystem.h"
#include "systems/partysystem.h"
#include "systems/mapsystem.h"
#include "systems/luasystem.h"
#include "connection.h"
#include "cmapclient.h"
#include <vector>
#include <set>
using namespace RoseCommon;
EntitySystem::EntitySystem() : systemManager_(*this) {
systemManager_.add<Systems::MovementSystem>();
systemManager_.add<Systems::UpdateSystem>();
systemManager_.add<Systems::ChatSystem>();
systemManager_.add<Systems::InventorySystem>();
systemManager_.add<Systems::PartySystem>();
systemManager_.add<Systems::MapSystem>();
systemManager_.add<Systems::LuaSystem>();
}
EntityManager &EntitySystem::getEntityManager() {
return entityManager_;
}
Entity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) {
Entity e = create();
e.assign<Item>(std::move(item));
auto pos = creator.component<Position>();
e.assign<Position>(pos->x_, pos->y_, pos->map_, 0);
auto basic = e.assign<BasicInfo>();
basic->ownerId_ = creator.component<BasicInfo>()->id_;
basic->id_ = 5000; //FIXME: ugly hack that doesn't allow more than 4999 users, please fix
while (idToEntity.at(basic->id_) != idToEntity.end())
++basic->id_;
idToEntity[basic->id_] = e;
return e;
}
void EntitySystem::registerEntity(Entity entity) {
if (!entity)
return;
auto basic = entity.component<BasicInfo>();
if (!basic || basic->name_ == "" || !basic->id_)
return;
nameToEntity_[basic->name_] = entity;
idToEntity_[basic->id_] = entity;
}
Entity EntitySystem::getEntity(const std::string &name) {
return nameToEntity_[name];
}
Entity EntitySystem::getEntity(uint32_t charId) {
return idToEntity_[charId];
}
void EntitySystem::update(double dt) {
std::lock_guard<std::mutex> lock(access_);
while (toDispatch_.size()) {
auto tmp = std::move(toDispatch_.front());
systemManager_.dispatch(tmp.first, *tmp.second);
toDispatch_.pop();
}
systemManager_.update(dt);
for (auto it : toDestroy_) {
if (it) {
saveCharacter(it.component<CharacterInfo>()->charId_, it);
auto basic = it.component<BasicInfo>();
nameToEntity_.erase(basic->name_);
idToEntity_.erase(basic->id_);
it.destroy();
}
}
toDestroy_.clear();
}
void EntitySystem::destroy(Entity entity) {
if (!entity)
return;
std::lock_guard<std::mutex> lock(access_);
toDestroy_.push_back(entity);
}
Entity EntitySystem::create() {
return entityManager_.create();
}
bool EntitySystem::isNearby(Entity a, Entity b) {
return true; // FIXME : actually implement the sight calculation instead of the distance
if (!a || !b)
return false;
auto posa = a.component<Position>();
auto posb = b.component<Position>();
if (!posa || !posb)
return false; // FIXME : is it a bug if there is no position?
if (posa->map_ != posb->map_)
return false;
double dist = (posa->x_ - posb->x_) * (posa->x_ - posb->x_) + (posa->y_ - posb->y_) * (posa->y_ - posb->y_);
if (dist > NEARBY_DIST)
return false;
return true;
}
bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) {
if (!entity)
return false;
if (systemManager_.wouldDispatch(*packet)) {
std::lock_guard<std::mutex> lock(access_);
toDispatch_.emplace(std::make_pair(entity, std::move(packet)));
return true;
}
return false;
}
Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium, uint32_t id) {
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters;
Core::InventoryTable inventoryTable;
Core::SkillTable skillsTable;
auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
.from(characters)
.where(characters.id == charId));
std::lock_guard<std::mutex> lock(access_);
auto entity = create();
if (static_cast<long>(charRes.front().count) != 1L) {
entity.destroy();
return Entity();
}
const auto &charRow = charRes.front();
entity.assign<Position>(charRow);
entity.assign<BasicInfo>(charRow, id);
entity.assign<Stats>(charRow);
entity.assign<AdvancedInfo>(charRow);
entity.assign<CharacterGraphics>(charRow);
entity.assign<CharacterInfo>(charRow, platinium, charId);
// TODO : write the pat initialization code
auto skills = entity.assign<Skills>();
auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level)
.from(skillsTable)
.where(skillsTable.charId == charId));
skills->loadFromResult(skillRes);
// TODO : write the hotbar table and loading code
entity.assign<Hotbar>();
entity.assign<StatusEffects>();
entity.assign<RidingItems>();
entity.assign<BulletItems>();
// TODO : write the inventory code
//auto luaSystem = systemManager_.get<Systems::LuaSystem>();
auto inventory = entity.assign<Inventory>();
auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable))
.from(inventoryTable)
.where(inventoryTable.charId == charId));
inventory->loadFromResult(invRes, get<Systems::InventorySystem>());
Systems::UpdateSystem::calculateSpeed(entity);
entity.assign<Quests>();
Core::WishTable wish;
auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish))
.from(wish)
.where(wish.charId == charId));
auto wishlist = entity.assign<Wishlist>();
wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>());
//auto lua = entity.assign<EntityAPI>();
//luaSystem->loadScript(entity, "function onInit()\ndisplay('test')\nend");
//lua->onInit();
registerEntity(entity);
return entity;
}
void EntitySystem::saveCharacter(uint32_t charId, Entity entity) {
if (!entity)
return;
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters;
using sqlpp::parameter;
auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId);
entity.component<Position>()->commitToUpdate<decltype(characters)>(update);
entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update);
entity.component<Stats>()->commitToUpdate<decltype(characters)>(update);
entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update);
//entity.component<CharacterGraphics>()->commitToUpdate(update);
entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update);
//entity.component<Hotbar>()->commitToUpdate(update);
//entity.component<StatusEffects>()->commitToUpdate(update);
//entity.component<RidingItems>()->commitToUpdate(update);
//entity.component<BulletItems>()->commitToUpdate(update);
conn->run(update);
//entity.component<Skills>()->commitToUpdate(updateSkills);
Core::InventoryTable inv;
auto invRes = conn(sqlpp::select(sqlpp::all_of(inv))
.from(inv)
.where(inv.charId == charId));
const auto& items = entity.component<Inventory>()->items_;
std::vector<size_t> toDelete;
std::vector<size_t> toUpdate;
std::set<size_t> modified;
std::vector<size_t> toInsert;
for (const auto& row : invRes) {
if (row.slot >= Inventory::maxItems)
toDelete.emplace_back(row.slot); //FIXME: that should never happen
else if (!items[row.slot])
toDelete.emplace_back(row.slot);
else if (items[row.slot] != Item(row, get<Systems::InventorySystem>()))
toUpdate.emplace_back(row.slot);
modified.insert(row.slot);
}
size_t i = 0;
for (const auto& item : items) {
if (item && modified.find(i) == modified.end())
toInsert.emplace_back(i);
++i;
}
for (auto it : toDelete)
conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it));
for (auto it : toUpdate) {
auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it);
items[it].commitToUpdate<decltype(inv)>(update);
conn->run(update);
}
for (auto it : toInsert) {
auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set();
items[it].commitToInsert<decltype(inv)>(insert);
insert.insert_list.add(inv.slot = it);
insert.insert_list.add(inv.charId = charId);
conn->run(insert);
}
}
<commit_msg>Update entitysystem.cpp<commit_after>#include "entitysystem.h"
#include "systems/movementsystem.h"
#include "systems/updatesystem.h"
#include "systems/chatsystem.h"
#include "systems/inventorysystem.h"
#include "systems/partysystem.h"
#include "systems/mapsystem.h"
#include "systems/luasystem.h"
#include "connection.h"
#include "cmapclient.h"
#include <vector>
#include <set>
using namespace RoseCommon;
EntitySystem::EntitySystem() : systemManager_(*this) {
systemManager_.add<Systems::MovementSystem>();
systemManager_.add<Systems::UpdateSystem>();
systemManager_.add<Systems::ChatSystem>();
systemManager_.add<Systems::InventorySystem>();
systemManager_.add<Systems::PartySystem>();
systemManager_.add<Systems::MapSystem>();
systemManager_.add<Systems::LuaSystem>();
}
EntityManager &EntitySystem::getEntityManager() {
return entityManager_;
}
Entity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) {
Entity e = create();
e.assign<Item>(std::move(item));
auto pos = creator.component<Position>();
e.assign<Position>(pos->x_, pos->y_, pos->map_, 0);
auto basic = e.assign<BasicInfo>();
basic->ownerId_ = creator.component<BasicInfo>()->id_;
basic->id_ = nextId_++;
itemToEntity[basic->id_] = e;
return e;
}
void EntitySystem::registerEntity(Entity entity) {
if (!entity)
return;
auto basic = entity.component<BasicInfo>();
if (!basic || basic->name_ == "" || !basic->id_)
return;
nameToEntity_[basic->name_] = entity;
idToEntity_[basic->id_] = entity;
}
Entity EntitySystem::getEntity(const std::string &name) {
return nameToEntity_[name];
}
Entity EntitySystem::getEntity(uint32_t charId) {
return idToEntity_[charId];
}
void EntitySystem::update(double dt) {
std::lock_guard<std::mutex> lock(access_);
while (toDispatch_.size()) {
auto tmp = std::move(toDispatch_.front());
systemManager_.dispatch(tmp.first, *tmp.second);
toDispatch_.pop();
}
systemManager_.update(dt);
for (auto it : toDestroy_) {
if (it) {
saveCharacter(it.component<CharacterInfo>()->charId_, it);
auto basic = it.component<BasicInfo>();
nameToEntity_.erase(basic->name_);
idToEntity_.erase(basic->id_);
it.destroy();
}
}
toDestroy_.clear();
}
void EntitySystem::destroy(Entity entity) {
if (!entity)
return;
std::lock_guard<std::mutex> lock(access_);
toDestroy_.push_back(entity);
}
Entity EntitySystem::create() {
return entityManager_.create();
}
bool EntitySystem::isNearby(Entity a, Entity b) {
return true; // FIXME : actually implement the sight calculation instead of the distance
if (!a || !b)
return false;
auto posa = a.component<Position>();
auto posb = b.component<Position>();
if (!posa || !posb)
return false; // FIXME : is it a bug if there is no position?
if (posa->map_ != posb->map_)
return false;
double dist = (posa->x_ - posb->x_) * (posa->x_ - posb->x_) + (posa->y_ - posb->y_) * (posa->y_ - posb->y_);
if (dist > NEARBY_DIST)
return false;
return true;
}
bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) {
if (!entity)
return false;
if (systemManager_.wouldDispatch(*packet)) {
std::lock_guard<std::mutex> lock(access_);
toDispatch_.emplace(std::make_pair(entity, std::move(packet)));
return true;
}
return false;
}
Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium, uint32_t id) {
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters;
Core::InventoryTable inventoryTable;
Core::SkillTable skillsTable;
auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
.from(characters)
.where(characters.id == charId));
std::lock_guard<std::mutex> lock(access_);
auto entity = create();
if (static_cast<long>(charRes.front().count) != 1L) {
entity.destroy();
return Entity();
}
const auto &charRow = charRes.front();
entity.assign<Position>(charRow);
entity.assign<BasicInfo>(charRow, id);
entity.assign<Stats>(charRow);
entity.assign<AdvancedInfo>(charRow);
entity.assign<CharacterGraphics>(charRow);
entity.assign<CharacterInfo>(charRow, platinium, charId);
// TODO : write the pat initialization code
auto skills = entity.assign<Skills>();
auto skillRes = conn(sqlpp::select(skillsTable.id, skillsTable.level)
.from(skillsTable)
.where(skillsTable.charId == charId));
skills->loadFromResult(skillRes);
// TODO : write the hotbar table and loading code
entity.assign<Hotbar>();
entity.assign<StatusEffects>();
entity.assign<RidingItems>();
entity.assign<BulletItems>();
// TODO : write the inventory code
//auto luaSystem = systemManager_.get<Systems::LuaSystem>();
auto inventory = entity.assign<Inventory>();
auto invRes = conn(sqlpp::select(sqlpp::all_of(inventoryTable))
.from(inventoryTable)
.where(inventoryTable.charId == charId));
inventory->loadFromResult(invRes, get<Systems::InventorySystem>());
Systems::UpdateSystem::calculateSpeed(entity);
entity.assign<Quests>();
Core::WishTable wish;
auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish))
.from(wish)
.where(wish.charId == charId));
auto wishlist = entity.assign<Wishlist>();
wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>());
//auto lua = entity.assign<EntityAPI>();
//luaSystem->loadScript(entity, "function onInit()\ndisplay('test')\nend");
//lua->onInit();
registerEntity(entity);
return entity;
}
void EntitySystem::saveCharacter(uint32_t charId, Entity entity) {
if (!entity)
return;
auto conn = Core::connectionPool.getConnection(Core::osirose);
Core::CharacterTable characters;
using sqlpp::parameter;
auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId);
entity.component<Position>()->commitToUpdate<decltype(characters)>(update);
entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update);
entity.component<Stats>()->commitToUpdate<decltype(characters)>(update);
entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update);
//entity.component<CharacterGraphics>()->commitToUpdate(update);
entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update);
//entity.component<Hotbar>()->commitToUpdate(update);
//entity.component<StatusEffects>()->commitToUpdate(update);
//entity.component<RidingItems>()->commitToUpdate(update);
//entity.component<BulletItems>()->commitToUpdate(update);
conn->run(update);
//entity.component<Skills>()->commitToUpdate(updateSkills);
Core::InventoryTable inv;
auto invRes = conn(sqlpp::select(sqlpp::all_of(inv))
.from(inv)
.where(inv.charId == charId));
const auto& items = entity.component<Inventory>()->items_;
std::vector<size_t> toDelete;
std::vector<size_t> toUpdate;
std::set<size_t> modified;
std::vector<size_t> toInsert;
for (const auto& row : invRes) {
if (row.slot >= Inventory::maxItems)
toDelete.emplace_back(row.slot); //FIXME: that should never happen
else if (!items[row.slot])
toDelete.emplace_back(row.slot);
else if (items[row.slot] != Item(row, get<Systems::InventorySystem>()))
toUpdate.emplace_back(row.slot);
modified.insert(row.slot);
}
size_t i = 0;
for (const auto& item : items) {
if (item && modified.find(i) == modified.end())
toInsert.emplace_back(i);
++i;
}
for (auto it : toDelete)
conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it));
for (auto it : toUpdate) {
auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it);
items[it].commitToUpdate<decltype(inv)>(update);
conn->run(update);
}
for (auto it : toInsert) {
auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set();
items[it].commitToInsert<decltype(inv)>(insert);
insert.insert_list.add(inv.slot = it);
insert.insert_list.add(inv.charId = charId);
conn->run(insert);
}
}
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "RhoLogSink.h"
#include "common/RhoFile.h"
#include "common/StringConverter.h"
#include "common/RhodesApp.h"
#include "net/RawSocket.h"
#include "net/URI.h"
#ifdef OS_SAILFISH
#include <QDebug>
#include <QString>
#endif
#if defined( OS_SYMBIAN )
#include <e32debug.h>
#endif
#if defined(OS_MACOSX) && !defined(RHODES_EMULATOR)
extern "C" void rho_ios_log_console_output(const char* message);
#endif
namespace rho {
CLogFileSink::CLogFileSink(const LogSettings& oSettings)
: m_pFile(0), m_pPosFile(0), m_oLogConf(oSettings), m_nCirclePos(-1), m_nFileLogSize(0)
{
}
CLogFileSink::~CLogFileSink()
{
if(m_pFile)
delete m_pFile;
}
void CLogFileSink::writeLogMessage( String& strMsg ){
unsigned int len = strMsg.length();
if ( !m_pFile )
m_pFile = new common::CRhoFile();
if ( !m_pFile->isOpened() ){
m_pFile->open( getLogConf().getLogFilePath().c_str(), common::CRhoFile::OpenForAppend );
m_nFileLogSize = m_pFile->size();
loadLogPosition();
}
if ( getLogConf().getMaxLogFileSize() > 0 )
{
if ( ( m_nCirclePos >= 0 && m_nCirclePos + len > getLogConf().getMaxLogFileSize() ) ||
( m_nCirclePos < 0 && m_nFileLogSize + len > getLogConf().getMaxLogFileSize() ) )
{
m_pFile->truncate(m_pFile->getPos());
m_pFile->movePosToStart();
m_nFileLogSize = 0;
m_nCirclePos = 0;
}
}
int nWritten = m_pFile->write( strMsg.c_str(), len );
m_pFile->flush();
if ( m_nCirclePos >= 0 )
m_nCirclePos += nWritten;
else
m_nFileLogSize += nWritten;
saveLogPosition();
}
int CLogFileSink::getCurPos()
{
return m_nCirclePos >= 0 ? m_nCirclePos : m_nFileLogSize;
}
void CLogFileSink::clear(){
if ( m_pFile ) {
delete m_pFile;
m_pFile = NULL;
}
common::CRhoFile().deleteFile(getLogConf().getLogFilePath().c_str());
String strPosPath = getLogConf().getLogFilePath() + "_pos";
common::CRhoFile().deleteFile(strPosPath.c_str());
}
void CLogFileSink::loadLogPosition(){
if ( !m_pPosFile )
m_pPosFile = new common::CRhoFile();
if ( !m_pPosFile->isOpened() ){
String strPosPath = getLogConf().getLogFilePath() + "_pos";
m_pPosFile->open( strPosPath.c_str(), common::CRhoFile::OpenForReadWrite );
}
if ( !m_pPosFile->isOpened() )
return;
String strPos;
m_pPosFile->movePosToStart();
m_pPosFile->readString(strPos);
if ( strPos.length() == 0 )
return;
m_nCirclePos = atoi(strPos.c_str());
if ( m_nCirclePos < 0 || m_nCirclePos > (int)m_nFileLogSize )
m_nCirclePos = -1;
if ( m_nCirclePos >= 0 )
m_pFile->setPosTo( m_nCirclePos );
}
void CLogFileSink::saveLogPosition(){
if ( m_nCirclePos < 0 )
return;
if ( m_nCirclePos > (int)getLogConf().getMaxLogFileSize() )
return;
String strPos = common::convertToStringA(m_nCirclePos);
for( int i = strPos.length(); i < 10; i++ )
strPos += ' ';
m_pPosFile->movePosToStart();
m_pPosFile->write( strPos.c_str(), strPos.length() );
m_pPosFile->flush();
}
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
void CLogOutputSink::writeLogMessage( String& strMsg )
{
if ( strMsg.length() > 1 && strMsg[strMsg.length()-2] == '\r' )
strMsg.erase(strMsg.length()-2,1);
const char* szMsg = strMsg.c_str();
#if defined( OS_WINDOWS_DESKTOP )
::OutputDebugStringA(szMsg);
#elif defined( OS_PLATFORM_MOTCE )
::OutputDebugStringW(common::convertToStringW(strMsg).c_str());
#elif defined(OS_WP8) || defined(OS_UWP)
::OutputDebugStringW(common::convertToStringW(strMsg).c_str());
#elif defined( OS_SYMBIAN )
TPtrC8 des((const TUint8*)szMsg);
RDebug::RawPrint(des);
return;
#elif defined(OS_MACOSX) && !defined(RHODES_EMULATOR)
rho_ios_log_console_output(szMsg);
#elif defined(OS_SAILFISH)
qDebug() << QString::fromStdString(strMsg);
#endif
#if !defined( OS_PLATFORM_MOTCE ) && !(defined(OS_MACOSX) && !defined(RHODES_EMULATOR))
for( int n = 0; n < (int)strMsg.length(); n+= 100 )
fwrite(szMsg+n, 1, min(100,strMsg.length()-n) , stdout );
fflush(stdout);
#endif
}
CLogSocketSink::CLogSocketSink(const LogSettings& oSettings)
{
m_URL = oSettings.getLogURL();
CThreadQueue::setLogCategory(LogCategory("NO_LOGGING"));
setPollInterval(QUEUE_POLL_INTERVAL_INFINITE);
#if !defined( OS_WINDOWS_DESKTOP )
start(epLow);
#endif
}
CLogSocketSink::~CLogSocketSink()
{
//wait till all commands will be sent to server
#if !defined( OS_WINDOWS_DESKTOP )
CRhoThread::stop(2000);
#endif
}
void CLogSocketSink::setUrl(String url)
{
m_URL = url;
}
void CLogSocketSink::writeLogMessage( String& strMsg )
{
addQueueCommand(new LogCommand(m_URL.c_str(), strMsg.c_str()));
}
void CLogSocketSink::processCommand(IQueueCommand* pCmd)
{
LogCommand *cmd = (LogCommand *)pCmd;
/*
Checking CRhodesApp instance is needed because net request requires it to be valid.
If socket sink is initialized from ext manager, log messages could occur before app instance is set so we will crash.
*/
if (!cmd || (common::CRhodesApp::getInstance()==0))
return;
#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
getNet().doRequest( "GET", cmd->m_url+"?LogSeverity="+cmd->m_body[0]+"&LogComment="+net::URI::urlEncode(cmd->m_body), String(), 0, 0 );
#else
getNet().doRequest( "POST", cmd->m_url, cmd->m_body, 0, 0 );
#endif
}
}
<commit_msg>sailfish: log changing<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "RhoLogSink.h"
#include "common/RhoFile.h"
#include "common/StringConverter.h"
#include "common/RhodesApp.h"
#include "net/RawSocket.h"
#include "net/URI.h"
#if defined( OS_SYMBIAN )
#include <e32debug.h>
#endif
#if defined(OS_MACOSX) && !defined(RHODES_EMULATOR)
extern "C" void rho_ios_log_console_output(const char* message);
#endif
namespace rho {
CLogFileSink::CLogFileSink(const LogSettings& oSettings)
: m_pFile(0), m_pPosFile(0), m_oLogConf(oSettings), m_nCirclePos(-1), m_nFileLogSize(0)
{
}
CLogFileSink::~CLogFileSink()
{
if(m_pFile)
delete m_pFile;
}
void CLogFileSink::writeLogMessage( String& strMsg ){
unsigned int len = strMsg.length();
if ( !m_pFile )
m_pFile = new common::CRhoFile();
if ( !m_pFile->isOpened() ){
m_pFile->open( getLogConf().getLogFilePath().c_str(), common::CRhoFile::OpenForAppend );
m_nFileLogSize = m_pFile->size();
loadLogPosition();
}
if ( getLogConf().getMaxLogFileSize() > 0 )
{
if ( ( m_nCirclePos >= 0 && m_nCirclePos + len > getLogConf().getMaxLogFileSize() ) ||
( m_nCirclePos < 0 && m_nFileLogSize + len > getLogConf().getMaxLogFileSize() ) )
{
m_pFile->truncate(m_pFile->getPos());
m_pFile->movePosToStart();
m_nFileLogSize = 0;
m_nCirclePos = 0;
}
}
int nWritten = m_pFile->write( strMsg.c_str(), len );
m_pFile->flush();
if ( m_nCirclePos >= 0 )
m_nCirclePos += nWritten;
else
m_nFileLogSize += nWritten;
saveLogPosition();
}
int CLogFileSink::getCurPos()
{
return m_nCirclePos >= 0 ? m_nCirclePos : m_nFileLogSize;
}
void CLogFileSink::clear(){
if ( m_pFile ) {
delete m_pFile;
m_pFile = NULL;
}
common::CRhoFile().deleteFile(getLogConf().getLogFilePath().c_str());
String strPosPath = getLogConf().getLogFilePath() + "_pos";
common::CRhoFile().deleteFile(strPosPath.c_str());
}
void CLogFileSink::loadLogPosition(){
if ( !m_pPosFile )
m_pPosFile = new common::CRhoFile();
if ( !m_pPosFile->isOpened() ){
String strPosPath = getLogConf().getLogFilePath() + "_pos";
m_pPosFile->open( strPosPath.c_str(), common::CRhoFile::OpenForReadWrite );
}
if ( !m_pPosFile->isOpened() )
return;
String strPos;
m_pPosFile->movePosToStart();
m_pPosFile->readString(strPos);
if ( strPos.length() == 0 )
return;
m_nCirclePos = atoi(strPos.c_str());
if ( m_nCirclePos < 0 || m_nCirclePos > (int)m_nFileLogSize )
m_nCirclePos = -1;
if ( m_nCirclePos >= 0 )
m_pFile->setPosTo( m_nCirclePos );
}
void CLogFileSink::saveLogPosition(){
if ( m_nCirclePos < 0 )
return;
if ( m_nCirclePos > (int)getLogConf().getMaxLogFileSize() )
return;
String strPos = common::convertToStringA(m_nCirclePos);
for( int i = strPos.length(); i < 10; i++ )
strPos += ' ';
m_pPosFile->movePosToStart();
m_pPosFile->write( strPos.c_str(), strPos.length() );
m_pPosFile->flush();
}
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
void CLogOutputSink::writeLogMessage( String& strMsg )
{
if ( strMsg.length() > 1 && strMsg[strMsg.length()-2] == '\r' )
strMsg.erase(strMsg.length()-2,1);
const char* szMsg = strMsg.c_str();
#if defined( OS_WINDOWS_DESKTOP )
::OutputDebugStringA(szMsg);
#elif defined( OS_PLATFORM_MOTCE )
::OutputDebugStringW(common::convertToStringW(strMsg).c_str());
#elif defined(OS_WP8) || defined(OS_UWP)
::OutputDebugStringW(common::convertToStringW(strMsg).c_str());
#elif defined( OS_SYMBIAN )
TPtrC8 des((const TUint8*)szMsg);
RDebug::RawPrint(des);
return;
#elif defined(OS_MACOSX) && !defined(RHODES_EMULATOR)
rho_ios_log_console_output(szMsg);
#endif
#if !defined( OS_PLATFORM_MOTCE ) && !(defined(OS_MACOSX) && !defined(RHODES_EMULATOR))
for( int n = 0; n < (int)strMsg.length(); n+= 100 )
fwrite(szMsg+n, 1, min(100,strMsg.length()-n) , stdout );
fflush(stdout);
#endif
}
CLogSocketSink::CLogSocketSink(const LogSettings& oSettings)
{
m_URL = oSettings.getLogURL();
CThreadQueue::setLogCategory(LogCategory("NO_LOGGING"));
setPollInterval(QUEUE_POLL_INTERVAL_INFINITE);
#if !defined( OS_WINDOWS_DESKTOP )
start(epLow);
#endif
}
CLogSocketSink::~CLogSocketSink()
{
//wait till all commands will be sent to server
#if !defined( OS_WINDOWS_DESKTOP )
CRhoThread::stop(2000);
#endif
}
void CLogSocketSink::setUrl(String url)
{
m_URL = url;
}
void CLogSocketSink::writeLogMessage( String& strMsg )
{
addQueueCommand(new LogCommand(m_URL.c_str(), strMsg.c_str()));
}
void CLogSocketSink::processCommand(IQueueCommand* pCmd)
{
LogCommand *cmd = (LogCommand *)pCmd;
/*
Checking CRhodesApp instance is needed because net request requires it to be valid.
If socket sink is initialized from ext manager, log messages could occur before app instance is set so we will crash.
*/
if (!cmd || (common::CRhodesApp::getInstance()==0))
return;
#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
getNet().doRequest( "GET", cmd->m_url+"?LogSeverity="+cmd->m_body[0]+"&LogComment="+net::URI::urlEncode(cmd->m_body), String(), 0, 0 );
#else
getNet().doRequest( "POST", cmd->m_url, cmd->m_body, 0, 0 );
#endif
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include <wininet.h>
#include "IEBrowserEngine.h"
#include "common/RhoConf.h"
#include "MainWindow.h"
#if defined(_WIN32_WCE)
#include <webvw.h>
#endif
extern "C" int rho_wm_impl_CheckLicense();
CIEBrowserEngine::CIEBrowserEngine(HWND hParentWnd, HINSTANCE hInstance) :
m_spIWebBrowser2(NULL)
{
m_bLoadingComplete = false;
#if defined(_WIN32_WCE)
m_browser.Create(hParentWnd,
CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
TEXT("Microsoft.PIEDocView"), // ProgID of the control
WS_CHILD, 0,
ID_BROWSER);
#else
m_browser.Create(hParentWnd,
CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
TEXT("Shell.Explorer"), // ProgID of the control
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0,
ID_BROWSER);
#endif
// cache IWebBrowser2 interface pointer
HRESULT hr = m_browser.QueryControl(&m_spIWebBrowser2);
m_spIWebBrowser2->put_AddressBar(VARIANT_FALSE);
if ( !RHOCONF().getBool("wm_show_statusbar") )
m_spIWebBrowser2->put_StatusBar(VARIANT_FALSE);
}
CIEBrowserEngine::~CIEBrowserEngine(void)
{
//TODO: destroy browser
}
BOOL CIEBrowserEngine::Navigate(LPCTSTR szURL)
{
BSTR bstrUrl = SysAllocString(szURL);
if ( wcsncmp(szURL, L"http://127.0.0.1", 16 ) == 0 )
wcsncpy( bstrUrl+7, L"localhost", 9 );
BOOL bRes = m_spIWebBrowser2->Navigate(bstrUrl, NULL, &CComVariant(L"_self"), NULL, NULL) == S_OK;
SysFreeString(bstrUrl);
return bRes;
}
BOOL CIEBrowserEngine::ResizeOnTab(int iInstID,RECT rcNewSize)
{
return m_browser.MoveWindow(&rcNewSize);
}
BOOL CIEBrowserEngine::BackOnTab(int iInstID,int iPagesBack /*= 1*/)
{
return m_spIWebBrowser2->GoBack() == S_OK;
}
BOOL CIEBrowserEngine::ForwardOnTab(int iInstID)
{
return m_spIWebBrowser2->GoForward() == S_OK;
}
BOOL CIEBrowserEngine::ReloadOnTab(bool bFromCache, UINT iTab)
{
return m_spIWebBrowser2->Refresh() == S_OK;
}
BOOL CIEBrowserEngine::StopOnTab(UINT iTab)
{
return FALSE;
}
BOOL CIEBrowserEngine::ZoomPageOnTab(float fZoom, UINT iTab)
{
return FALSE;
}
BOOL CIEBrowserEngine::ZoomTextOnTab(int nZoom, UINT iTab)
{
return FALSE;
}
int CIEBrowserEngine::GetTextZoomOnTab(UINT iTab)
{
return 2; //Normal
}
BOOL CIEBrowserEngine::GetTitleOnTab(LPTSTR szURL, UINT iMaxLen, UINT iTab)
{
return FALSE;
}
static void writeHtmlToTheDoc (
#if defined(_WIN32_WCE) && !defined( OS_PLATFORM_MOTCE )
IPIEHTMLDocument2 *document
#else
IHTMLDocument2 *document
#endif
, LPCTSTR szHtml)
{
HRESULT hresult = S_OK;
VARIANT *param;
SAFEARRAY *sfArray;
//std::wstring html;
BSTR bstr = SysAllocString(szHtml);
// Creates a new one-dimensional array
sfArray = SafeArrayCreateVector(VT_VARIANT, 0, 1);
if (sfArray && document)
{
hresult = SafeArrayAccessData(sfArray,(LPVOID*) & param);
param->vt = VT_BSTR;
param->bstrVal = bstr;
hresult = SafeArrayUnaccessData(sfArray);
hresult = document->write(sfArray);
}
SysFreeString(bstr);
if (sfArray != NULL) {
SafeArrayDestroy(sfArray);
}
}
BOOL CIEBrowserEngine::NavigateToHtml(LPCTSTR szHtml)
{
HRESULT hr;
IDispatch* pHtmlDoc = NULL;
// Retrieve the document object.
hr = m_spIWebBrowser2->get_Document( &pHtmlDoc );
if ( SUCCEEDED(hr) )
{
#if defined(_WIN32_WCE)&& !defined( OS_PLATFORM_MOTCE )
IPIEHTMLDocument2* pDoc;
hr = pHtmlDoc->QueryInterface(__uuidof(IPIEHTMLDocument2), (void**)&pDoc );
#else
IHTMLDocument2* pDoc;
hr = pHtmlDoc->QueryInterface(__uuidof(IHTMLDocument2), (void**)&pDoc );
#endif
if ( SUCCEEDED(hr) )
{
// Write to the document
writeHtmlToTheDoc(pDoc, szHtml);
pDoc->Release();
}
}
return TRUE;
}
LRESULT CIEBrowserEngine::OnWebKitMessages(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
switch (uMsg)
{
case PB_ONMETA:
RHODESAPP().getExtManager().onSetPropertiesData( (LPCWSTR)wParam, (LPCWSTR)lParam );
break;
}
bHandled = TRUE;
return 0;
}
void CIEBrowserEngine::RunMessageLoop(CMainWindow& mainWnd)
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if ( RHODESAPP().getExtManager().onWndMsg(msg) )
continue;
if (!mainWnd.TranslateAccelerator(&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
bool CIEBrowserEngine::isExistJavascript(const wchar_t* szJSFunction, int index)
{
return true;
}
void CIEBrowserEngine::executeJavascript(const wchar_t* szJSFunction, int index)
{
StringW strUrlW;
if(_memicmp(szJSFunction,L"JavaScript:",11*2) != 0)
strUrlW = L"javascript:";
strUrlW += szJSFunction;
Navigate(strUrlW.c_str());
}
void CIEBrowserEngine::SetCookie(char* url, char* cookie)
{
URL_COMPONENTSA uri;
::memset(&uri, 0, sizeof(uri));
uri.dwStructSize = sizeof(uri);
uri.dwSchemeLength = 1;
uri.dwHostNameLength = 1;
uri.dwUrlPathLength = 1;
if (!::InternetCrackUrlA(url, ::strlen(url), 0, &uri)) {
RAWLOG_ERROR1("WebView.set_cookie: can not parse url: %s", url);
return;
}
std::string nurl(uri.lpszScheme, uri.dwSchemeLength);
nurl += "://";
nurl += std::string(uri.lpszHostName, uri.dwHostNameLength);
nurl += std::string(uri.lpszUrlPath, uri.dwUrlPathLength);
for (const char *c = cookie;;) {
const char *s = c;
for (; *s != ';' && *s != '\0'; ++s);
std::string c1(c, s - c);
if (!::InternetSetCookieA(nurl.c_str(), NULL, c1.c_str()))
RAWLOG_ERROR1("WebView.set_cookie: can not set cookie for url %s", nurl.c_str());
if (*s == '\0')
break;
for (c = s + 1; *c == ' '; ++c);
}
}
void CIEBrowserEngine::OnDocumentComplete(LPCTSTR url)
{
if(!m_bLoadingComplete && wcscmp(url,_T("about:blank"))!=0)
{
rho_wm_impl_CheckLicense();
m_bLoadingComplete = true;
}
}
void CIEBrowserEngine::setBrowserGesturing(bool bEnableGesturing)
{
}
void CIEBrowserEngine::NotifyEngineOfSipPosition()
{
}<commit_msg>wm: show license in case of IE<commit_after>#include "stdafx.h"
#include <wininet.h>
#include "IEBrowserEngine.h"
#include "common/RhoConf.h"
#include "MainWindow.h"
#if defined(_WIN32_WCE)
#include <webvw.h>
#endif
extern "C" int rho_wm_impl_CheckLicense();
CIEBrowserEngine::CIEBrowserEngine(HWND hParentWnd, HINSTANCE hInstance) :
m_spIWebBrowser2(NULL)
{
m_bLoadingComplete = false;
#if defined(_WIN32_WCE)
m_browser.Create(hParentWnd,
CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
TEXT("Microsoft.PIEDocView"), // ProgID of the control
WS_CHILD, 0,
ID_BROWSER);
#else
m_browser.Create(hParentWnd,
CWindow::rcDefault, // proper sizing is done in CMainWindow::OnSize
TEXT("Shell.Explorer"), // ProgID of the control
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0,
ID_BROWSER);
#endif
// cache IWebBrowser2 interface pointer
HRESULT hr = m_browser.QueryControl(&m_spIWebBrowser2);
m_spIWebBrowser2->put_AddressBar(VARIANT_FALSE);
if ( !RHOCONF().getBool("wm_show_statusbar") )
m_spIWebBrowser2->put_StatusBar(VARIANT_FALSE);
}
CIEBrowserEngine::~CIEBrowserEngine(void)
{
//TODO: destroy browser
}
BOOL CIEBrowserEngine::Navigate(LPCTSTR szURL)
{
BSTR bstrUrl = SysAllocString(szURL);
if ( wcsncmp(szURL, L"http://127.0.0.1", 16 ) == 0 )
wcsncpy( bstrUrl+7, L"localhost", 9 );
BOOL bRes = m_spIWebBrowser2->Navigate(bstrUrl, NULL, &CComVariant(L"_self"), NULL, NULL) == S_OK;
SysFreeString(bstrUrl);
return bRes;
}
BOOL CIEBrowserEngine::ResizeOnTab(int iInstID,RECT rcNewSize)
{
return m_browser.MoveWindow(&rcNewSize);
}
BOOL CIEBrowserEngine::BackOnTab(int iInstID,int iPagesBack /*= 1*/)
{
return m_spIWebBrowser2->GoBack() == S_OK;
}
BOOL CIEBrowserEngine::ForwardOnTab(int iInstID)
{
return m_spIWebBrowser2->GoForward() == S_OK;
}
BOOL CIEBrowserEngine::ReloadOnTab(bool bFromCache, UINT iTab)
{
return m_spIWebBrowser2->Refresh() == S_OK;
}
BOOL CIEBrowserEngine::StopOnTab(UINT iTab)
{
return FALSE;
}
BOOL CIEBrowserEngine::ZoomPageOnTab(float fZoom, UINT iTab)
{
return FALSE;
}
BOOL CIEBrowserEngine::ZoomTextOnTab(int nZoom, UINT iTab)
{
return FALSE;
}
int CIEBrowserEngine::GetTextZoomOnTab(UINT iTab)
{
return 2; //Normal
}
BOOL CIEBrowserEngine::GetTitleOnTab(LPTSTR szURL, UINT iMaxLen, UINT iTab)
{
return FALSE;
}
static void writeHtmlToTheDoc (
#if defined(_WIN32_WCE) && !defined( OS_PLATFORM_MOTCE )
IPIEHTMLDocument2 *document
#else
IHTMLDocument2 *document
#endif
, LPCTSTR szHtml)
{
HRESULT hresult = S_OK;
VARIANT *param;
SAFEARRAY *sfArray;
//std::wstring html;
BSTR bstr = SysAllocString(szHtml);
// Creates a new one-dimensional array
sfArray = SafeArrayCreateVector(VT_VARIANT, 0, 1);
if (sfArray && document)
{
hresult = SafeArrayAccessData(sfArray,(LPVOID*) & param);
param->vt = VT_BSTR;
param->bstrVal = bstr;
hresult = SafeArrayUnaccessData(sfArray);
hresult = document->write(sfArray);
}
SysFreeString(bstr);
if (sfArray != NULL) {
SafeArrayDestroy(sfArray);
}
}
BOOL CIEBrowserEngine::NavigateToHtml(LPCTSTR szHtml)
{
HRESULT hr;
IDispatch* pHtmlDoc = NULL;
// Retrieve the document object.
hr = m_spIWebBrowser2->get_Document( &pHtmlDoc );
if ( SUCCEEDED(hr) )
{
#if defined(_WIN32_WCE)&& !defined( OS_PLATFORM_MOTCE )
IPIEHTMLDocument2* pDoc;
hr = pHtmlDoc->QueryInterface(__uuidof(IPIEHTMLDocument2), (void**)&pDoc );
#else
IHTMLDocument2* pDoc;
hr = pHtmlDoc->QueryInterface(__uuidof(IHTMLDocument2), (void**)&pDoc );
#endif
if ( SUCCEEDED(hr) )
{
// Write to the document
writeHtmlToTheDoc(pDoc, szHtml);
pDoc->Release();
}
}
return TRUE;
}
LRESULT CIEBrowserEngine::OnWebKitMessages(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
switch (uMsg)
{
case PB_ONMETA:
RHODESAPP().getExtManager().onSetPropertiesData( (LPCWSTR)wParam, (LPCWSTR)lParam );
break;
}
bHandled = TRUE;
return 0;
}
void CIEBrowserEngine::RunMessageLoop(CMainWindow& mainWnd)
{
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if ( RHODESAPP().getExtManager().onWndMsg(msg) )
continue;
if (!mainWnd.TranslateAccelerator(&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
bool CIEBrowserEngine::isExistJavascript(const wchar_t* szJSFunction, int index)
{
return true;
}
void CIEBrowserEngine::executeJavascript(const wchar_t* szJSFunction, int index)
{
StringW strUrlW;
if(_memicmp(szJSFunction,L"JavaScript:",11*2) != 0)
strUrlW = L"javascript:";
strUrlW += szJSFunction;
Navigate(strUrlW.c_str());
}
void CIEBrowserEngine::SetCookie(char* url, char* cookie)
{
URL_COMPONENTSA uri;
::memset(&uri, 0, sizeof(uri));
uri.dwStructSize = sizeof(uri);
uri.dwSchemeLength = 1;
uri.dwHostNameLength = 1;
uri.dwUrlPathLength = 1;
if (!::InternetCrackUrlA(url, ::strlen(url), 0, &uri)) {
RAWLOG_ERROR1("WebView.set_cookie: can not parse url: %s", url);
return;
}
std::string nurl(uri.lpszScheme, uri.dwSchemeLength);
nurl += "://";
nurl += std::string(uri.lpszHostName, uri.dwHostNameLength);
nurl += std::string(uri.lpszUrlPath, uri.dwUrlPathLength);
for (const char *c = cookie;;) {
const char *s = c;
for (; *s != ';' && *s != '\0'; ++s);
std::string c1(c, s - c);
if (!::InternetSetCookieA(nurl.c_str(), NULL, c1.c_str()))
RAWLOG_ERROR1("WebView.set_cookie: can not set cookie for url %s", nurl.c_str());
if (*s == '\0')
break;
for (c = s + 1; *c == ' '; ++c);
}
}
void CIEBrowserEngine::OnDocumentComplete(LPCTSTR url)
{
if(!m_bLoadingComplete && wcscmp(url,_T("about:blank"))!=0)
{
int nRes = rho_wm_impl_CheckLicense();
if ( !nRes )
::MessageBoxW(0, L"Please provide RhoElements license key.", L"Motorola License", MB_ICONERROR | MB_OK);
m_bLoadingComplete = true;
}
}
void CIEBrowserEngine::setBrowserGesturing(bool bEnableGesturing)
{
}
void CIEBrowserEngine::NotifyEngineOfSipPosition()
{
}<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "pch_rhoruntime.h"
#include "rhoruntime.h"
//#include "../../shared/sqlite/sqlite3.h"
//#include "logging/RhoLogConf.h"
#include "common/RhodesApp.h"
#include "rubyext/WebView.h"
using namespace rhoruntime;
using namespace Platform;
CRhoRuntime^ CRhoRuntime::m_instance = nullptr;
CRhoRuntime::CRhoRuntime(IMainPage^ mainPage):
m_MainPage(mainPage)
{
}
CRhoRuntime^ CRhoRuntime::getInstance(IMainPage^ mainPage)
{
if (m_instance == nullptr)
m_instance = ref new CRhoRuntime(mainPage);
return m_instance;
}
CRhoRuntime^ CRhoRuntime::getInstance()
{
return m_instance;
}
IMainPage^ CRhoRuntime::getMainPage()
{
return m_MainPage;
}
// rhodes executed in a separate thread
void CRhoRuntime::Execute()
{
rho::String m_strRootPath = rho_native_rhopath(), m_logPort, m_strRuntimePath;
rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());
rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRuntimePath);
//RHODESAPP().setExtManager( &m_oExtManager );
//Create Main window
RHODESAPP().startApp();
//// wait for 5 seconds
//m_MainPage->DoWait(5000);
//// exit application
//m_MainPage->exitCommand();
}
// *** CALLBACKS from MainPage object ***
void CRhoRuntime::updateSizeProperties(int width, int height)
{
}
void CRhoRuntime::onActivate(int active)
{
RHODESAPP().callUiCreatedCallback();
}
void CRhoRuntime::logEvent(::Platform::String^ message)
{
}
void CRhoRuntime::createCustomMenu(void)
{
}
void CRhoRuntime::onCustomMenuItemCommand(int nItemPos)
{
}
void CRhoRuntime::onWindowClose(void)
{
}
void CRhoRuntime::onWebViewUrlChanged(::Platform::String^ url)
{
}
// *** PUBLIC METHODS ***
bool CRhoRuntime::Initialize(::Platform::String^ title)
{
return true;
}
void CRhoRuntime::DestroyUi(void)
{
}
<commit_msg>hotfix for onactivate handler<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "pch_rhoruntime.h"
#include "rhoruntime.h"
//#include "../../shared/sqlite/sqlite3.h"
//#include "logging/RhoLogConf.h"
#include "common/RhodesApp.h"
#include "rubyext/WebView.h"
using namespace rhoruntime;
using namespace Platform;
CRhoRuntime^ CRhoRuntime::m_instance = nullptr;
CRhoRuntime::CRhoRuntime(IMainPage^ mainPage):
m_MainPage(mainPage)
{
}
CRhoRuntime^ CRhoRuntime::getInstance(IMainPage^ mainPage)
{
if (m_instance == nullptr)
m_instance = ref new CRhoRuntime(mainPage);
return m_instance;
}
CRhoRuntime^ CRhoRuntime::getInstance()
{
return m_instance;
}
IMainPage^ CRhoRuntime::getMainPage()
{
return m_MainPage;
}
// rhodes executed in a separate thread
void CRhoRuntime::Execute()
{
rho::String m_strRootPath = rho_native_rhopath(), m_logPort, m_strRuntimePath;
rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());
rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRuntimePath);
//RHODESAPP().setExtManager( &m_oExtManager );
//Create Main window
RHODESAPP().startApp();
//// wait for 5 seconds
//m_MainPage->DoWait(5000);
//// exit application
//m_MainPage->exitCommand();
}
// *** CALLBACKS from MainPage object ***
void CRhoRuntime::updateSizeProperties(int width, int height)
{
}
void CRhoRuntime::onActivate(int active)
{
rho_webview_navigate("system/uicreated", 0); //HOTFIX, should remove after threadqueue fix
//RHODESAPP().callUiCreatedCallback();
}
void CRhoRuntime::logEvent(::Platform::String^ message)
{
}
void CRhoRuntime::createCustomMenu(void)
{
}
void CRhoRuntime::onCustomMenuItemCommand(int nItemPos)
{
}
void CRhoRuntime::onWindowClose(void)
{
}
void CRhoRuntime::onWebViewUrlChanged(::Platform::String^ url)
{
}
// *** PUBLIC METHODS ***
bool CRhoRuntime::Initialize(::Platform::String^ title)
{
return true;
}
void CRhoRuntime::DestroyUi(void)
{
}
<|endoftext|>
|
<commit_before>/*
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. The license is
in the file "COPYING".
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
This class is based on QLCFTDI class from
Q Light Controller
qlcftdi-libftdi.cpp
Copyright (C) Heikki Junnila
Only standard CPP conversion was changed and function name changed
to follow OLA coding standards.
by
Rui Barreiros
*/
#include <strings.h>
#include <ftdi.h>
#include <assert.h>
#include <string>
#include <algorithm>
#include <vector>
#include "ola/Logging.h"
#include "ola/BaseTypes.h"
#include "plugins/ftdidmx/FtdiWidget.h"
namespace ola {
namespace plugin {
namespace ftdidmx {
using std::string;
using std::vector;
FtdiWidget::FtdiWidget(const string& serial,
const string& name,
uint32_t id)
: m_serial(serial),
m_name(name),
m_id(id) {
bzero(&m_handle, sizeof(struct ftdi_context));
ftdi_init(&m_handle);
}
FtdiWidget::~FtdiWidget() {
if (IsOpen())
Close();
ftdi_deinit(&m_handle);
}
/**
* Build a list of all attached ftdi devices
*/
void FtdiWidget::Widgets(vector<FtdiWidgetInfo> *widgets) {
int i = 0;
widgets->clear();
struct ftdi_device_list* list = NULL;
struct ftdi_context ftdi;
ftdi_init(&ftdi);
ftdi_usb_find_all(&ftdi, &list, FtdiWidget::VID, FtdiWidget::PID);
while (list != NULL) {
struct usb_device* dev = list->dev;
if (!dev) {
OLA_WARN << "Device returned from ftdi_usb_find_all was NULL";
continue;
}
char serial[256];
char name[256];
char vendor[256];
int r = ftdi_usb_get_strings(&ftdi, dev,
vendor, sizeof(vendor),
name, sizeof(name),
serial, sizeof(serial));
if (r) {
OLA_WARN << "Unable to fetch string information from USB device: " <<
ftdi_get_error_string(&ftdi);
continue;
}
string v = string(vendor);
string sname = string(name);
string sserial = string(serial);
if (sserial == "?") {
// this means there wasn't a serial number
sserial.clear();
}
OLA_INFO << "Found FTDI device. Vendor: '" << v << "', Name: '" << sname <<
"', Serial: '" << sserial << "'";
std::transform(v.begin(), v.end(), v.begin(), ::toupper);
if (std::string::npos != v.find("FTDI")) {
widgets->push_back(FtdiWidgetInfo(sname, sserial, i));
}
list = list->next;
i++;
}
ftdi_list_free(&list);
ftdi_deinit(&ftdi);
}
bool FtdiWidget::Open() {
if (ftdi_usb_open_desc(&m_handle, FtdiWidget::VID, FtdiWidget::PID,
Name().c_str(), Serial().c_str()) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::Close() {
if (ftdi_usb_close(&m_handle) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::IsOpen() const {
return (m_handle.usb_dev != NULL) ? true : false;
}
bool FtdiWidget::Reset() {
if (ftdi_usb_reset(&m_handle) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetLineProperties() {
if (ftdi_set_line_property(&m_handle, BITS_8, STOP_BIT_2, NONE) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetBaudRate() {
if (ftdi_set_baudrate(&m_handle, 250000) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetFlowControl() {
if (ftdi_setflowctrl(&m_handle, SIO_DISABLE_FLOW_CTRL) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::ClearRts() {
if (ftdi_setrts(&m_handle, 0) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::PurgeBuffers() {
if (ftdi_usb_purge_buffers(&m_handle) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetBreak(bool on) {
ftdi_break_type type;
if (on == true)
type = BREAK_ON;
else
type = BREAK_OFF;
if (ftdi_set_line_property2(&m_handle, BITS_8, STOP_BIT_2, NONE, type) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::Write(const ola::DmxBuffer& data) {
unsigned char buffer[DMX_UNIVERSE_SIZE + 1];
int unsigned length = DMX_UNIVERSE_SIZE;
buffer[0] = 0x00;
data.Get(buffer+1, &length);
if (ftdi_write_data(&m_handle, buffer, sizeof(buffer)) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::Read(unsigned char *buff, int size) {
int read = ftdi_read_data(&m_handle, buff, size);
if (read <= 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
} // ftdidmx
} // plugin
} // ola
<commit_msg> * fix a bug in the ftdi plugin<commit_after>/*
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. The license is
in the file "COPYING".
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
This class is based on QLCFTDI class from
Q Light Controller
qlcftdi-libftdi.cpp
Copyright (C) Heikki Junnila
Only standard CPP conversion was changed and function name changed
to follow OLA coding standards.
by
Rui Barreiros
*/
#include <strings.h>
#include <ftdi.h>
#include <assert.h>
#include <string>
#include <algorithm>
#include <vector>
#include "ola/Logging.h"
#include "ola/BaseTypes.h"
#include "plugins/ftdidmx/FtdiWidget.h"
namespace ola {
namespace plugin {
namespace ftdidmx {
using std::string;
using std::vector;
FtdiWidget::FtdiWidget(const string& serial,
const string& name,
uint32_t id)
: m_serial(serial),
m_name(name),
m_id(id) {
bzero(&m_handle, sizeof(struct ftdi_context));
ftdi_init(&m_handle);
}
FtdiWidget::~FtdiWidget() {
if (IsOpen())
Close();
ftdi_deinit(&m_handle);
}
/**
* Build a list of all attached ftdi devices
*/
void FtdiWidget::Widgets(vector<FtdiWidgetInfo> *widgets) {
int i = -1;
widgets->clear();
struct ftdi_device_list* list = NULL;
struct ftdi_context ftdi;
ftdi_init(&ftdi);
ftdi_usb_find_all(&ftdi, &list, FtdiWidget::VID, FtdiWidget::PID);
while (list != NULL) {
struct usb_device* dev = list->dev;
list = list->next;
i++;
if (!dev) {
OLA_WARN << "Device returned from ftdi_usb_find_all was NULL";
continue;
}
char serial[256];
char name[256];
char vendor[256];
int r = ftdi_usb_get_strings(&ftdi, dev,
vendor, sizeof(vendor),
name, sizeof(name),
serial, sizeof(serial));
if (r) {
OLA_WARN << "Unable to fetch string information from USB device: " <<
ftdi_get_error_string(&ftdi);
continue;
}
string v = string(vendor);
string sname = string(name);
string sserial = string(serial);
if (sserial == "?") {
// this means there wasn't a serial number
sserial.clear();
}
OLA_INFO << "Found FTDI device. Vendor: '" << v << "', Name: '" << sname <<
"', Serial: '" << sserial << "'";
std::transform(v.begin(), v.end(), v.begin(), ::toupper);
if (std::string::npos != v.find("FTDI")) {
widgets->push_back(FtdiWidgetInfo(sname, sserial, i));
}
}
ftdi_list_free(&list);
ftdi_deinit(&ftdi);
}
bool FtdiWidget::Open() {
if (ftdi_usb_open_desc(&m_handle, FtdiWidget::VID, FtdiWidget::PID,
Name().c_str(), Serial().c_str()) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::Close() {
if (ftdi_usb_close(&m_handle) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::IsOpen() const {
return (m_handle.usb_dev != NULL) ? true : false;
}
bool FtdiWidget::Reset() {
if (ftdi_usb_reset(&m_handle) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetLineProperties() {
if (ftdi_set_line_property(&m_handle, BITS_8, STOP_BIT_2, NONE) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetBaudRate() {
if (ftdi_set_baudrate(&m_handle, 250000) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetFlowControl() {
if (ftdi_setflowctrl(&m_handle, SIO_DISABLE_FLOW_CTRL) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::ClearRts() {
if (ftdi_setrts(&m_handle, 0) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::PurgeBuffers() {
if (ftdi_usb_purge_buffers(&m_handle) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::SetBreak(bool on) {
ftdi_break_type type;
if (on == true)
type = BREAK_ON;
else
type = BREAK_OFF;
if (ftdi_set_line_property2(&m_handle, BITS_8, STOP_BIT_2, NONE, type) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::Write(const ola::DmxBuffer& data) {
unsigned char buffer[DMX_UNIVERSE_SIZE + 1];
int unsigned length = DMX_UNIVERSE_SIZE;
buffer[0] = 0x00;
data.Get(buffer+1, &length);
if (ftdi_write_data(&m_handle, buffer, sizeof(buffer)) < 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
bool FtdiWidget::Read(unsigned char *buff, int size) {
int read = ftdi_read_data(&m_handle, buff, size);
if (read <= 0) {
OLA_WARN << Name() << " " << ftdi_get_error_string(&m_handle);
return false;
} else {
return true;
}
}
} // ftdidmx
} // plugin
} // ola
<|endoftext|>
|
<commit_before>// Copyright 2019, Intel Corporation
#include "mlir/ADT/TypeSwitch.h"
#include "mlir/Dialect/AffineOps/AffineOps.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/AffineExprVisitor.h"
#include "mlir/Support/DebugStringHelper.h"
#include "llvm/ADT/Optional.h"
#include "pmlc/dialect/eltwise/ir/ops.h"
#include "pmlc/dialect/pxa/analysis/strides.h"
#include "pmlc/dialect/pxa/ir/ops.h"
#include "pmlc/dialect/pxa/transforms/passes.h"
#include "pmlc/dialect/tile/ir/ops.h"
#include "pmlc/util/logging.h"
#include "pmlc/util/util.h"
namespace pmlc::dialect::pxa {
enum MulOperationType {
NoneMulOpType,
FloatTy,
IntTy,
};
// Number of tensors for the matrix multiplication
const unsigned kNumTensors = 3;
class Stencil {
private:
// Number of instructions that need to be presented in the ParallelOp region
// to be Considered a Gemm operation. For now they are affine.load,
// affined.load, mul(f/i), reduce add, terminator.
const unsigned kNumValidInstrInGemmRegion = 5;
// The ParallelOp that is being stencelled.
mlir::AffineParallelOp op;
// Target tensors, the first two are load, the third is aggregate
llvm::SmallVector<Value, kNumTensors> tensors;
// Target tensors strides, the first two are load, the third is aggregate
llvm::SmallVector<mlir::StrideInfo, kNumTensors> tensorsStrides;
// Found Gemm operation data
MulOperationType mulOpType;
mlir::AffineLoadOp in1Op;
mlir::AffineLoadOp in2Op;
AffineReduceOp outOp;
public:
explicit Stencil(mlir::AffineParallelOp opIn) : op(opIn) {}
// Main function
void DoStenciling();
// Returns if a Gemm operation is identified.
bool TryIdentifyGemmOperation();
// Collect the tensors in the block
bool CollectTensors();
// Collect the StrideInfo of the tensors in the block
bool ComputeStrideInfo();
};
bool Stencil::TryIdentifyGemmOperation() {
auto *body = op.getBody();
// Get the instructions in the body and match for load, load, mulXXX, reduce
// add operations. For everything else we fail.
if (body->getOperations().size() != kNumValidInstrInGemmRegion) {
IVLOG(3, "the ParallelOp region didn't have the right number of "
"instructions for a Gemm");
return false;
}
auto beforeLastInstr = std::prev(body->end(), 2);
AffineReduceOp reduceOp = llvm::dyn_cast<AffineReduceOp>(*beforeLastInstr);
if (!reduceOp) {
return false;
}
IVLOG(3, "Found ReduceOp");
// Not check the reduceOp aggregation.
if (reduceOp.agg() != AggregationKind::add) {
IVLOG(3, "the reduce operation is not addition");
return false;
}
// Get the in tensors for the reduce op.
Value reduceIn = reduceOp.val();
MulOperationType mulOpType = MulOperationType::NoneMulOpType;
// Make sure the in for the reduce is a result of a multiplication.
auto valDef = reduceIn.getDefiningOp();
if (!valDef) {
IVLOG(3, "the source of the reduce operation is not defined in this block");
return false;
}
mlir::MulFOp mulfOp = llvm::dyn_cast_or_null<mlir::MulFOp>(valDef);
mlir::MulIOp muliOp = llvm::dyn_cast_or_null<mlir::MulIOp>(valDef);
if (!mulfOp && !muliOp) {
IVLOG(3, "The source of the reduce is not a multiplication operation");
return false;
}
mlir::AffineLoadOp lhs;
mlir::AffineLoadOp rhs;
if (mulfOp) {
mulOpType = MulOperationType::FloatTy;
lhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
mulfOp.lhs().getDefiningOp());
rhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
mulfOp.rhs().getDefiningOp());
} else if (muliOp) {
mulOpType = MulOperationType::IntTy;
lhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
muliOp.lhs().getDefiningOp());
rhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
muliOp.rhs().getDefiningOp());
}
// Now verify the types of the operands of the mulOp must be affine.load
// operations.
if (!lhs || !rhs || mulOpType == NoneMulOpType) {
IVLOG(
3,
"the lhs or rhs of the mul operation are not an affne.load operations "
"or the type of the multiplication is not on floats or ints.");
return false;
}
// Fill the values for the in/out/type of multiplication, etc.
this->mulOpType = mulOpType;
in1Op = lhs;
in2Op = rhs;
outOp = reduceOp;
return true;
}
bool Stencil::CollectTensors() {
assert(in1Op && in2Op && outOp);
tensors.push_back(in1Op.getMemRef());
tensors.push_back(in2Op.getMemRef());
tensors.push_back(outOp.out());
return tensors.size() == kNumTensors;
}
bool Stencil::ComputeStrideInfo() {
assert(in1Op && in2Op && outOp);
auto in1OpOptional = computeStrideInfo(in1Op);
auto in2OpOptional = computeStrideInfo(in2Op);
auto outOpOptional = computeStrideInfo(outOp);
if (!in1OpOptional || !in2OpOptional || !outOpOptional)
return false;
tensorsStrides.push_back(*in1OpOptional);
tensorsStrides.push_back(*in2OpOptional);
tensorsStrides.push_back(*outOpOptional);
return tensorsStrides.size() == kNumTensors;
}
void Stencil::DoStenciling() {
// Initialization
if (!TryIdentifyGemmOperation()) {
IVLOG(3, "Not a Gemm match.");
return;
}
if (!CollectTensors())
return;
if (!ComputeStrideInfo())
return;
op.setAttr("is_gemm", mlir::UnitAttr::get(op.getContext()));
}
void StencilPass::runOnFunction() {
auto func = getFunction();
func.walk([&](mlir::AffineParallelOp op) {
Stencil as(op);
as.DoStenciling();
});
}
std::unique_ptr<mlir::Pass> createStencilPass() {
return std::make_unique<StencilPass>();
}
} // namespace pmlc::dialect::pxa
<commit_msg>Add code to find used and stride one indexes for stencilling (#959)<commit_after>// Copyright 2019, Intel Corporation
#include "mlir/ADT/TypeSwitch.h"
#include "mlir/Dialect/AffineOps/AffineOps.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/AffineExprVisitor.h"
#include "mlir/Support/DebugStringHelper.h"
#include "llvm/ADT/Optional.h"
#include "pmlc/dialect/eltwise/ir/ops.h"
#include "pmlc/dialect/pxa/analysis/strides.h"
#include "pmlc/dialect/pxa/ir/ops.h"
#include "pmlc/dialect/pxa/transforms/passes.h"
#include "pmlc/dialect/tile/ir/ops.h"
#include "pmlc/util/logging.h"
#include "pmlc/util/util.h"
namespace pmlc::dialect::pxa {
enum MulOperationType {
NoneMulOpType,
FloatTy,
IntTy,
};
using BlockArgumentSet = llvm::SmallPtrSet<mlir::BlockArgument, 8>;
// Number of tensors for the matrix multiplication
const unsigned kNumTensors = 3;
// Number of indices to search for (e.g. M, N, K)
const unsigned kNumIndex = 3;
class Stencil {
private:
// Number of instructions that need to be presented in the ParallelOp region
// to be Considered a Gemm operation. For now they are affine.load,
// affined.load, mul(f/i), reduce add, terminator.
const unsigned kNumValidInstrInGemmRegion = 5;
// The ParallelOp that is being stencelled.
mlir::AffineParallelOp op;
// Target tensors, the first two are load, the third is aggregate
llvm::SmallVector<Value, kNumTensors> tensors;
// Target tensors strides, the first two are load, the third is aggregate
llvm::SmallVector<mlir::StrideInfo, kNumTensors> tensorsStrides;
// Set of the op's BlockArguments.
BlockArgumentSet opBlockArguments;
// Index in tensors
BlockArgumentSet tensorIdxs[kNumTensors];
// Stride one index for the tensors
BlockArgumentSet strideOne[kNumTensors];
// The indices used by the output tensor
BlockArgumentSet outIdxs;
// The accumulation indices
BlockArgumentSet accIdxs;
// All used indices
BlockArgumentSet allIdxs;
// Found Gemm operation data
MulOperationType mulOpType;
mlir::AffineLoadOp in1Op;
mlir::AffineLoadOp in2Op;
AffineReduceOp outOp;
void PopulateOpBlockArgumentSet();
BlockArgumentSet UsedIdxs(unsigned strideInfoIndex);
void CollectUsedIndices();
void CollectStrideOneIndices();
void strideOneIdxs(unsigned indx);
public:
explicit Stencil(mlir::AffineParallelOp opIn) : op(opIn) {}
// Main function
void DoStenciling();
// Returns if a Gemm operation is identified.
bool TryIdentifyGemmOperation();
// Collect the tensors in the block
bool CollectTensors();
// Collect the StrideInfo of the tensors in the block
bool ComputeStrideInfo();
};
bool Stencil::TryIdentifyGemmOperation() {
auto *body = op.getBody();
// Get the instructions in the body and match for load, load, mulXXX, reduce
// add operations. For everything else we fail.
if (body->getOperations().size() != kNumValidInstrInGemmRegion) {
IVLOG(3, "the ParallelOp region didn't have the right number of "
"instructions for a Gemm");
return false;
}
auto beforeLastInstr = std::prev(body->end(), 2);
AffineReduceOp reduceOp = llvm::dyn_cast<AffineReduceOp>(*beforeLastInstr);
if (!reduceOp) {
return false;
}
IVLOG(3, "Found ReduceOp");
// Not check the reduceOp aggregation.
if (reduceOp.agg() != AggregationKind::add) {
IVLOG(3, "the reduce operation is not addition");
return false;
}
// Get the in tensors for the reduce op.
Value reduceIn = reduceOp.val();
MulOperationType mulOpType = MulOperationType::NoneMulOpType;
// Make sure the in for the reduce is a result of a multiplication.
auto valDef = reduceIn.getDefiningOp();
if (!valDef) {
IVLOG(3, "the source of the reduce operation is not defined in this block");
return false;
}
mlir::MulFOp mulfOp = llvm::dyn_cast_or_null<mlir::MulFOp>(valDef);
mlir::MulIOp muliOp = llvm::dyn_cast_or_null<mlir::MulIOp>(valDef);
if (!mulfOp && !muliOp) {
IVLOG(3, "The source of the reduce is not a multiplication operation");
return false;
}
mlir::AffineLoadOp lhs;
mlir::AffineLoadOp rhs;
if (mulfOp) {
mulOpType = MulOperationType::FloatTy;
lhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
mulfOp.lhs().getDefiningOp());
rhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
mulfOp.rhs().getDefiningOp());
} else if (muliOp) {
mulOpType = MulOperationType::IntTy;
lhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
muliOp.lhs().getDefiningOp());
rhs = llvm::dyn_cast_or_null<mlir::AffineLoadOp>(
muliOp.rhs().getDefiningOp());
}
// Now verify the types of the operands of the mulOp must be affine.load
// operations.
if (!lhs || !rhs || mulOpType == NoneMulOpType) {
IVLOG(
3,
"the lhs or rhs of the mul operation are not an affne.load operations "
"or the type of the multiplication is not on floats or ints.");
return false;
}
// Fill the values for the in/out/type of multiplication, etc.
this->mulOpType = mulOpType;
in1Op = lhs;
in2Op = rhs;
outOp = reduceOp;
return true;
}
bool Stencil::CollectTensors() {
assert(in1Op && in2Op && outOp);
tensors.push_back(in1Op.getMemRef());
tensors.push_back(in2Op.getMemRef());
tensors.push_back(outOp.out());
return tensors.size() == kNumTensors;
}
bool Stencil::ComputeStrideInfo() {
assert(in1Op && in2Op && outOp);
auto in1OpOptional = computeStrideInfo(in1Op);
auto in2OpOptional = computeStrideInfo(in2Op);
auto outOpOptional = computeStrideInfo(outOp);
if (!in1OpOptional || !in2OpOptional || !outOpOptional)
return false;
tensorsStrides.push_back(*in1OpOptional);
tensorsStrides.push_back(*in2OpOptional);
tensorsStrides.push_back(*outOpOptional);
return tensorsStrides.size() == kNumTensors;
}
// Collect the non constant indices used to index the memref at specific index.
// Ignore indices that are constant for the ParallelOp.
BlockArgumentSet Stencil::UsedIdxs(unsigned strideInfoIndex) {
assert(strideInfoIndex < kNumTensors);
BlockArgumentSet used_idxs;
for (auto kv : tensorsStrides[strideInfoIndex].strides) {
// Make sure the BlockArgument is in the list of the ParallelOp's
// BlockArguments.
if (opBlockArguments.find(kv.first) != opBlockArguments.end()) {
used_idxs.insert(kv.first);
}
}
return used_idxs;
}
void Stencil::PopulateOpBlockArgumentSet() {
for (auto blkArg : op.getBody()->getArguments()) {
opBlockArguments.insert(blkArg);
}
}
// Collect the indices that are not constants for the ParallelOp
// and also the accumulation indices.
void Stencil::CollectUsedIndices() {
// The last tensor is the output.
tensorIdxs[kNumIndex - 1] = UsedIdxs(kNumIndex - 1);
outIdxs = tensorIdxs[kNumIndex - 1];
accIdxs.clear();
for (unsigned i = 0; i < kNumIndex - 1; ++i) {
tensorIdxs[i] = UsedIdxs(i);
for (auto idx : tensorIdxs[i]) {
if (outIdxs.find(idx) == outIdxs.end()) {
accIdxs.insert(idx);
}
}
}
// Add the out used indices to the all the used indices collection as well.
allIdxs = accIdxs;
allIdxs.insert(outIdxs.begin(), outIdxs.end());
}
// Get the indices with stride of one.
void Stencil::strideOneIdxs(unsigned indx) {
for (auto kv : tensorsStrides[indx].strides) {
if (kv.second == 1) {
strideOne[indx].insert(kv.first);
}
}
}
void Stencil::CollectStrideOneIndices() {
// Collect stride-one index
for (unsigned i = 0; i < kNumTensors; ++i) {
strideOneIdxs(i);
}
}
void Stencil::DoStenciling() {
// Initialization
if (!TryIdentifyGemmOperation()) {
IVLOG(3, "Not a Gemm match.");
return;
}
if (!CollectTensors())
return;
if (!ComputeStrideInfo())
return;
PopulateOpBlockArgumentSet();
CollectUsedIndices();
CollectStrideOneIndices();
op.setAttr("is_gemm", mlir::UnitAttr::get(op.getContext()));
}
void StencilPass::runOnFunction() {
auto func = getFunction();
func.walk([&](mlir::AffineParallelOp op) {
Stencil as(op);
as.DoStenciling();
});
}
std::unique_ptr<mlir::Pass> createStencilPass() {
return std::make_unique<StencilPass>();
}
} // namespace pmlc::dialect::pxa
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "atomic.h"
#define NEED_SWAP_MUTEXES !defined(__arm__) && !defined(__i386__)
#if NEED_SWAP_MUTEXES
#include <vector>
#include "base/mutex.h"
#include "base/stl_util.h"
#include "base/stringprintf.h"
#include "thread.h"
#endif
namespace art {
#if NEED_SWAP_MUTEXES
// We stripe across a bunch of different mutexes to reduce contention.
static const size_t kSwapMutexCount = 32;
static std::vector<Mutex*>* gSwapMutexes;
static Mutex& GetSwapMutex(const volatile int64_t* addr) {
return *(*gSwapMutexes)[((unsigned)(void*)(addr) >> 3U) % kSwapMutexCount];
}
#endif
void QuasiAtomic::Startup() {
#if NEED_SWAP_MUTEXES
gSwapMutexes = new std::vector<Mutex*>;
for (size_t i = 0; i < kSwapMutexCount; ++i) {
gSwapMutexes->push_back(new Mutex(StringPrintf("QuasiAtomic stripe %d", i).c_str()));
}
#endif
}
void QuasiAtomic::Shutdown() {
#if NEED_SWAP_MUTEXES
STLDeleteElements(gSwapMutexes);
delete gSwapMutexes;
#endif
}
int64_t QuasiAtomic::Read64(volatile const int64_t* addr) {
int64_t value;
#if defined(__arm__)
// Exclusive loads are defined not to tear, clearing the exclusive state isn't necessary. If we
// have LPAE (such as Cortex-A15) then ldrd would suffice.
__asm__ __volatile__("@ QuasiAtomic::Read64\n"
"ldrexd %0, %H0, [%1]"
: "=&r" (value)
: "r" (addr));
#elif defined(__i386__)
__asm__ __volatile__(
"movq %1, %0\n"
: "=x" (value)
: "m" (*addr));
#else
MutexLock mu(Thread::Current(), GetSwapMutex(addr));
return *addr;
#endif
return value;
}
void QuasiAtomic::Write64(volatile int64_t* addr, int64_t value) {
#if defined(__arm__)
// The write is done as a swap so that the cache-line is in the exclusive state for the store. If
// we know that ARM architecture has LPAE (such as Cortex-A15) this isn't necessary and strd will
// suffice.
int64_t prev;
int status;
do {
__asm__ __volatile__("@ QuasiAtomic::Write64\n"
"ldrexd %0, %H0, [%3]\n"
"strexd %1, %4, %H4, [%3]"
: "=&r" (prev), "=&r" (status), "+m"(*addr)
: "r" (addr), "r" (value)
: "cc");
} while (__builtin_expect(status != 0, 0));
#elif defined(__i386__)
__asm__ __volatile__(
"movq %1, %0"
: "=m" (*addr)
: "x" (value));
#else
MutexLock mu(Thread::Current(), GetSwapMutex(addr));
*addr = value;
#endif
}
bool QuasiAtomic::Cas64(int64_t old_value, int64_t new_value, volatile int64_t* addr) {
#if defined(__arm__)
int64_t prev;
int status;
do {
__asm__ __volatile__("@ QuasiAtomic::Cas64\n"
"ldrexd %0, %H0, [%3]\n"
"mov %1, #0\n"
"teq %0, %4\n"
"teqeq %H0, %H4\n"
"strexdeq %1, %5, %H5, [%3]"
: "=&r" (prev), "=&r" (status), "+m"(*addr)
: "r" (addr), "Ir" (old_value), "r" (new_value)
: "cc");
} while (__builtin_expect(status != 0, 0));
return prev != old_value;
#elif defined(__i386__)
// cmpxchg8b implicitly uses %ebx which is also the PIC register.
int8_t status;
__asm__ __volatile__ (
"pushl %%ebx\n"
"movl (%3), %%ebx\n"
"movl 4(%3), %%ecx\n"
"lock cmpxchg8b %1\n"
"sete %0\n"
"popl %%ebx"
: "=R" (status), "+m" (*addr)
: "A"(old_value), "D" (&new_value)
: "%ecx"
);
return status != 0;
#else
MutexLock mu(Thread::Current(), GetSwapMutex(addr));
if (*addr == old_value) {
*addr = new_value;
return true;
}
return false;
#endif
}
bool QuasiAtomic::LongAtomicsUseMutexes() {
#if NEED_SWAP_MUTEXES
return true;
#else
return false;
#endif
}
} // namespace art
<commit_msg>Fix ARM CAS64.<commit_after>/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "atomic.h"
#define NEED_SWAP_MUTEXES !defined(__arm__) && !defined(__i386__)
#if NEED_SWAP_MUTEXES
#include <vector>
#include "base/mutex.h"
#include "base/stl_util.h"
#include "base/stringprintf.h"
#include "thread.h"
#endif
namespace art {
#if NEED_SWAP_MUTEXES
// We stripe across a bunch of different mutexes to reduce contention.
static const size_t kSwapMutexCount = 32;
static std::vector<Mutex*>* gSwapMutexes;
static Mutex& GetSwapMutex(const volatile int64_t* addr) {
return *(*gSwapMutexes)[((unsigned)(void*)(addr) >> 3U) % kSwapMutexCount];
}
#endif
void QuasiAtomic::Startup() {
#if NEED_SWAP_MUTEXES
gSwapMutexes = new std::vector<Mutex*>;
for (size_t i = 0; i < kSwapMutexCount; ++i) {
gSwapMutexes->push_back(new Mutex(StringPrintf("QuasiAtomic stripe %d", i).c_str()));
}
#endif
}
void QuasiAtomic::Shutdown() {
#if NEED_SWAP_MUTEXES
STLDeleteElements(gSwapMutexes);
delete gSwapMutexes;
#endif
}
int64_t QuasiAtomic::Read64(volatile const int64_t* addr) {
int64_t value;
#if defined(__arm__)
// Exclusive loads are defined not to tear, clearing the exclusive state isn't necessary. If we
// have LPAE (such as Cortex-A15) then ldrd would suffice.
__asm__ __volatile__("@ QuasiAtomic::Read64\n"
"ldrexd %0, %H0, [%1]"
: "=&r" (value)
: "r" (addr));
#elif defined(__i386__)
__asm__ __volatile__(
"movq %1, %0\n"
: "=x" (value)
: "m" (*addr));
#else
MutexLock mu(Thread::Current(), GetSwapMutex(addr));
return *addr;
#endif
return value;
}
void QuasiAtomic::Write64(volatile int64_t* addr, int64_t value) {
#if defined(__arm__)
// The write is done as a swap so that the cache-line is in the exclusive state for the store. If
// we know that ARM architecture has LPAE (such as Cortex-A15) this isn't necessary and strd will
// suffice.
int64_t prev;
int status;
do {
__asm__ __volatile__("@ QuasiAtomic::Write64\n"
"ldrexd %0, %H0, [%3]\n"
"strexd %1, %4, %H4, [%3]"
: "=&r" (prev), "=&r" (status), "+m"(*addr)
: "r" (addr), "r" (value)
: "cc");
} while (__builtin_expect(status != 0, 0));
#elif defined(__i386__)
__asm__ __volatile__(
"movq %1, %0"
: "=m" (*addr)
: "x" (value));
#else
MutexLock mu(Thread::Current(), GetSwapMutex(addr));
*addr = value;
#endif
}
bool QuasiAtomic::Cas64(int64_t old_value, int64_t new_value, volatile int64_t* addr) {
#if defined(__arm__)
int64_t prev;
int status;
do {
__asm__ __volatile__("@ QuasiAtomic::Cas64\n"
"ldrexd %0, %H0, [%3]\n"
"mov %1, #0\n"
"teq %0, %4\n"
"teqeq %H0, %H4\n"
"strexdeq %1, %5, %H5, [%3]"
: "=&r" (prev), "=&r" (status), "+m"(*addr)
: "r" (addr), "Ir" (old_value), "r" (new_value)
: "cc");
} while (__builtin_expect(status != 0, 0));
return prev == old_value;
#elif defined(__i386__)
// cmpxchg8b implicitly uses %ebx which is also the PIC register.
int8_t status;
__asm__ __volatile__ (
"pushl %%ebx\n"
"movl (%3), %%ebx\n"
"movl 4(%3), %%ecx\n"
"lock cmpxchg8b %1\n"
"sete %0\n"
"popl %%ebx"
: "=R" (status), "+m" (*addr)
: "A"(old_value), "D" (&new_value)
: "%ecx"
);
return status != 0;
#else
MutexLock mu(Thread::Current(), GetSwapMutex(addr));
if (*addr == old_value) {
*addr = new_value;
return true;
}
return false;
#endif
}
bool QuasiAtomic::LongAtomicsUseMutexes() {
#if NEED_SWAP_MUTEXES
return true;
#else
return false;
#endif
}
} // namespace art
<|endoftext|>
|
<commit_before>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED
#define HAS_STATIC_MEMBER_DETECTOR(member) \
template<typename T> \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, decltype(U::member)* func = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_STATIC_MEMBER(type, member) \
(HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)
#define HAS_NESTED_TYPE_DETECTOR(member) \
template<typename T> \
class HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, typename U::member* ty = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_NESTED_TYPE(type, member) \
(HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member<type>::value)
enum class CWrapperType
{
Implicit,
Explicit,
Get,
};
template<
typename H,
typename F,
CWrapperType TY,
bool C>
class __CWrapperHelper__
{
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ArrowHandler
{ };
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
PTR_T* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* operator->()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
CWrapperType TYPE,
bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
operator HANDLE_T() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
explicit operator HANDLE_T() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
HANDLE_T get() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
operator PTR_T const*() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
explicit operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
explicit operator PTR_T const*() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* get()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* get() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperBase
: public ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperBase(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw EXCEPTION_T{};
}
CWrapperBase(CWrapperBase const& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperBase(CWrapperBase& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
template<typename... ARGS>
explicit CWrapperBase(ARGS&&... args) :
CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperBase(CWrapperBase&& old) :
CWrapperBase{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperBase& operator=(CWrapperBase&& old)
{
if(this != &old)
{
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperBase()
{
FUNCTIONS::dtor_func(ptr);
}
CWrapperBase& operator=(CWrapperBase const& other)
{
if(this != &other)
{
HANDLE_T new_ptr = FUNCTIONS::copy_func(other.ptr);
if(!VALIDATE_T::validate_func(new_ptr))
throw EXCEPTION_T{};
FUNCTIONS::dtor_func(ptr);
ptr = new_ptr;
}
return *this;
}
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperNonCopiable
: public ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperNonCopiable(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw EXCEPTION_T{};
}
template<typename... ARGS>
explicit CWrapperNonCopiable(ARGS&&... args) :
CWrapperNonCopiable{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperNonCopiable(CWrapperNonCopiable&& old) :
CWrapperNonCopiable{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperNonCopiable& operator=(CWrapperNonCopiable&& old)
{
if(this != &old)
{
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperNonCopiable()
{
FUNCTIONS::dtor_func(ptr);
}
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperNonCopiable(CWrapperNonCopiable& other) = delete;
CWrapperNonCopiable(CWrapperNonCopiable const& other) = delete;
CWrapperNonCopiable& operator=(CWrapperNonCopiable const& other) = delete;
};
template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
using type = TRUE_TYPE;
};
template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
using type = FALSE_TYPE;
};
HAS_NESTED_TYPE_DETECTOR(exception);
HAS_STATIC_MEMBER_DETECTOR(copy_func);
HAS_STATIC_MEMBER_DETECTOR(invalid_value);
HAS_STATIC_MEMBER_DETECTOR(validate_func);
template<typename TYPE, typename DEFTYPE, bool>
struct default_exception_type
{
using type = DEFTYPE;
};
template<typename TYPE, typename DEFTYPE>
struct default_exception_type<TYPE, DEFTYPE, true>
{
using type = typename TYPE::exception;
};
template<typename T>
struct default_invalid_value
{
static constexpr T invalid_value = 0;
};
template<typename T>
struct default_invalid_value<T*>
{
static constexpr T* invalid_value = nullptr;
};
template<typename T, typename INVALID_T>
struct default_validate_func
{
static constexpr bool validate_func(T ptr)
{
return ptr != INVALID_T::invalid_value;
}
};
using E = typename default_exception_type<F, std::bad_alloc, HAS_NESTED_TYPE(F, exception)>::type;
using D = typename COND< HAS_STATIC_MEMBER(F, invalid_value),
F, default_invalid_value<H>>::type;
using V = typename COND< HAS_STATIC_MEMBER(F, validate_func),
F, default_validate_func<H, D>>::type;
public:
using type = typename COND< HAS_STATIC_MEMBER(F, copy_func),
CWrapperBase<H, F, TY, C, E, D, V>,
CWrapperNonCopiable<H, F, TY, C, E, D, V>>::type;
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE = CWrapperType::Get,
bool CONSTSAFE = true>
using CWrapper = typename __CWrapperHelper__<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE>::type;
#endif // CWRAPPER_HPP_INCLUDED
<commit_msg>Default exception simplified<commit_after>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED
#define HAS_STATIC_MEMBER_DETECTOR(member) \
template<typename T> \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, decltype(U::member)* func = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_STATIC_MEMBER(type, member) \
(HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)
#define HAS_NESTED_TYPE_DETECTOR(member) \
template<typename T> \
class HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, typename U::member* ty = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_NESTED_TYPE(type, member) \
(HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member<type>::value)
enum class CWrapperType
{
Implicit,
Explicit,
Get,
};
template<
typename H,
typename F,
CWrapperType TY,
bool C>
class __CWrapperHelper__
{
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ArrowHandler
{ };
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
PTR_T* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* operator->()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
CWrapperType TYPE,
bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
operator HANDLE_T() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
explicit operator HANDLE_T() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
HANDLE_T get() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
operator PTR_T const*() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
explicit operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
explicit operator PTR_T const*() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* get()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* get() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperBase
: public ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperBase(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
CWrapperBase(CWrapperBase const& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperBase(CWrapperBase& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
template<typename... ARGS>
explicit CWrapperBase(ARGS&&... args) :
CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperBase(CWrapperBase&& old) :
CWrapperBase{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperBase& operator=(CWrapperBase&& old)
{
if(this != &old)
{
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperBase()
{
FUNCTIONS::dtor_func(ptr);
}
CWrapperBase& operator=(CWrapperBase const& other)
{
if(this != &other)
{
HANDLE_T new_ptr = FUNCTIONS::copy_func(other.ptr);
if(!VALIDATE_T::validate_func(new_ptr))
throw typename EXCEPTION_T::exception{};
FUNCTIONS::dtor_func(ptr);
ptr = new_ptr;
}
return *this;
}
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperNonCopiable
: public ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperNonCopiable(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
template<typename... ARGS>
explicit CWrapperNonCopiable(ARGS&&... args) :
CWrapperNonCopiable{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperNonCopiable(CWrapperNonCopiable&& old) :
CWrapperNonCopiable{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperNonCopiable& operator=(CWrapperNonCopiable&& old)
{
if(this != &old)
{
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperNonCopiable()
{
FUNCTIONS::dtor_func(ptr);
}
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperNonCopiable(CWrapperNonCopiable& other) = delete;
CWrapperNonCopiable(CWrapperNonCopiable const& other) = delete;
CWrapperNonCopiable& operator=(CWrapperNonCopiable const& other) = delete;
};
template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
using type = TRUE_TYPE;
};
template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
using type = FALSE_TYPE;
};
HAS_NESTED_TYPE_DETECTOR(exception);
HAS_STATIC_MEMBER_DETECTOR(copy_func);
HAS_STATIC_MEMBER_DETECTOR(invalid_value);
HAS_STATIC_MEMBER_DETECTOR(validate_func);
struct default_exception_type
{
using exception = std::bad_alloc;
};
template<typename T>
struct default_invalid_value
{
static constexpr T invalid_value = 0;
};
template<typename T>
struct default_invalid_value<T*>
{
static constexpr T* invalid_value = nullptr;
};
template<typename T, typename INVALID_T>
struct default_validate_func
{
static constexpr bool validate_func(T ptr)
{
return ptr != INVALID_T::invalid_value;
}
};
using E = typename COND< HAS_NESTED_TYPE(F, exception),
F, default_exception_type>::type;
using D = typename COND< HAS_STATIC_MEMBER(F, invalid_value),
F, default_invalid_value<H>>::type;
using V = typename COND< HAS_STATIC_MEMBER(F, validate_func),
F, default_validate_func<H, D>>::type;
public:
using type = typename COND< HAS_STATIC_MEMBER(F, copy_func),
CWrapperBase<H, F, TY, C, E, D, V>,
CWrapperNonCopiable<H, F, TY, C, E, D, V>>::type;
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE = CWrapperType::Get,
bool CONSTSAFE = true>
using CWrapper = typename __CWrapperHelper__<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE>::type;
#endif // CWRAPPER_HPP_INCLUDED
<|endoftext|>
|
<commit_before>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED
#define HAS_STATIC_MEMBER_DETECTOR(member) \
template<typename T> \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, decltype(U::member)* func = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_STATIC_MEMBER(type, member) \
(HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)
#define HAS_NESTED_TYPE_DETECTOR(member) \
template<typename T> \
class HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, typename U::member* ty = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_NESTED_TYPE(type, member) \
(HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member<type>::value)
namespace CW {
enum class CWrapperType
{
Implicit,
Explicit,
Get,
};
template<
typename H,
typename F,
CWrapperType TY = CWrapperType::Get,
bool C = true>
class CWrapperFriend
{
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ArrowHandler
{ };
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
PTR_T* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* operator->()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
CWrapperType TYPE,
bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
operator HANDLE_T() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
explicit operator HANDLE_T() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
HANDLE_T get() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
operator PTR_T const*() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
explicit operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
explicit operator PTR_T const*() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* get()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* get() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperBase
: public ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperBase(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
CWrapperBase(CWrapperBase const& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperBase(CWrapperBase& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
template<typename... ARGS>
explicit CWrapperBase(ARGS&&... args) :
CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperBase(CWrapperBase&& old) :
CWrapperBase{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperBase& operator=(CWrapperBase&& old)
{
if(this != &old)
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperBase()
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
}
CWrapperBase& operator=(CWrapperBase const& other)
{
if(this != &other)
{
HANDLE_T new_ptr = FUNCTIONS::copy_func(other.ptr);
if(!VALIDATE_T::validate_func(new_ptr))
throw typename EXCEPTION_T::exception{};
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = new_ptr;
}
return *this;
}
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperNonCopiable
: public ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperNonCopiable(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
template<typename... ARGS>
explicit CWrapperNonCopiable(ARGS&&... args) :
CWrapperNonCopiable{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperNonCopiable(CWrapperNonCopiable&& old) :
CWrapperNonCopiable{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperNonCopiable& operator=(CWrapperNonCopiable&& old)
{
if(this != &old)
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperNonCopiable()
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
}
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperNonCopiable(CWrapperNonCopiable& other) = delete;
CWrapperNonCopiable(CWrapperNonCopiable const& other) = delete;
CWrapperNonCopiable& operator=(CWrapperNonCopiable const& other) = delete;
};
template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
using type = TRUE_TYPE;
};
template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
using type = FALSE_TYPE;
};
HAS_NESTED_TYPE_DETECTOR(exception);
HAS_STATIC_MEMBER_DETECTOR(copy_func);
HAS_STATIC_MEMBER_DETECTOR(invalid_value);
HAS_STATIC_MEMBER_DETECTOR(validate_func);
struct default_exception_type
{
using exception = std::bad_alloc;
};
template<typename T>
struct default_invalid_value
{
static constexpr T invalid_value = 0;
};
template<typename T>
struct default_invalid_value<T*>
{
static constexpr T* invalid_value = nullptr;
};
template<typename T, typename INVALID_T>
struct default_validate_func
{
static constexpr bool validate_func(T ptr)
{
return ptr != INVALID_T::invalid_value;
}
};
using E = typename COND< HAS_NESTED_TYPE(F, exception),
F, default_exception_type>::type;
using D = typename COND< HAS_STATIC_MEMBER(F, invalid_value),
F, default_invalid_value<H>>::type;
using V = typename COND< HAS_STATIC_MEMBER(F, validate_func),
F, default_validate_func<H, D>>::type;
public:
using type = typename COND< HAS_STATIC_MEMBER(F, copy_func),
CWrapperBase<H, F, TY, C, E, D, V>,
CWrapperNonCopiable<H, F, TY, C, E, D, V>>::type;
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE = CWrapperType::Get,
bool CONSTSAFE = true>
using CWrapper = typename CWrapperFriend<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE>::type;
}
#undef HAS_STATIC_MEMBER_DETECTOR
#undef HAS_STATIC_MEMBER
#undef HAS_NESTED_TYPE_DETECTOR
#undef HAS_NESTED_TYPE
#endif // CWRAPPER_HPP_INCLUDED
<commit_msg>CRTP const this fixed<commit_after>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED
#define HAS_STATIC_MEMBER_DETECTOR(member) \
template<typename T> \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, decltype(U::member)* func = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_STATIC_MEMBER(type, member) \
(HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)
#define HAS_NESTED_TYPE_DETECTOR(member) \
template<typename T> \
class HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, typename U::member* ty = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_NESTED_TYPE(type, member) \
(HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member<type>::value)
namespace CW {
enum class CWrapperType
{
Implicit,
Explicit,
Get,
};
template<
typename H,
typename F,
CWrapperType TY = CWrapperType::Get,
bool C = true>
class CWrapperFriend
{
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ArrowHandler
{ };
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
PTR_T* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* operator->()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* operator->() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
CWrapperType TYPE,
bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
operator HANDLE_T() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
explicit operator HANDLE_T() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
HANDLE_T get() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
operator PTR_T const*() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
explicit operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
explicit operator PTR_T const*() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* get()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* get() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperBase
: public ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperBase(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
CWrapperBase(CWrapperBase const& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperBase(CWrapperBase& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
template<typename... ARGS>
explicit CWrapperBase(ARGS&&... args) :
CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperBase(CWrapperBase&& old) :
CWrapperBase{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperBase& operator=(CWrapperBase&& old)
{
if(this != &old)
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperBase()
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
}
CWrapperBase& operator=(CWrapperBase const& other)
{
if(this != &other)
{
HANDLE_T new_ptr = FUNCTIONS::copy_func(other.ptr);
if(!VALIDATE_T::validate_func(new_ptr))
throw typename EXCEPTION_T::exception{};
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = new_ptr;
}
return *this;
}
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperNonCopiable
: public ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperNonCopiable(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
template<typename... ARGS>
explicit CWrapperNonCopiable(ARGS&&... args) :
CWrapperNonCopiable{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperNonCopiable(CWrapperNonCopiable&& old) :
CWrapperNonCopiable{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperNonCopiable& operator=(CWrapperNonCopiable&& old)
{
if(this != &old)
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperNonCopiable()
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
}
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperNonCopiable(CWrapperNonCopiable& other) = delete;
CWrapperNonCopiable(CWrapperNonCopiable const& other) = delete;
CWrapperNonCopiable& operator=(CWrapperNonCopiable const& other) = delete;
};
template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
using type = TRUE_TYPE;
};
template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
using type = FALSE_TYPE;
};
HAS_NESTED_TYPE_DETECTOR(exception);
HAS_STATIC_MEMBER_DETECTOR(copy_func);
HAS_STATIC_MEMBER_DETECTOR(invalid_value);
HAS_STATIC_MEMBER_DETECTOR(validate_func);
struct default_exception_type
{
using exception = std::bad_alloc;
};
template<typename T>
struct default_invalid_value
{
static constexpr T invalid_value = 0;
};
template<typename T>
struct default_invalid_value<T*>
{
static constexpr T* invalid_value = nullptr;
};
template<typename T, typename INVALID_T>
struct default_validate_func
{
static constexpr bool validate_func(T ptr)
{
return ptr != INVALID_T::invalid_value;
}
};
using E = typename COND< HAS_NESTED_TYPE(F, exception),
F, default_exception_type>::type;
using D = typename COND< HAS_STATIC_MEMBER(F, invalid_value),
F, default_invalid_value<H>>::type;
using V = typename COND< HAS_STATIC_MEMBER(F, validate_func),
F, default_validate_func<H, D>>::type;
public:
using type = typename COND< HAS_STATIC_MEMBER(F, copy_func),
CWrapperBase<H, F, TY, C, E, D, V>,
CWrapperNonCopiable<H, F, TY, C, E, D, V>>::type;
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE = CWrapperType::Get,
bool CONSTSAFE = true>
using CWrapper = typename CWrapperFriend<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE>::type;
}
#undef HAS_STATIC_MEMBER_DETECTOR
#undef HAS_STATIC_MEMBER
#undef HAS_NESTED_TYPE_DETECTOR
#undef HAS_NESTED_TYPE
#endif // CWRAPPER_HPP_INCLUDED
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2016 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 "coins.h"
#include "memusage.h"
#include "random.h"
#include <cassert>
/**
* calculate number of bytes for the bitmask, and its number of non-zero bytes
* each bit in the bitmask represents the availability of one output, but the
* availabilities of the first two outputs are encoded separately
*/
void CCoins::CalcMaskSize(unsigned int &nBytes,
unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2 + b * 8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2 + b * 8 + i < vout.size(); i++) {
if (!vout[2 + b * 8 + i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool CCoins::Spend(uint32_t nPos) {
if (nPos >= vout.size() || vout[nPos].IsNull()) return false;
vout[nPos].SetNull();
Cleanup();
return true;
}
bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const {
return false;
}
bool CCoinsView::HaveCoins(const uint256 &txid) const {
return false;
}
uint256 CCoinsView::GetBestBlock() const {
return uint256();
}
bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
return false;
}
CCoinsViewCursor *CCoinsView::Cursor() const {
return 0;
}
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) {}
bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const {
return base->GetCoins(txid, coins);
}
bool CCoinsViewBacked::HaveCoins(const uint256 &txid) const {
return base->HaveCoins(txid);
}
uint256 CCoinsViewBacked::GetBestBlock() const {
return base->GetBestBlock();
}
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) {
base = &viewIn;
}
bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins,
const uint256 &hashBlock) {
return base->BatchWrite(mapCoins, hashBlock);
}
CCoinsViewCursor *CCoinsViewBacked::Cursor() const {
return base->Cursor();
}
SaltedTxidHasher::SaltedTxidHasher()
: k0(GetRand(std::numeric_limits<uint64_t>::max())),
k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn)
: CCoinsViewBacked(baseIn), hasModifier(false), cachedCoinsUsage(0) {}
CCoinsViewCache::~CCoinsViewCache() {
assert(!hasModifier);
}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::const_iterator
CCoinsViewCache::FetchCoins(const uint256 &txid) const {
CCoinsMap::iterator it = cacheCoins.find(txid);
if (it != cacheCoins.end()) return it;
CCoins tmp;
if (!base->GetCoins(txid, tmp)) return cacheCoins.end();
CCoinsMap::iterator ret =
cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
tmp.swap(ret->second.coins);
if (ret->second.coins.IsPruned()) {
// The parent only has an empty entry for this txid; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coins.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it != cacheCoins.end()) {
coins = it->second.coins;
return true;
}
return false;
}
CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret =
cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
size_t cachedCoinUsage = 0;
if (ret.second) {
if (!base->GetCoins(txid, ret.first->second.coins)) {
// The parent view does not have this entry; mark it as fresh.
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
} else if (ret.first->second.coins.IsPruned()) {
// The parent view only has a pruned entry for this; mark it as
// fresh.
ret.first->second.flags = CCoinsCacheEntry::FRESH;
}
} else {
cachedCoinUsage = ret.first->second.coins.DynamicMemoryUsage();
}
// Assume that whenever ModifyCoins is called, the entry will be modified.
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, cachedCoinUsage);
}
/* ModifyNewCoins allows for faster coin modification when creating the new
* outputs from a transaction. It assumes that BIP 30 (no duplicate txids)
* applies and has already been tested for (or the test is not required due to
* BIP 34, height in coinbase). If we can assume BIP 30 then we know that any
* non-coinbase transaction we are adding to the UTXO must not already exist in
* the utxo unless it is fully spent. Thus we can check only if it exists DIRTY
* at the current level of the cache, in which case it is not safe to mark it
* FRESH (b/c then its spentness still needs to flushed). If it's not dirty and
* doesn't exist or is pruned in the current cache, we know it either doesn't
* exist or is pruned in parent caches, which is the definition of FRESH. The
* exception to this is the two historical violations of BIP 30 in the chain,
* both of which were coinbases. We do not mark these fresh so we we can ensure
* that they will still be properly overwritten when spent.
*/
CCoinsModifier CCoinsViewCache::ModifyNewCoins(const uint256 &txid,
bool coinbase) {
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret =
cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
if (!coinbase) {
// New coins must not already exist.
if (!ret.first->second.coins.IsPruned())
throw std::logic_error("ModifyNewCoins should not find "
"pre-existing coins on a non-coinbase "
"unless they are pruned!");
if (!(ret.first->second.flags & CCoinsCacheEntry::DIRTY)) {
// If the coin is known to be pruned (have no unspent outputs) in
// the current view and the cache entry is not dirty, we know the
// coin also must be pruned in the parent view as well, so it is
// safe
// to mark this fresh.
ret.first->second.flags |= CCoinsCacheEntry::FRESH;
}
}
ret.first->second.coins.Clear();
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, 0);
}
const CCoins *CCoinsViewCache::AccessCoins(const uint256 &txid) const {
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it == cacheCoins.end()) {
return nullptr;
} else {
return &it->second.coins;
}
}
bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
CCoinsMap::const_iterator it = FetchCoins(txid);
// We're using vtx.empty() instead of IsPruned here for performance reasons,
// as we only care about the case where a transaction was replaced entirely
// in a reorganization (which wipes vout entirely, as opposed to spending
// which just cleans individual outputs).
return (it != cacheCoins.end() && !it->second.coins.vout.empty());
}
bool CCoinsViewCache::HaveCoinsInCache(const uint256 &txid) const {
CCoinsMap::const_iterator it = cacheCoins.find(txid);
return it != cacheCoins.end();
}
uint256 CCoinsViewCache::GetBestBlock() const {
if (hashBlock.IsNull()) hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins,
const uint256 &hashBlockIn) {
assert(!hasModifier);
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
// Ignore non-dirty entries (optimization).
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child does
// We can ignore it if it's both FRESH and pruned in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH &&
it->second.coins.IsPruned())) {
// Otherwise we will need to create it in the parent and
// move the data up and mark it as dirty
CCoinsCacheEntry &entry = cacheCoins[it->first];
entry.coins.swap(it->second.coins);
cachedCoinsUsage += entry.coins.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the
// child. Otherwise it might have just been flushed from the
// parent's cache and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH)
entry.flags |= CCoinsCacheEntry::FRESH;
}
} else {
// Assert that the child cache entry was not marked FRESH if the
// parent cache entry has unspent outputs. If this ever happens,
// it means the FRESH flag was misapplied and there is a logic
// error in the calling code.
if ((it->second.flags & CCoinsCacheEntry::FRESH) &&
!itUs->second.coins.IsPruned())
throw std::logic_error("FRESH flag misapplied to cache "
"entry for base transaction with "
"spendable outputs");
// Found the entry in the parent cache
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) &&
it->second.coins.IsPruned()) {
// The grandparent does not have an entry, and the child is
// modified and being pruned. This means we can just delete
// it from the parent.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
itUs->second.coins.swap(it->second.coins);
cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
// NOTE: It is possible the child has a FRESH flag here in
// the event the entry we found in the parent is pruned. But
// we must not copy that FRESH flag to the parent as that
// pruned state likely still needs to be communicated to the
// grandparent.
}
}
}
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, hashBlock);
cacheCoins.clear();
cachedCoinsUsage = 0;
return fOk;
}
void CCoinsViewCache::Uncache(const uint256 &hash) {
CCoinsMap::iterator it = cacheCoins.find(hash);
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coins.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
return cacheCoins.size();
}
const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn &input) const {
const CCoins *coins = AccessCoins(input.prevout.hash);
assert(coins && coins->IsAvailable(input.prevout.n));
return coins->vout[input.prevout.n];
}
CAmount CCoinsViewCache::GetValueIn(const CTransaction &tx) const {
if (tx.IsCoinBase()) return 0;
CAmount nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += GetOutputFor(tx.vin[i]).nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction &tx) const {
if (tx.IsCoinBase()) {
return true;
}
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins *coins = AccessCoins(prevout.hash);
if (!coins || !coins->IsAvailable(prevout.n)) {
return false;
}
}
return true;
}
double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight,
CAmount &inChainInputValue) const {
inChainInputValue = 0;
if (tx.IsCoinBase()) return 0.0;
double dResult = 0.0;
for (const CTxIn &txin : tx.vin) {
const CCoins *coins = AccessCoins(txin.prevout.hash);
assert(coins);
if (!coins->IsAvailable(txin.prevout.n)) continue;
if (coins->nHeight <= nHeight) {
dResult += (double)(coins->vout[txin.prevout.n].nValue) *
(nHeight - coins->nHeight);
inChainInputValue += coins->vout[txin.prevout.n].nValue;
}
}
return tx.ComputePriority(dResult);
}
CCoinsModifier::CCoinsModifier(CCoinsViewCache &cache_, CCoinsMap::iterator it_,
size_t usage)
: cache(cache_), it(it_), cachedCoinUsage(usage) {
assert(!cache.hasModifier);
cache.hasModifier = true;
}
CCoinsModifier::~CCoinsModifier() {
assert(cache.hasModifier);
cache.hasModifier = false;
it->second.coins.Cleanup();
// Subtract the old usage
cache.cachedCoinsUsage -= cachedCoinUsage;
if ((it->second.flags & CCoinsCacheEntry::FRESH) &&
it->second.coins.IsPruned()) {
cache.cacheCoins.erase(it);
} else {
// If the coin still exists after the modification, add the new usage
cache.cachedCoinsUsage += it->second.coins.DynamicMemoryUsage();
}
}
CCoinsViewCursor::~CCoinsViewCursor() {}
<commit_msg>Some formatting in coins.cpp<commit_after>// Copyright (c) 2012-2016 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 "coins.h"
#include "memusage.h"
#include "random.h"
#include <cassert>
/**
* calculate number of bytes for the bitmask, and its number of non-zero bytes
* each bit in the bitmask represents the availability of one output, but the
* availabilities of the first two outputs are encoded separately
*/
void CCoins::CalcMaskSize(unsigned int &nBytes,
unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2 + b * 8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2 + b * 8 + i < vout.size(); i++) {
if (!vout[2 + b * 8 + i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool CCoins::Spend(uint32_t nPos) {
if (nPos >= vout.size() || vout[nPos].IsNull()) return false;
vout[nPos].SetNull();
Cleanup();
return true;
}
bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const {
return false;
}
bool CCoinsView::HaveCoins(const uint256 &txid) const {
return false;
}
uint256 CCoinsView::GetBestBlock() const {
return uint256();
}
bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) {
return false;
}
CCoinsViewCursor *CCoinsView::Cursor() const {
return 0;
}
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) {}
bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const {
return base->GetCoins(txid, coins);
}
bool CCoinsViewBacked::HaveCoins(const uint256 &txid) const {
return base->HaveCoins(txid);
}
uint256 CCoinsViewBacked::GetBestBlock() const {
return base->GetBestBlock();
}
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) {
base = &viewIn;
}
bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins,
const uint256 &hashBlock) {
return base->BatchWrite(mapCoins, hashBlock);
}
CCoinsViewCursor *CCoinsViewBacked::Cursor() const {
return base->Cursor();
}
SaltedTxidHasher::SaltedTxidHasher()
: k0(GetRand(std::numeric_limits<uint64_t>::max())),
k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn)
: CCoinsViewBacked(baseIn), hasModifier(false), cachedCoinsUsage(0) {}
CCoinsViewCache::~CCoinsViewCache() {
assert(!hasModifier);
}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::const_iterator
CCoinsViewCache::FetchCoins(const uint256 &txid) const {
CCoinsMap::iterator it = cacheCoins.find(txid);
if (it != cacheCoins.end()) {
return it;
}
CCoins tmp;
if (!base->GetCoins(txid, tmp)) {
return cacheCoins.end();
}
CCoinsMap::iterator ret =
cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
tmp.swap(ret->second.coins);
if (ret->second.coins.IsPruned()) {
// The parent only has an empty entry for this txid; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coins.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it != cacheCoins.end()) {
coins = it->second.coins;
return true;
}
return false;
}
CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret =
cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
size_t cachedCoinUsage = 0;
if (ret.second) {
if (!base->GetCoins(txid, ret.first->second.coins)) {
// The parent view does not have this entry; mark it as fresh.
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
} else if (ret.first->second.coins.IsPruned()) {
// The parent view only has a pruned entry for this; mark it as
// fresh.
ret.first->second.flags = CCoinsCacheEntry::FRESH;
}
} else {
cachedCoinUsage = ret.first->second.coins.DynamicMemoryUsage();
}
// Assume that whenever ModifyCoins is called, the entry will be modified.
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, cachedCoinUsage);
}
/**
* ModifyNewCoins allows for faster coin modification when creating the new
* outputs from a transaction. It assumes that BIP 30 (no duplicate txids)
* applies and has already been tested for (or the test is not required due to
* BIP 34, height in coinbase). If we can assume BIP 30 then we know that any
* non-coinbase transaction we are adding to the UTXO must not already exist in
* the utxo unless it is fully spent. Thus we can check only if it exists DIRTY
* at the current level of the cache, in which case it is not safe to mark it
* FRESH (b/c then its spentness still needs to flushed). If it's not dirty and
* doesn't exist or is pruned in the current cache, we know it either doesn't
* exist or is pruned in parent caches, which is the definition of FRESH. The
* exception to this is the two historical violations of BIP 30 in the chain,
* both of which were coinbases. We do not mark these fresh so we we can ensure
* that they will still be properly overwritten when spent.
*/
CCoinsModifier CCoinsViewCache::ModifyNewCoins(const uint256 &txid,
bool coinbase) {
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret =
cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
if (!coinbase) {
// New coins must not already exist.
if (!ret.first->second.coins.IsPruned())
throw std::logic_error("ModifyNewCoins should not find "
"pre-existing coins on a non-coinbase "
"unless they are pruned!");
if (!(ret.first->second.flags & CCoinsCacheEntry::DIRTY)) {
// If the coin is known to be pruned (have no unspent outputs) in
// the current view and the cache entry is not dirty, we know the
// coin also must be pruned in the parent view as well, so it is
// safe to mark this fresh.
ret.first->second.flags |= CCoinsCacheEntry::FRESH;
}
}
ret.first->second.coins.Clear();
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, 0);
}
const CCoins *CCoinsViewCache::AccessCoins(const uint256 &txid) const {
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it == cacheCoins.end()) {
return nullptr;
} else {
return &it->second.coins;
}
}
bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
CCoinsMap::const_iterator it = FetchCoins(txid);
// We're using vtx.empty() instead of IsPruned here for performance reasons,
// as we only care about the case where a transaction was replaced entirely
// in a reorganization (which wipes vout entirely, as opposed to spending
// which just cleans individual outputs).
return (it != cacheCoins.end() && !it->second.coins.vout.empty());
}
bool CCoinsViewCache::HaveCoinsInCache(const uint256 &txid) const {
CCoinsMap::const_iterator it = cacheCoins.find(txid);
return it != cacheCoins.end();
}
uint256 CCoinsViewCache::GetBestBlock() const {
if (hashBlock.IsNull()) hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins,
const uint256 &hashBlockIn) {
assert(!hasModifier);
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
// Ignore non-dirty entries (optimization).
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child does
// We can ignore it if it's both FRESH and pruned in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH &&
it->second.coins.IsPruned())) {
// Otherwise we will need to create it in the parent and
// move the data up and mark it as dirty
CCoinsCacheEntry &entry = cacheCoins[it->first];
entry.coins.swap(it->second.coins);
cachedCoinsUsage += entry.coins.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the
// child. Otherwise it might have just been flushed from the
// parent's cache and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH)
entry.flags |= CCoinsCacheEntry::FRESH;
}
} else {
// Assert that the child cache entry was not marked FRESH if the
// parent cache entry has unspent outputs. If this ever happens,
// it means the FRESH flag was misapplied and there is a logic
// error in the calling code.
if ((it->second.flags & CCoinsCacheEntry::FRESH) &&
!itUs->second.coins.IsPruned())
throw std::logic_error("FRESH flag misapplied to cache "
"entry for base transaction with "
"spendable outputs");
// Found the entry in the parent cache
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) &&
it->second.coins.IsPruned()) {
// The grandparent does not have an entry, and the child is
// modified and being pruned. This means we can just delete
// it from the parent.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
itUs->second.coins.swap(it->second.coins);
cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
// NOTE: It is possible the child has a FRESH flag here in
// the event the entry we found in the parent is pruned. But
// we must not copy that FRESH flag to the parent as that
// pruned state likely still needs to be communicated to the
// grandparent.
}
}
}
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, hashBlock);
cacheCoins.clear();
cachedCoinsUsage = 0;
return fOk;
}
void CCoinsViewCache::Uncache(const uint256 &hash) {
CCoinsMap::iterator it = cacheCoins.find(hash);
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coins.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
return cacheCoins.size();
}
const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn &input) const {
const CCoins *coins = AccessCoins(input.prevout.hash);
assert(coins && coins->IsAvailable(input.prevout.n));
return coins->vout[input.prevout.n];
}
CAmount CCoinsViewCache::GetValueIn(const CTransaction &tx) const {
if (tx.IsCoinBase()) return 0;
CAmount nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += GetOutputFor(tx.vin[i]).nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction &tx) const {
if (tx.IsCoinBase()) {
return true;
}
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins *coins = AccessCoins(prevout.hash);
if (!coins || !coins->IsAvailable(prevout.n)) {
return false;
}
}
return true;
}
double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight,
CAmount &inChainInputValue) const {
inChainInputValue = 0;
if (tx.IsCoinBase()) return 0.0;
double dResult = 0.0;
for (const CTxIn &txin : tx.vin) {
const CCoins *coins = AccessCoins(txin.prevout.hash);
assert(coins);
if (!coins->IsAvailable(txin.prevout.n)) continue;
if (coins->nHeight <= nHeight) {
dResult += (double)(coins->vout[txin.prevout.n].nValue) *
(nHeight - coins->nHeight);
inChainInputValue += coins->vout[txin.prevout.n].nValue;
}
}
return tx.ComputePriority(dResult);
}
CCoinsModifier::CCoinsModifier(CCoinsViewCache &cache_, CCoinsMap::iterator it_,
size_t usage)
: cache(cache_), it(it_), cachedCoinUsage(usage) {
assert(!cache.hasModifier);
cache.hasModifier = true;
}
CCoinsModifier::~CCoinsModifier() {
assert(cache.hasModifier);
cache.hasModifier = false;
it->second.coins.Cleanup();
// Subtract the old usage
cache.cachedCoinsUsage -= cachedCoinUsage;
if ((it->second.flags & CCoinsCacheEntry::FRESH) &&
it->second.coins.IsPruned()) {
cache.cacheCoins.erase(it);
} else {
// If the coin still exists after the modification, add the new usage
cache.cachedCoinsUsage += it->second.coins.DynamicMemoryUsage();
}
}
CCoinsViewCursor::~CCoinsViewCursor() {}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2014 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coins.h"
#include "random.h"
#include <assert.h>
/**
* calculate number of bytes for the bitmask, and its number of non-zero bytes
* each bit in the bitmask represents the availability of one output, but the
* availabilities of the first two outputs are encoded separately
*/
void CCoins::CalcMaskSize(unsigned int& nBytes, unsigned int& nNonzeroBytes) const
{
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2 + b * 8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2 + b * 8 + i < vout.size(); i++) {
if (!vout[2 + b * 8 + i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool CCoins::Spend(const COutPoint& out, CTxInUndo& undo)
{
if (out.n >= vout.size())
return false;
if (vout[out.n].IsNull())
return false;
undo = CTxInUndo(vout[out.n]);
vout[out.n].SetNull();
Cleanup();
if (vout.size() == 0) {
undo.nHeight = nHeight;
undo.fCoinBase = fCoinBase;
undo.fCoinStake = fCoinStake;
undo.nVersion = this->nVersion;
}
return true;
}
bool CCoins::Spend(int nPos)
{
CTxInUndo undo;
COutPoint out(0, nPos);
return Spend(out, undo);
}
bool CCoinsView::GetCoins(const uint256& txid, CCoins& coins) const { return false; }
bool CCoinsView::HaveCoins(const uint256& txid) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(0); }
bool CCoinsView::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { return false; }
bool CCoinsView::GetStats(CCoinsStats& stats) const { return false; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView* viewIn) : base(viewIn) {}
bool CCoinsViewBacked::GetCoins(const uint256& txid, CCoins& coins) const { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(const uint256& txid) const { return base->HaveCoins(txid); }
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
void CCoinsViewBacked::SetBackend(CCoinsView& viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
bool CCoinsViewBacked::GetStats(CCoinsStats& stats) const { return base->GetStats(stats); }
CCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView* baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), hashBlock(0) {}
CCoinsViewCache::~CCoinsViewCache()
{
assert(!hasModifier);
}
CCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256& txid) const
{
CCoinsMap::iterator it = cacheCoins.find(txid);
if (it != cacheCoins.end())
return it;
CCoins tmp;
if (!base->GetCoins(txid, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
tmp.swap(ret->second.coins);
if (ret->second.coins.IsPruned()) {
// The parent only has an empty entry for this txid; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
return ret;
}
bool CCoinsViewCache::GetCoins(const uint256& txid, CCoins& coins) const
{
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it != cacheCoins.end()) {
coins = it->second.coins;
return true;
}
return false;
}
CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256& txid)
{
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
if (ret.second) {
if (!base->GetCoins(txid, ret.first->second.coins)) {
// The parent view does not have this entry; mark it as fresh.
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
} else if (ret.first->second.coins.IsPruned()) {
// The parent view only has a pruned entry for this; mark it as fresh.
ret.first->second.flags = CCoinsCacheEntry::FRESH;
}
}
// Assume that whenever ModifyCoins is called, the entry will be modified.
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first);
}
const CCoins* CCoinsViewCache::AccessCoins(const uint256& txid) const
{
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it == cacheCoins.end()) {
return NULL;
} else {
return &it->second.coins;
}
}
bool CCoinsViewCache::HaveCoins(const uint256& txid) const
{
CCoinsMap::const_iterator it = FetchCoins(txid);
// We're using vtx.empty() instead of IsPruned here for performance reasons,
// as we only care about the case where a transaction was replaced entirely
// in a reorganization (which wipes vout entirely, as opposed to spending
// which just cleans individual outputs).
return (it != cacheCoins.end() && !it->second.coins.vout.empty());
}
uint256 CCoinsViewCache::GetBestBlock() const
{
if (hashBlock == uint256(0))
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256& hashBlockIn)
{
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlockIn)
{
assert(!hasModifier);
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
if (!it->second.coins.IsPruned()) {
// The parent cache does not have an entry, while the child
// cache does have (a non-pruned) one. Move the data up, and
// mark it as fresh (if the grandparent did have it, we
// would have pulled it in at first GetCoins).
assert(it->second.flags & CCoinsCacheEntry::FRESH);
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coins.swap(it->second.coins);
entry.flags = CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH;
}
} else {
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
// The grandparent does not have an entry, and the child is
// modified and being pruned. This means we can just delete
// it from the parent.
cacheCoins.erase(itUs);
} else {
// A normal modification.
itUs->second.coins.swap(it->second.coins);
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
}
}
}
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush()
{
bool fOk = base->BatchWrite(cacheCoins, hashBlock);
cacheCoins.clear();
return fOk;
}
unsigned int CCoinsViewCache::GetCacheSize() const
{
return cacheCoins.size();
}
const CTxOut& CCoinsViewCache::GetOutputFor(const CTxIn& input) const
{
const CCoins* coins = AccessCoins(input.prevout.hash);
assert(coins && coins->IsAvailable(input.prevout.n));
return coins->vout[input.prevout.n];
}
CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
{
if (tx.IsCoinBase())
return 0;
//todo are there any security precautions to take here?
if (tx.HasZerocoinSpendInputs())
return tx.GetZerocoinSpent();
CAmount nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += GetOutputFor(tx.vin[i]).nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
if (!tx.IsCoinBase() && !tx.HasZerocoinSpendInputs()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint& prevout = tx.vin[i].prevout;
const CCoins* coins = AccessCoins(prevout.hash);
if (!coins || !coins->IsAvailable(prevout.n)) {
return false;
}
}
}
return true;
}
bool CCoinsViewCache::IsOutputAvailable(const uint256& txId, int index) {
const CCoins* coins = AccessCoins(txId);
return !coins || !coins->IsAvailable(index);
}
double CCoinsViewCache::GetPriority(const CTransaction& tx, int nHeight) const
{
if (tx.IsCoinBase() || tx.IsCoinStake())
return 0.0;
double dResult = 0.0;
for (const CTxIn& txin : tx.vin) {
const CCoins* coins = AccessCoins(txin.prevout.hash);
assert(coins);
if (!coins->IsAvailable(txin.prevout.n)) continue;
if (coins->nHeight < nHeight) {
dResult += coins->vout[txin.prevout.n].nValue * (nHeight - coins->nHeight);
}
}
return tx.ComputePriority(dResult);
}
CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_) : cache(cache_), it(it_)
{
assert(!cache.hasModifier);
cache.hasModifier = true;
}
CCoinsModifier::~CCoinsModifier()
{
assert(cache.hasModifier);
cache.hasModifier = false;
it->second.coins.Cleanup();
if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
cache.cacheCoins.erase(it);
}
}
<commit_msg>[Coins] IsOutputAvailable badly checking if the output is available fix (was checking if the output is not available).<commit_after>// Copyright (c) 2012-2014 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coins.h"
#include "random.h"
#include <assert.h>
/**
* calculate number of bytes for the bitmask, and its number of non-zero bytes
* each bit in the bitmask represents the availability of one output, but the
* availabilities of the first two outputs are encoded separately
*/
void CCoins::CalcMaskSize(unsigned int& nBytes, unsigned int& nNonzeroBytes) const
{
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2 + b * 8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2 + b * 8 + i < vout.size(); i++) {
if (!vout[2 + b * 8 + i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool CCoins::Spend(const COutPoint& out, CTxInUndo& undo)
{
if (out.n >= vout.size())
return false;
if (vout[out.n].IsNull())
return false;
undo = CTxInUndo(vout[out.n]);
vout[out.n].SetNull();
Cleanup();
if (vout.size() == 0) {
undo.nHeight = nHeight;
undo.fCoinBase = fCoinBase;
undo.fCoinStake = fCoinStake;
undo.nVersion = this->nVersion;
}
return true;
}
bool CCoins::Spend(int nPos)
{
CTxInUndo undo;
COutPoint out(0, nPos);
return Spend(out, undo);
}
bool CCoinsView::GetCoins(const uint256& txid, CCoins& coins) const { return false; }
bool CCoinsView::HaveCoins(const uint256& txid) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(0); }
bool CCoinsView::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { return false; }
bool CCoinsView::GetStats(CCoinsStats& stats) const { return false; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView* viewIn) : base(viewIn) {}
bool CCoinsViewBacked::GetCoins(const uint256& txid, CCoins& coins) const { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(const uint256& txid) const { return base->HaveCoins(txid); }
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
void CCoinsViewBacked::SetBackend(CCoinsView& viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
bool CCoinsViewBacked::GetStats(CCoinsStats& stats) const { return base->GetStats(stats); }
CCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView* baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), hashBlock(0) {}
CCoinsViewCache::~CCoinsViewCache()
{
assert(!hasModifier);
}
CCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256& txid) const
{
CCoinsMap::iterator it = cacheCoins.find(txid);
if (it != cacheCoins.end())
return it;
CCoins tmp;
if (!base->GetCoins(txid, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
tmp.swap(ret->second.coins);
if (ret->second.coins.IsPruned()) {
// The parent only has an empty entry for this txid; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
return ret;
}
bool CCoinsViewCache::GetCoins(const uint256& txid, CCoins& coins) const
{
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it != cacheCoins.end()) {
coins = it->second.coins;
return true;
}
return false;
}
CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256& txid)
{
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
if (ret.second) {
if (!base->GetCoins(txid, ret.first->second.coins)) {
// The parent view does not have this entry; mark it as fresh.
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
} else if (ret.first->second.coins.IsPruned()) {
// The parent view only has a pruned entry for this; mark it as fresh.
ret.first->second.flags = CCoinsCacheEntry::FRESH;
}
}
// Assume that whenever ModifyCoins is called, the entry will be modified.
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first);
}
const CCoins* CCoinsViewCache::AccessCoins(const uint256& txid) const
{
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it == cacheCoins.end()) {
return NULL;
} else {
return &it->second.coins;
}
}
bool CCoinsViewCache::HaveCoins(const uint256& txid) const
{
CCoinsMap::const_iterator it = FetchCoins(txid);
// We're using vtx.empty() instead of IsPruned here for performance reasons,
// as we only care about the case where a transaction was replaced entirely
// in a reorganization (which wipes vout entirely, as opposed to spending
// which just cleans individual outputs).
return (it != cacheCoins.end() && !it->second.coins.vout.empty());
}
uint256 CCoinsViewCache::GetBestBlock() const
{
if (hashBlock == uint256(0))
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256& hashBlockIn)
{
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlockIn)
{
assert(!hasModifier);
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
if (!it->second.coins.IsPruned()) {
// The parent cache does not have an entry, while the child
// cache does have (a non-pruned) one. Move the data up, and
// mark it as fresh (if the grandparent did have it, we
// would have pulled it in at first GetCoins).
assert(it->second.flags & CCoinsCacheEntry::FRESH);
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coins.swap(it->second.coins);
entry.flags = CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH;
}
} else {
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
// The grandparent does not have an entry, and the child is
// modified and being pruned. This means we can just delete
// it from the parent.
cacheCoins.erase(itUs);
} else {
// A normal modification.
itUs->second.coins.swap(it->second.coins);
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
}
}
}
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush()
{
bool fOk = base->BatchWrite(cacheCoins, hashBlock);
cacheCoins.clear();
return fOk;
}
unsigned int CCoinsViewCache::GetCacheSize() const
{
return cacheCoins.size();
}
const CTxOut& CCoinsViewCache::GetOutputFor(const CTxIn& input) const
{
const CCoins* coins = AccessCoins(input.prevout.hash);
assert(coins && coins->IsAvailable(input.prevout.n));
return coins->vout[input.prevout.n];
}
CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
{
if (tx.IsCoinBase())
return 0;
//todo are there any security precautions to take here?
if (tx.HasZerocoinSpendInputs())
return tx.GetZerocoinSpent();
CAmount nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += GetOutputFor(tx.vin[i]).nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
if (!tx.IsCoinBase() && !tx.HasZerocoinSpendInputs()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint& prevout = tx.vin[i].prevout;
const CCoins* coins = AccessCoins(prevout.hash);
if (!coins || !coins->IsAvailable(prevout.n)) {
return false;
}
}
}
return true;
}
bool CCoinsViewCache::IsOutputAvailable(const uint256& txId, int index) {
const CCoins* coins = AccessCoins(txId);
return coins && coins->IsAvailable(index);
}
double CCoinsViewCache::GetPriority(const CTransaction& tx, int nHeight) const
{
if (tx.IsCoinBase() || tx.IsCoinStake())
return 0.0;
double dResult = 0.0;
for (const CTxIn& txin : tx.vin) {
const CCoins* coins = AccessCoins(txin.prevout.hash);
assert(coins);
if (!coins->IsAvailable(txin.prevout.n)) continue;
if (coins->nHeight < nHeight) {
dResult += coins->vout[txin.prevout.n].nValue * (nHeight - coins->nHeight);
}
}
return tx.ComputePriority(dResult);
}
CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_) : cache(cache_), it(it_)
{
assert(!cache.hasModifier);
cache.hasModifier = true;
}
CCoinsModifier::~CCoinsModifier()
{
assert(cache.hasModifier);
cache.hasModifier = false;
it->second.coins.Cleanup();
if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
cache.cacheCoins.erase(it);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2010 Telmo Menezes.
* telmo@telmomenezes.com
*/
#include "drmap.h"
#include "utils.h"
#include "emd_hat_signatures_interface.hpp"
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
namespace syn
{
DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor,
double min_val_ver, double max_val_ver)
{
this->bin_number = bin_number;
this->min_val_hor = min_val_hor;
this->max_val_hor = max_val_hor;
this->min_val_ver = min_val_ver;
this->max_val_ver = max_val_ver;
data = (double*)malloc(bin_number * bin_number * sizeof(double));
clear();
}
DRMap::~DRMap()
{
free(data);
}
void DRMap::clear()
{
bzero(data, bin_number * bin_number * sizeof(double));
}
void DRMap::set_value(unsigned int x, unsigned int y, double val)
{
data[(y * bin_number) + x] = val;
}
void DRMap::inc_value(unsigned int x, unsigned int y)
{
data[(y * bin_number) + x] += 1;
}
double DRMap::get_value(unsigned int x, unsigned int y)
{
return data[(y * bin_number) + x];
}
void DRMap::log_scale()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = log(data[(y * bin_number) + x]);
}
}
}
}
void DRMap::normalize()
{
double = total();
if (total <= 0) {
return;
}
// normalize by total
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
data[(y * bin_number) + x] = data[(y * bin_number) + x] / total;
}
}
}
void DRMap::binary()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = 1;
}
}
}
}
double DRMap::total()
{
double total = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
total += data[(y * bin_number) + x];
}
}
return total;
}
double DRMap::simple_dist(DRMap* map)
{
double dist = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]);
}
}
return dist;
}
double ground_dist(feature_tt* feature1, feature_tt* feature2)
{
double deltaX = feature1->x - feature2->x;
double deltaY = feature1->y - feature2->y;
double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY));
//double dist = (deltaX * deltaX) + (deltaY * deltaY);
return dist;
}
signature_tt* get_emd_signature(DRMap* map)
{
unsigned int n = 0;
unsigned int bin_number = map->get_bin_number();
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if (map->get_value(x, y) > 0) {
n++;
}
}
}
feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n);
double* weights = (double*)malloc(sizeof(double) * n);
unsigned int i = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
double val = map->get_value(x, y);
if (val > 0) {
features[i].x = x;
features[i].y = y;
weights[i] = val;
i++;
}
}
}
signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt));
signature->n = n;
signature->Features = features;
signature->Weights = weights;
return signature;
}
double DRMap::emd_dist(DRMap* map)
{
printf("totals-> %f; %f\n", total(), map->total());
double infinity = 9999999999.9;
if (total() <= 0) {
return infinity;
}
if (map->total() <= 0) {
return infinity;
}
signature_tt* sig1 = get_emd_signature(this);
signature_tt* sig2 = get_emd_signature(map);
double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1);
free(sig1->Features);
free(sig1->Weights);
free(sig1);
free(sig2->Features);
free(sig2->Weights);
free(sig2);
return dist;
}
void DRMap::print()
{
for (unsigned int y = 0; y < bin_number; y++) {
for (unsigned int x = 0; x < bin_number; x++) {
printf("%f\t", get_value(x, y));
}
printf("\n");
}
}
}
<commit_msg>tweaking DRMap::normalize()<commit_after>/*
* Copyright (C) 2010 Telmo Menezes.
* telmo@telmomenezes.com
*/
#include "drmap.h"
#include "utils.h"
#include "emd_hat_signatures_interface.hpp"
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
namespace syn
{
DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor,
double min_val_ver, double max_val_ver)
{
this->bin_number = bin_number;
this->min_val_hor = min_val_hor;
this->max_val_hor = max_val_hor;
this->min_val_ver = min_val_ver;
this->max_val_ver = max_val_ver;
data = (double*)malloc(bin_number * bin_number * sizeof(double));
clear();
}
DRMap::~DRMap()
{
free(data);
}
void DRMap::clear()
{
bzero(data, bin_number * bin_number * sizeof(double));
}
void DRMap::set_value(unsigned int x, unsigned int y, double val)
{
data[(y * bin_number) + x] = val;
}
void DRMap::inc_value(unsigned int x, unsigned int y)
{
data[(y * bin_number) + x] += 1;
}
double DRMap::get_value(unsigned int x, unsigned int y)
{
return data[(y * bin_number) + x];
}
void DRMap::log_scale()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = log(data[(y * bin_number) + x]);
}
}
}
}
void DRMap::normalize()
{
double t = total();
if (t <= 0) {
return;
}
// normalize by total
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
data[(y * bin_number) + x] = data[(y * bin_number) + x] / t;
}
}
}
void DRMap::binary()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = 1;
}
}
}
}
double DRMap::total()
{
double total = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
total += data[(y * bin_number) + x];
}
}
return total;
}
double DRMap::simple_dist(DRMap* map)
{
double dist = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]);
}
}
return dist;
}
double ground_dist(feature_tt* feature1, feature_tt* feature2)
{
double deltaX = feature1->x - feature2->x;
double deltaY = feature1->y - feature2->y;
double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY));
//double dist = (deltaX * deltaX) + (deltaY * deltaY);
return dist;
}
signature_tt* get_emd_signature(DRMap* map)
{
unsigned int n = 0;
unsigned int bin_number = map->get_bin_number();
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if (map->get_value(x, y) > 0) {
n++;
}
}
}
feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n);
double* weights = (double*)malloc(sizeof(double) * n);
unsigned int i = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
double val = map->get_value(x, y);
if (val > 0) {
features[i].x = x;
features[i].y = y;
weights[i] = val;
i++;
}
}
}
signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt));
signature->n = n;
signature->Features = features;
signature->Weights = weights;
return signature;
}
double DRMap::emd_dist(DRMap* map)
{
printf("totals-> %f; %f\n", total(), map->total());
double infinity = 9999999999.9;
if (total() <= 0) {
return infinity;
}
if (map->total() <= 0) {
return infinity;
}
signature_tt* sig1 = get_emd_signature(this);
signature_tt* sig2 = get_emd_signature(map);
double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1);
free(sig1->Features);
free(sig1->Weights);
free(sig1);
free(sig2->Features);
free(sig2->Weights);
free(sig2);
return dist;
}
void DRMap::print()
{
for (unsigned int y = 0; y < bin_number; y++) {
for (unsigned int x = 0; x < bin_number; x++) {
printf("%f\t", get_value(x, y));
}
printf("\n");
}
}
}
<|endoftext|>
|
<commit_before>#include "QDMEwald.hpp"
#include <iostream>
#include <vector>
int main() {
Kokkos::initialize();
{
// testing system size
constexpr int cry_l = 16;
constexpr int N = cry_l * cry_l * cry_l;
constexpr double l = (double)cry_l / 2.0;
// testing particle positions
std::vector<double> xyz(3 * N);
// testing charges
std::vector<double> q(N);
// testing dipole momenta
std::vector<double> d(3 * N);
std::vector<double> Q(9 * N);
for (int i = 0; i < N; ++i) {
xyz.at(3 * i + 0) = (double)(i % cry_l) * 0.5;
xyz.at(3 * i + 1) = (double)((i % (cry_l * cry_l)) / cry_l) * 0.5;
xyz.at(3 * i + 2) = (double)(i / (cry_l * cry_l)) * 0.5;
q.at(i) = -1 + (double)(i % 2) * 2.0;
}
for (auto i : d) i = 0.0;
for (auto i : Q) i = 0.0;
double alpha = 2.6;
double r_max = 3.4;
double k_max = 9.7;
// testing the initialization with different data types
QDMEwald<double> qdme_d(alpha, k_max, r_max, l);
QDMEwald<float> qdme_f((float)alpha, (float)k_max, (float)r_max, (float)l);
QDMEwald<long double> qdme_ld((long double)alpha, (long double)k_max,
(long double)r_max, (long double)l);
qdme_d.compute(xyz, q, d, Q);
std::cout << qdme_d.get_energy() << std::endl;
}
Kokkos::finalize();
}
<commit_msg>changed testing parameters<commit_after>#include "QDMEwald.hpp"
#include <iostream>
#include <vector>
int main() {
Kokkos::initialize();
{
// testing system size
constexpr int cry_l = 8;
constexpr int N = cry_l * cry_l * cry_l;
constexpr double l = (double)cry_l / 2.0;
// testing particle positions
std::vector<double> xyz(3 * N);
// testing charges
std::vector<double> q(N);
// testing dipole momenta
std::vector<double> d(3 * N);
std::vector<double> Q(9 * N);
for (int i = 0; i < N; ++i) {
xyz.at(3 * i + 0) = (double)(i % cry_l) * 0.5;
xyz.at(3 * i + 1) = (double)((i % (cry_l * cry_l)) / cry_l) * 0.5;
xyz.at(3 * i + 2) = (double)(i / (cry_l * cry_l)) * 0.5;
q.at(i) = -1 + (double)(i % 2) * 2.0;
std::cout << i << ": " << xyz.at(3 * i + 0) << " " << xyz.at(3 * i + 1)
<< " " << xyz.at(3 * i + 2) << " " << q.at(i) << " "
<< std::endl;
}
for (auto i : d) i = 0.0;
for (auto i : Q) i = 0.0;
double alpha = 1.46010226038;
double r_max = 3.11778257707;
double k_max = 13.2935926895;
// testing the initialization with different data types
QDMEwald<double> qdme_d(alpha, k_max, r_max, l);
QDMEwald<float> qdme_f((float)alpha, (float)k_max, (float)r_max, (float)l);
QDMEwald<long double> qdme_ld((long double)alpha, (long double)k_max,
(long double)r_max, (long double)l);
qdme_d.compute(xyz, q, d, Q);
std::cout << qdme_d.get_energy() << std::endl;
}
Kokkos::finalize();
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 <algorithm>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#include <boost/bind.hpp>
#include <boost/next_prior.hpp>
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
assert(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
entry::entry(const dictionary_type& v)
{
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(const string_type& v)
{
new(data) string_type(v);
m_type = string_t;
}
entry::entry(const list_type& v)
{
new(data) list_type(v);
m_type = list_t;
}
entry::entry(const integer_type& v)
{
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(const dictionary_type& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
}
void entry::operator=(const string_type& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
}
void entry::operator=(const list_type& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
}
void entry::operator=(const integer_type& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
assert(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
m_type = t;
switch(m_type)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
assert(m_type == undefined_t);
m_type = undefined_t;
}
}
void entry::copy(const entry& e)
{
m_type = e.m_type;
switch(m_type)
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
m_type = undefined_t;
}
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
assert(m_type == undefined_t);
break;
}
}
void entry::print(std::ostream& os, int indent) const
{
assert(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<commit_msg>fixed entry::print() to work correctly with binary strings<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 <algorithm>
#include <iomanip>
#include "libtorrent/entry.hpp"
#include "libtorrent/config.hpp"
#include <boost/bind.hpp>
#include <boost/next_prior.hpp>
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
assert(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
entry::entry(const dictionary_type& v)
{
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(const string_type& v)
{
new(data) string_type(v);
m_type = string_t;
}
entry::entry(const list_type& v)
{
new(data) list_type(v);
m_type = list_t;
}
entry::entry(const integer_type& v)
{
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(const dictionary_type& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
}
void entry::operator=(const string_type& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
}
void entry::operator=(const list_type& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
}
void entry::operator=(const integer_type& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
assert(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
m_type = t;
switch(m_type)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
assert(m_type == undefined_t);
m_type = undefined_t;
}
}
void entry::copy(const entry& e)
{
m_type = e.m_type;
switch(m_type)
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
m_type = undefined_t;
}
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
assert(m_type == undefined_t);
break;
}
}
void entry::print(std::ostream& os, int indent) const
{
assert(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << std::setfill('0') << std::setw(2)
<< static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<|endoftext|>
|
<commit_before>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz)
: max(nsz) {
mem = std::malloc(nsz);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = (char*)allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = (char*)mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(lifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = (char*) allocstart;
endpt = (char*) allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = (char*) allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prev_alloc = sz;
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(void* pt) {
/*if we can't deallocate, just ignore*/
if(pt != lifoallocpt) return;
size_t sz = ((Generic*) pt)->real_size();
((Generic*) pt)->~Generic();
char* clifoallocpt = (char*) pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g) const {
/*TODO*/
}
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
void Heap::cheney_collection(Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
scan_root_object(&gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = (char*) nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(&gc);
mvpt += obsz;
}
}
void Heap::GC(size_t insurance) {
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance;
total +=
(other_spaces) ? other_spaces->used_total() :
/*otherwise*/ 0 ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(&*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<commit_msg>src/heaps.cpp: Added debug dumping code<commit_after>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz)
: max(nsz) {
mem = std::malloc(nsz);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = (char*)allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = (char*)mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(lifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = (char*) allocstart;
endpt = (char*) allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = (char*) allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = (char*) allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prev_alloc = sz;
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(void* pt) {
/*if we can't deallocate, just ignore*/
if(pt != lifoallocpt) return;
size_t sz = ((Generic*) pt)->real_size();
((Generic*) pt)->~Generic();
char* clifoallocpt = (char*) pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g) const {
/*TODO*/
}
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
void Heap::cheney_collection(Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
scan_root_object(&gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = (char*) nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(&gc);
mvpt += obsz;
}
}
#ifdef DEBUG
#include<iostream>
#endif
void Heap::GC(size_t insurance) {
#ifdef DEBUG
std::cout << "GC!" << std::endl;
#endif
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance;
total +=
(other_spaces) ? other_spaces->used_total() :
/*otherwise*/ 0 ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(&*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright 2016 Nervana Systems Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <cmath>
#include "block.hpp"
using namespace nervana;
std::vector<block_info> nervana::generate_block_list(size_t record_count, size_t block_size)
{
size_t block_count = round((float)record_count / (float)block_size);
block_count = std::max<size_t>(block_count, 1);
block_size = ceil((float)record_count / (float)block_count);
std::vector<block_info> rc;
for (size_t block = 0; block < block_count; block++)
{
size_t sequence_start = block_size * block;
size_t sequence_count = block_size;
if (sequence_start + sequence_count > record_count)
{
sequence_count -= sequence_start + sequence_count - record_count;
}
rc.emplace_back(sequence_start, sequence_count);
}
return rc;
}
<commit_msg>Fixed calculating sequence sizes for blocks smaller than block size<commit_after>/*
Copyright 2016 Nervana Systems Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <cmath>
#include "block.hpp"
using namespace nervana;
std::vector<block_info> nervana::generate_block_list(size_t record_count, size_t block_size)
{
size_t block_count = round((float)record_count / (float)block_size);
block_count = std::max<size_t>(block_count, 1);
block_size = ceil((float)record_count / (float)block_count);
std::vector<block_info> rc;
for (size_t block = 0; block < block_count; block++)
{
size_t sequence_start = block_size * block;
size_t sequence_count = block_size;
if (sequence_start + sequence_count > record_count)
{
sequence_count = record_count - sequence_start;
rc.emplace_back(sequence_start, sequence_count);
break;
}
rc.emplace_back(sequence_start, sequence_count);
}
return rc;
}
<|endoftext|>
|
<commit_before>#ifndef RETRIEVER_CACHE_HPP
#define RETRIEVER_CACHE_HPP
#include "list.hpp"
#include <memory>
#include <shared_mutex>
#include <unordered_map>
template <typename K, typename V> class CacheItem : public Item {
public:
CacheItem(K k, V v) : key(k), value(v){};
K key;
V value;
};
template <typename K, typename V> class Cache {
public:
explicit Cache(const int capacity) : capacity(capacity) {
lookUpTable =
std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>>(capacity);
};
void set(const K key, const V value) {
std::unique_lock<std::shared_mutex> lock(tableSMutex);
auto mapIt = lookUpTable.find(key);
if (mapIt == lookUpTable.end()) {
std::unique_ptr<CacheItem<K, V>> item(new CacheItem<K, V>(key, value));
if (lookUpTable.size() == capacity) {
auto toRemove = kList.back;
kList.remove(toRemove);
lookUpTable.erase(
lookUpTable.find(dynamic_cast<CacheItem<K, V> *>(toRemove)->key));
}
kList.pushFront(dynamic_cast<Item *>(item.get()));
} else {
auto item = mapIt->second;
item->value = value;
kList.moveToFront(dynamic_cast<Item *>(item.get()));
}
};
V get(const K key) {
std::shared_lock<std::shared_mutex> lock(tableSMutex);
auto mapIt = lookUpTable.find(key);
if (mapIt == lookUpTable.end()) {
return V();
}
kList.moveToFront(dynamic_cast<Item *>(mapIt->second->get()));
return mapIt->second->value;
};
private:
Cache(){};
int capacity;
std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>> lookUpTable;
std::shared_mutex tableSMutex;
List kList;
};
#endif
<commit_msg>fix: transfer unordered map parameter<commit_after>#ifndef RETRIEVER_CACHE_HPP
#define RETRIEVER_CACHE_HPP
#include "list.hpp"
#include <memory>
#include <shared_mutex>
#include <unordered_map>
template <typename K, typename V> class CacheItem : public Item {
public:
CacheItem(K k, V v) : key(k), value(v){};
K key;
V value;
};
template <typename K, typename V, class Hash = std::hash<K>,
class KeyEqual = std::equal_to<K>,
class Allocator = std::allocator<std::pair<const K, V>>>
class Cache {
public:
explicit Cache(const int capacity) : capacity(capacity) {
lookUpTable = std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>, Hash,
KeyEqual, Allocator>(capacity);
};
void set(const K key, const V value) {
std::unique_lock<std::shared_mutex> lock(tableSMutex);
auto mapIt = lookUpTable.find(key);
if (mapIt == lookUpTable.end()) {
std::unique_ptr<CacheItem<K, V>> item(new CacheItem<K, V>(key, value));
if (lookUpTable.size() == capacity) {
auto toRemove = kList.back;
kList.remove(toRemove);
lookUpTable.erase(
lookUpTable.find(dynamic_cast<CacheItem<K, V> *>(toRemove)->key));
}
kList.pushFront(dynamic_cast<Item *>(item.get()));
} else {
auto item = mapIt->second;
item->value = value;
kList.moveToFront(dynamic_cast<Item *>(item.get()));
}
};
V get(const K key) {
std::shared_lock<std::shared_mutex> lock(tableSMutex);
auto mapIt = lookUpTable.find(key);
if (mapIt == lookUpTable.end()) {
return V();
}
kList.moveToFront(dynamic_cast<Item *>(mapIt->second->get()));
return mapIt->second->value;
};
private:
Cache(){};
int capacity;
std::unordered_map<K, std::unique_ptr<CacheItem<K, V>>, Hash, KeyEqual,
Allocator>
lookUpTable;
std::shared_mutex tableSMutex;
List kList;
};
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2007-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2011-2017 The Litecoin Core developers
// Copyright (c) 2013-2018 The Goldcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex == NULL) {
return NULL;
}
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const
{
std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime,
[](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; });
return (lower == vChain.end() ? NULL : *lower);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height) {
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != NULL &&
(heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height)))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
assert(pindexWalk->pprev);
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * r.GetLow64();
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, const Consensus::Params & params, unsigned int nRequired)
{
unsigned int nToCheck = params.nToCheckBlockUpgradeMajority;
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
<commit_msg>Update chain.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2011-2017 The Litecoin Core developers
// Copyright (c) 2013-2023 The Goldcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex == NULL) {
return NULL;
}
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const
{
std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime,
[](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; });
return (lower == vChain.end() ? NULL : *lower);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height) {
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != NULL &&
(heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height)))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
assert(pindexWalk->pprev);
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * r.GetLow64();
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, const Consensus::Params & params, unsigned int nRequired)
{
unsigned int nToCheck = params.nToCheckBlockUpgradeMajority;
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
<|endoftext|>
|
<commit_before>/*
* Tyrion
* Copyright 2010, Silas Sewell
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <csignal>
#include <pthread.h>
#include "client_loop.h"
#include "client_request.h"
#include "client_settings.h"
#include "client_utils.h"
#ifdef _DEBUG
#include <txmpp/logging.h>
#endif
int main(int argc, char* argv[]) {
#ifdef _DEBUG
txmpp::LogMessage::LogToDebug(txmpp::LS_SENSITIVE);
#endif
int code = 0;
int sig;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
pthread_sigmask(SIG_BLOCK, &set, NULL);
tyrion::ClientRequest request;
tyrion::Logging::Instance()->Debug(tyrion::Logging::WARNING);
tyrion::ClientSetup(argc, argv, &request);
tyrion::ClientLoop* loop = tyrion::ClientLoop::Instance();
loop->Start();
loop->Login();
while (true) {
sigwait(&set, &sig);
if (sig == SIGHUP) {
loop->Reload();
} else if (sig == SIGINT || sig == SIGTERM) {
if (loop->state() == tyrion::ClientLoop::ERROR) code = 1;
loop->Disconnect();
loop->Quit();
loop->Stop();
break;
}
}
delete loop;
tyrion::ClientExit(0);
}
<commit_msg>No reloading in client<commit_after>/*
* Tyrion
* Copyright 2010, Silas Sewell
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <csignal>
#include <pthread.h>
#include "client_loop.h"
#include "client_request.h"
#include "client_settings.h"
#include "client_utils.h"
#ifdef _DEBUG
#include <txmpp/logging.h>
#endif
int main(int argc, char* argv[]) {
#ifdef _DEBUG
txmpp::LogMessage::LogToDebug(txmpp::LS_SENSITIVE);
#endif
int code = 0;
int sig;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
pthread_sigmask(SIG_BLOCK, &set, NULL);
tyrion::ClientRequest request;
tyrion::Logging::Instance()->Debug(tyrion::Logging::WARNING);
tyrion::ClientSetup(argc, argv, &request);
tyrion::ClientLoop* loop = tyrion::ClientLoop::Instance();
loop->Start();
loop->Login();
while (true) {
sigwait(&set, &sig);
if (sig == SIGHUP || sig == SIGINT || sig == SIGTERM) {
if (loop->state() == tyrion::ClientLoop::ERROR) code = 1;
loop->Disconnect();
loop->Quit();
loop->Stop();
break;
}
}
delete loop;
tyrion::ClientExit(0);
}
<|endoftext|>
|
<commit_before>#ifndef client_hh_INCLUDED
#define client_hh_INCLUDED
#include "display_buffer.hh"
#include "env_vars.hh"
#include "input_handler.hh"
#include "safe_ptr.hh"
#include "utils.hh"
#include "option_manager.hh"
#include "enum.hh"
namespace Kakoune
{
class Window;
class UserInterface;
class String;
struct Key;
enum class EventMode;
enum class InfoStyle;
enum class MenuStyle;
class Client : public SafeCountable, public OptionManagerWatcher
{
public:
Client(std::unique_ptr<UserInterface>&& ui,
std::unique_ptr<Window>&& window,
SelectionList selections,
EnvVarMap env_vars,
String name);
~Client() override;
Client(Client&&) = delete;
bool process_pending_inputs();
void menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style);
void menu_select(int selected);
void menu_hide();
void info_show(String title, String content, BufferCoord anchor, InfoStyle style);
void info_hide(bool even_modal = false);
void print_status(DisplayLine status_line, bool immediate = false);
DisplayCoord dimensions() const;
void force_redraw();
void redraw_ifn();
void check_if_buffer_needs_reloading();
Context& context() { return m_input_handler.context(); }
const Context& context() const { return m_input_handler.context(); }
InputHandler& input_handler() { return m_input_handler; }
const InputHandler& input_handler() const { return m_input_handler; }
void change_buffer(Buffer& buffer);
StringView get_env_var(StringView name) const;
Buffer* last_buffer() const { return m_last_buffer.get(); }
void set_last_buffer(Buffer* last_buffer) { m_last_buffer = last_buffer; }
private:
void on_option_changed(const Option& option) override;
void on_buffer_reload_key(Key key);
void close_buffer_reload_dialog();
void reload_buffer();
Optional<Key> get_next_key(EventMode mode);
DisplayLine generate_mode_line() const;
std::unique_ptr<UserInterface> m_ui;
std::unique_ptr<Window> m_window;
EnvVarMap m_env_vars;
InputHandler m_input_handler;
DisplayLine m_status_line;
DisplayLine m_mode_line;
enum PendingUI : int
{
MenuShow = 1 << 0,
MenuSelect = 1 << 1,
MenuHide = 1 << 2,
InfoShow = 1 << 3,
InfoHide = 1 << 4,
StatusLine = 1 << 5,
Draw = 1 << 6,
Refresh = 1 << 7,
};
int m_ui_pending = 0;
struct Menu
{
Vector<DisplayLine> items;
BufferCoord anchor;
DisplayCoord ui_anchor;
MenuStyle style;
int selected;
} m_menu;
struct Info
{
String title;
String content;
BufferCoord anchor;
DisplayCoord ui_anchor;
InfoStyle style;
} m_info;
Vector<Key, MemoryDomain::Client> m_pending_keys;
bool m_buffer_reload_dialog_opened = false;
SafePtr<Buffer> m_last_buffer;
};
enum class Autoreload
{
Yes,
No,
Ask
};
constexpr Array<EnumDesc<Autoreload>, 5> enum_desc(Autoreload)
{
return { {
{ Autoreload::Yes, "yes" },
{ Autoreload::No, "no" },
{ Autoreload::Ask, "ask" },
{ Autoreload::Yes, "true" },
{ Autoreload::No, "false" }
} };
}
}
#endif // client_hh_INCLUDED
<commit_msg>Fix some uninitialized values<commit_after>#ifndef client_hh_INCLUDED
#define client_hh_INCLUDED
#include "display_buffer.hh"
#include "env_vars.hh"
#include "input_handler.hh"
#include "safe_ptr.hh"
#include "utils.hh"
#include "option_manager.hh"
#include "enum.hh"
namespace Kakoune
{
class Window;
class UserInterface;
class String;
struct Key;
enum class EventMode;
enum class InfoStyle;
enum class MenuStyle;
class Client : public SafeCountable, public OptionManagerWatcher
{
public:
Client(std::unique_ptr<UserInterface>&& ui,
std::unique_ptr<Window>&& window,
SelectionList selections,
EnvVarMap env_vars,
String name);
~Client() override;
Client(Client&&) = delete;
bool process_pending_inputs();
void menu_show(Vector<DisplayLine> choices, BufferCoord anchor, MenuStyle style);
void menu_select(int selected);
void menu_hide();
void info_show(String title, String content, BufferCoord anchor, InfoStyle style);
void info_hide(bool even_modal = false);
void print_status(DisplayLine status_line, bool immediate = false);
DisplayCoord dimensions() const;
void force_redraw();
void redraw_ifn();
void check_if_buffer_needs_reloading();
Context& context() { return m_input_handler.context(); }
const Context& context() const { return m_input_handler.context(); }
InputHandler& input_handler() { return m_input_handler; }
const InputHandler& input_handler() const { return m_input_handler; }
void change_buffer(Buffer& buffer);
StringView get_env_var(StringView name) const;
Buffer* last_buffer() const { return m_last_buffer.get(); }
void set_last_buffer(Buffer* last_buffer) { m_last_buffer = last_buffer; }
private:
void on_option_changed(const Option& option) override;
void on_buffer_reload_key(Key key);
void close_buffer_reload_dialog();
void reload_buffer();
Optional<Key> get_next_key(EventMode mode);
DisplayLine generate_mode_line() const;
std::unique_ptr<UserInterface> m_ui;
std::unique_ptr<Window> m_window;
EnvVarMap m_env_vars;
InputHandler m_input_handler;
DisplayLine m_status_line;
DisplayLine m_mode_line;
enum PendingUI : int
{
MenuShow = 1 << 0,
MenuSelect = 1 << 1,
MenuHide = 1 << 2,
InfoShow = 1 << 3,
InfoHide = 1 << 4,
StatusLine = 1 << 5,
Draw = 1 << 6,
Refresh = 1 << 7,
};
int m_ui_pending = 0;
struct Menu
{
Vector<DisplayLine> items;
BufferCoord anchor;
DisplayCoord ui_anchor;
MenuStyle style;
int selected;
} m_menu{};
struct Info
{
String title;
String content;
BufferCoord anchor;
DisplayCoord ui_anchor;
InfoStyle style;
} m_info{};
Vector<Key, MemoryDomain::Client> m_pending_keys;
bool m_buffer_reload_dialog_opened = false;
SafePtr<Buffer> m_last_buffer;
};
enum class Autoreload
{
Yes,
No,
Ask
};
constexpr Array<EnumDesc<Autoreload>, 5> enum_desc(Autoreload)
{
return { {
{ Autoreload::Yes, "yes" },
{ Autoreload::No, "no" },
{ Autoreload::Ask, "ask" },
{ Autoreload::Yes, "true" },
{ Autoreload::No, "false" }
} };
}
}
#endif // client_hh_INCLUDED
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "buildstepspage.h"
#include "buildconfiguration.h"
#include "buildsteplist.h"
#include "detailsbutton.h"
#include "projectexplorerconstants.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <utils/detailswidget.h>
#include <QtCore/QSignalMapper>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QToolButton>
#include <QtGui/QMessageBox>
#include <QtGui/QMainWindow>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
BuildStepListWidget::BuildStepListWidget(QWidget *parent) :
NamedWidget(parent),
m_buildStepList(0),
m_addButton(0)
{
setStyleSheet("background: red");
}
BuildStepListWidget::~BuildStepListWidget()
{
foreach(const BuildStepsWidgetStruct &s, m_buildSteps) {
delete s.widget;
delete s.detailsWidget;
}
m_buildSteps.clear();
}
void BuildStepListWidget::updateSummary()
{
BuildStepConfigWidget *widget = qobject_cast<BuildStepConfigWidget *>(sender());
if (widget) {
foreach(const BuildStepsWidgetStruct &s, m_buildSteps) {
if (s.widget == widget) {
s.detailsWidget->setSummaryText(widget->summaryText());
break;
}
}
}
}
void BuildStepListWidget::init(BuildStepList *bsl)
{
Q_ASSERT(bsl);
setupUi();
foreach(BuildStepsWidgetStruct s, m_buildSteps) {
delete s.widget;
delete s.detailsWidget;
}
m_buildSteps.clear();
m_buildStepList = bsl;
//: %1 is the name returned by BuildStepList::displayName
setDisplayName(tr("%1 Steps").arg(m_buildStepList->displayName()));
for (int i = 0; i < bsl->count(); ++i)
addBuildStepWidget(i, m_buildStepList->at(i));
m_noStepsLabel->setVisible(bsl->isEmpty());
m_noStepsLabel->setText(tr("No %1 Steps").arg(m_buildStepList->displayName()));
m_addButton->setText(tr("Add %1 Step").arg(m_buildStepList->displayName()));
// make sure widget is updated
foreach(BuildStepsWidgetStruct s, m_buildSteps) {
s.widget->init();
s.detailsWidget->setSummaryText(s.widget->summaryText());
}
updateBuildStepButtonsState();
static QLatin1String buttonStyle(
"QToolButton{ border-width: 2;}"
"QToolButton:hover{border-image: url(:/welcome/images/btn_26_hover.png) 4;}"
"QToolButton:pressed{ border-image: url(:/welcome/images/btn_26_pressed.png) 4;}");
setStyleSheet(buttonStyle);
}
void BuildStepListWidget::updateAddBuildStepMenu()
{
QMap<QString, QPair<QString, IBuildStepFactory *> > map;
//Build up a list of possible steps and save map the display names to the (internal) name and factories.
QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IBuildStepFactory>();
foreach (IBuildStepFactory *factory, factories) {
QStringList ids = factory->availableCreationIds(m_buildStepList);
foreach (const QString &id, ids) {
map.insert(factory->displayNameForId(id), QPair<QString, IBuildStepFactory *>(id, factory));
}
}
// Ask the user which one to add
QMenu *menu = m_addButton->menu();
m_addBuildStepHash.clear();
menu->clear();
if (!map.isEmpty()) {
QMap<QString, QPair<QString, IBuildStepFactory *> >::const_iterator it, end;
end = map.constEnd();
for (it = map.constBegin(); it != end; ++it) {
QAction *action = menu->addAction(it.key());
connect(action, SIGNAL(triggered()),
this, SLOT(addBuildStep()));
m_addBuildStepHash.insert(action, it.value());
}
}
}
void BuildStepListWidget::addBuildStepWidget(int pos, BuildStep *step)
{
// create everything
BuildStepsWidgetStruct s;
s.widget = step->createConfigWidget();
Q_ASSERT(s.widget);
s.widget->init();
s.detailsWidget = new Utils::DetailsWidget(this);
s.detailsWidget->setSummaryText(s.widget->summaryText());
s.detailsWidget->setWidget(s.widget);
// layout
Utils::FadingPanel *toolWidget = new Utils::FadingPanel(s.detailsWidget);
#ifdef Q_WS_MAC
QSize buttonSize(20, 20);
#else
QSize buttonSize(20, 26);
#endif
s.upButton = new QToolButton(toolWidget);
s.upButton->setAutoRaise(true);
s.upButton->setToolTip(tr("Move Up"));
s.upButton->setFixedSize(buttonSize);
s.upButton->setIcon(QIcon(QLatin1String(":/core/images/darkarrowup.png")));
s.downButton = new QToolButton(toolWidget);
s.downButton->setAutoRaise(true);
s.downButton->setToolTip(tr("Move Down"));
s.downButton->setFixedSize(buttonSize);
s.downButton->setIcon(QIcon(QLatin1String(":/core/images/darkarrowdown.png")));
s.removeButton = new QToolButton(toolWidget);
s.removeButton->setAutoRaise(true);
s.removeButton->setToolTip(tr("Remove Item"));
s.removeButton->setFixedSize(buttonSize);
s.removeButton->setIcon(QIcon(QLatin1String(":/core/images/darkclose.png")));
toolWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
QHBoxLayout *hbox = new QHBoxLayout();
toolWidget->setLayout(hbox);
hbox->setMargin(4);
hbox->setSpacing(0);
hbox->addWidget(s.upButton);
hbox->addWidget(s.downButton);
hbox->addWidget(s.removeButton);
s.detailsWidget->setToolWidget(toolWidget);
s.detailsWidget->setContentsMargins(0, 0, 0, 1);
m_buildSteps.insert(pos, s);
m_vbox->insertWidget(pos, s.detailsWidget);
connect(s.widget, SIGNAL(updateSummary()),
this, SLOT(updateSummary()));
connect(s.upButton, SIGNAL(clicked()),
m_upMapper, SLOT(map()));
connect(s.downButton, SIGNAL(clicked()),
m_downMapper, SLOT(map()));
connect(s.removeButton, SIGNAL(clicked()),
m_removeMapper, SLOT(map()));
}
void BuildStepListWidget::addBuildStep()
{
if (QAction *action = qobject_cast<QAction *>(sender())) {
QPair<QString, IBuildStepFactory *> pair = m_addBuildStepHash.value(action);
BuildStep *newStep = pair.second->create(m_buildStepList, pair.first);
int pos = m_buildStepList->count();
m_buildStepList->insertStep(pos, newStep);
addBuildStepWidget(pos, newStep);
const BuildStepsWidgetStruct s = m_buildSteps.at(pos);
s.detailsWidget->setState(Utils::DetailsWidget::Expanded);
}
m_noStepsLabel->setVisible(false);
updateBuildStepButtonsState();
}
void BuildStepListWidget::stepMoveUp(int pos)
{
m_buildStepList->moveStepUp(pos);
m_vbox->insertWidget(pos - 1, m_buildSteps.at(pos).detailsWidget);
m_buildSteps.swap(pos - 1, pos);
updateBuildStepButtonsState();
}
void BuildStepListWidget::stepMoveDown(int pos)
{
stepMoveUp(pos + 1);
}
void BuildStepListWidget::stepRemove(int pos)
{
if (m_buildStepList->removeStep(pos)) {
BuildStepsWidgetStruct s = m_buildSteps.at(pos);
delete s.widget;
delete s.detailsWidget;
m_buildSteps.removeAt(pos);
updateBuildStepButtonsState();
bool hasSteps = m_buildStepList->isEmpty();
m_noStepsLabel->setVisible(hasSteps);
} else {
QMessageBox::warning(Core::ICore::instance()->mainWindow(),
tr("Removing Step failed"),
tr("Cannot remove build step while building"),
QMessageBox::Ok, QMessageBox::Ok);
}
}
void BuildStepListWidget::setupUi()
{
if (0 != m_addButton)
return;
m_upMapper = new QSignalMapper(this);
connect(m_upMapper, SIGNAL(mapped(int)),
this, SLOT(stepMoveUp(int)));
m_downMapper = new QSignalMapper(this);
connect(m_downMapper, SIGNAL(mapped(int)),
this, SLOT(stepMoveDown(int)));
m_removeMapper = new QSignalMapper(this);
connect(m_removeMapper, SIGNAL(mapped(int)),
this, SLOT(stepRemove(int)));
m_vbox = new QVBoxLayout(this);
m_vbox->setContentsMargins(0, 0, 0, 0);
m_vbox->setSpacing(0);
m_noStepsLabel = new QLabel(tr("No Build Steps"), this);
m_noStepsLabel->setContentsMargins(0, 0, 0, 0);
m_vbox->addWidget(m_noStepsLabel);
QHBoxLayout *hboxLayout = new QHBoxLayout();
hboxLayout->setContentsMargins(0, 4, 0, 0);
m_addButton = new QPushButton(this);
m_addButton->setMenu(new QMenu(this));
hboxLayout->addWidget(m_addButton);
hboxLayout->addStretch(10);
#ifdef Q_OS_MAC
m_addButton->setAttribute(Qt::WA_MacSmallSize);
#endif
m_vbox->addLayout(hboxLayout);
connect(m_addButton->menu(), SIGNAL(aboutToShow()),
this, SLOT(updateAddBuildStepMenu()));
}
void BuildStepListWidget::updateBuildStepButtonsState()
{
for(int i = 0; i < m_buildSteps.count(); ++i) {
BuildStepsWidgetStruct s = m_buildSteps.at(i);
s.removeButton->setEnabled(!m_buildStepList->at(i)->immutable());
m_removeMapper->setMapping(s.removeButton, i);
s.upButton->setEnabled((i > 0)
&& !(m_buildStepList->at(i)->immutable()
&& m_buildStepList->at(i - 1)));
m_upMapper->setMapping(s.upButton, i);
s.downButton->setEnabled((i + 1 < m_buildStepList->count())
&& !(m_buildStepList->at(i)->immutable()
&& m_buildStepList->at(i + 1)->immutable()));
m_downMapper->setMapping(s.downButton, i);
// Only show buttons when needed
s.downButton->setVisible(m_buildStepList->count() != 1);
s.upButton->setVisible(m_buildStepList->count() != 1);
}
}
BuildStepsPage::BuildStepsPage(Target *target, const QString &id) :
BuildConfigWidget(),
m_id(id),
m_widget(new BuildStepListWidget(this))
{
Q_UNUSED(target);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(m_widget);
}
BuildStepsPage::~BuildStepsPage()
{ }
QString BuildStepsPage::displayName() const
{
if (m_id == QLatin1String(Constants::BUILDSTEPS_BUILD))
return tr("Build Steps");
if (m_id == QLatin1String(Constants::BUILDSTEPS_CLEAN))
return tr("Clean Steps");
return QString();
}
void BuildStepsPage::init(BuildConfiguration *bc)
{
m_widget->init(bc->stepList(m_id));
}
<commit_msg>ProjectExplorer: DeployStepsPage avoid callign init() twice<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "buildstepspage.h"
#include "buildconfiguration.h"
#include "buildsteplist.h"
#include "detailsbutton.h"
#include "projectexplorerconstants.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <utils/detailswidget.h>
#include <QtCore/QSignalMapper>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QMenu>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QToolButton>
#include <QtGui/QMessageBox>
#include <QtGui/QMainWindow>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
BuildStepListWidget::BuildStepListWidget(QWidget *parent) :
NamedWidget(parent),
m_buildStepList(0),
m_addButton(0)
{
setStyleSheet("background: red");
}
BuildStepListWidget::~BuildStepListWidget()
{
foreach(const BuildStepsWidgetStruct &s, m_buildSteps) {
delete s.widget;
delete s.detailsWidget;
}
m_buildSteps.clear();
}
void BuildStepListWidget::updateSummary()
{
BuildStepConfigWidget *widget = qobject_cast<BuildStepConfigWidget *>(sender());
if (widget) {
foreach(const BuildStepsWidgetStruct &s, m_buildSteps) {
if (s.widget == widget) {
s.detailsWidget->setSummaryText(widget->summaryText());
break;
}
}
}
}
void BuildStepListWidget::init(BuildStepList *bsl)
{
Q_ASSERT(bsl);
setupUi();
foreach(BuildStepsWidgetStruct s, m_buildSteps) {
delete s.widget;
delete s.detailsWidget;
}
m_buildSteps.clear();
m_buildStepList = bsl;
//: %1 is the name returned by BuildStepList::displayName
setDisplayName(tr("%1 Steps").arg(m_buildStepList->displayName()));
for (int i = 0; i < bsl->count(); ++i)
addBuildStepWidget(i, m_buildStepList->at(i));
m_noStepsLabel->setVisible(bsl->isEmpty());
m_noStepsLabel->setText(tr("No %1 Steps").arg(m_buildStepList->displayName()));
m_addButton->setText(tr("Add %1 Step").arg(m_buildStepList->displayName()));
updateBuildStepButtonsState();
static QLatin1String buttonStyle(
"QToolButton{ border-width: 2;}"
"QToolButton:hover{border-image: url(:/welcome/images/btn_26_hover.png) 4;}"
"QToolButton:pressed{ border-image: url(:/welcome/images/btn_26_pressed.png) 4;}");
setStyleSheet(buttonStyle);
}
void BuildStepListWidget::updateAddBuildStepMenu()
{
QMap<QString, QPair<QString, IBuildStepFactory *> > map;
//Build up a list of possible steps and save map the display names to the (internal) name and factories.
QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IBuildStepFactory>();
foreach (IBuildStepFactory *factory, factories) {
QStringList ids = factory->availableCreationIds(m_buildStepList);
foreach (const QString &id, ids) {
map.insert(factory->displayNameForId(id), QPair<QString, IBuildStepFactory *>(id, factory));
}
}
// Ask the user which one to add
QMenu *menu = m_addButton->menu();
m_addBuildStepHash.clear();
menu->clear();
if (!map.isEmpty()) {
QMap<QString, QPair<QString, IBuildStepFactory *> >::const_iterator it, end;
end = map.constEnd();
for (it = map.constBegin(); it != end; ++it) {
QAction *action = menu->addAction(it.key());
connect(action, SIGNAL(triggered()),
this, SLOT(addBuildStep()));
m_addBuildStepHash.insert(action, it.value());
}
}
}
void BuildStepListWidget::addBuildStepWidget(int pos, BuildStep *step)
{
// create everything
BuildStepsWidgetStruct s;
s.widget = step->createConfigWidget();
Q_ASSERT(s.widget);
s.widget->init();
s.detailsWidget = new Utils::DetailsWidget(this);
s.detailsWidget->setSummaryText(s.widget->summaryText());
s.detailsWidget->setWidget(s.widget);
// layout
Utils::FadingPanel *toolWidget = new Utils::FadingPanel(s.detailsWidget);
#ifdef Q_WS_MAC
QSize buttonSize(20, 20);
#else
QSize buttonSize(20, 26);
#endif
s.upButton = new QToolButton(toolWidget);
s.upButton->setAutoRaise(true);
s.upButton->setToolTip(tr("Move Up"));
s.upButton->setFixedSize(buttonSize);
s.upButton->setIcon(QIcon(QLatin1String(":/core/images/darkarrowup.png")));
s.downButton = new QToolButton(toolWidget);
s.downButton->setAutoRaise(true);
s.downButton->setToolTip(tr("Move Down"));
s.downButton->setFixedSize(buttonSize);
s.downButton->setIcon(QIcon(QLatin1String(":/core/images/darkarrowdown.png")));
s.removeButton = new QToolButton(toolWidget);
s.removeButton->setAutoRaise(true);
s.removeButton->setToolTip(tr("Remove Item"));
s.removeButton->setFixedSize(buttonSize);
s.removeButton->setIcon(QIcon(QLatin1String(":/core/images/darkclose.png")));
toolWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
QHBoxLayout *hbox = new QHBoxLayout();
toolWidget->setLayout(hbox);
hbox->setMargin(4);
hbox->setSpacing(0);
hbox->addWidget(s.upButton);
hbox->addWidget(s.downButton);
hbox->addWidget(s.removeButton);
s.detailsWidget->setToolWidget(toolWidget);
s.detailsWidget->setContentsMargins(0, 0, 0, 1);
m_buildSteps.insert(pos, s);
m_vbox->insertWidget(pos, s.detailsWidget);
connect(s.widget, SIGNAL(updateSummary()),
this, SLOT(updateSummary()));
connect(s.upButton, SIGNAL(clicked()),
m_upMapper, SLOT(map()));
connect(s.downButton, SIGNAL(clicked()),
m_downMapper, SLOT(map()));
connect(s.removeButton, SIGNAL(clicked()),
m_removeMapper, SLOT(map()));
}
void BuildStepListWidget::addBuildStep()
{
if (QAction *action = qobject_cast<QAction *>(sender())) {
QPair<QString, IBuildStepFactory *> pair = m_addBuildStepHash.value(action);
BuildStep *newStep = pair.second->create(m_buildStepList, pair.first);
int pos = m_buildStepList->count();
m_buildStepList->insertStep(pos, newStep);
addBuildStepWidget(pos, newStep);
const BuildStepsWidgetStruct s = m_buildSteps.at(pos);
s.detailsWidget->setState(Utils::DetailsWidget::Expanded);
}
m_noStepsLabel->setVisible(false);
updateBuildStepButtonsState();
}
void BuildStepListWidget::stepMoveUp(int pos)
{
m_buildStepList->moveStepUp(pos);
m_vbox->insertWidget(pos - 1, m_buildSteps.at(pos).detailsWidget);
m_buildSteps.swap(pos - 1, pos);
updateBuildStepButtonsState();
}
void BuildStepListWidget::stepMoveDown(int pos)
{
stepMoveUp(pos + 1);
}
void BuildStepListWidget::stepRemove(int pos)
{
if (m_buildStepList->removeStep(pos)) {
BuildStepsWidgetStruct s = m_buildSteps.at(pos);
delete s.widget;
delete s.detailsWidget;
m_buildSteps.removeAt(pos);
updateBuildStepButtonsState();
bool hasSteps = m_buildStepList->isEmpty();
m_noStepsLabel->setVisible(hasSteps);
} else {
QMessageBox::warning(Core::ICore::instance()->mainWindow(),
tr("Removing Step failed"),
tr("Cannot remove build step while building"),
QMessageBox::Ok, QMessageBox::Ok);
}
}
void BuildStepListWidget::setupUi()
{
if (0 != m_addButton)
return;
m_upMapper = new QSignalMapper(this);
connect(m_upMapper, SIGNAL(mapped(int)),
this, SLOT(stepMoveUp(int)));
m_downMapper = new QSignalMapper(this);
connect(m_downMapper, SIGNAL(mapped(int)),
this, SLOT(stepMoveDown(int)));
m_removeMapper = new QSignalMapper(this);
connect(m_removeMapper, SIGNAL(mapped(int)),
this, SLOT(stepRemove(int)));
m_vbox = new QVBoxLayout(this);
m_vbox->setContentsMargins(0, 0, 0, 0);
m_vbox->setSpacing(0);
m_noStepsLabel = new QLabel(tr("No Build Steps"), this);
m_noStepsLabel->setContentsMargins(0, 0, 0, 0);
m_vbox->addWidget(m_noStepsLabel);
QHBoxLayout *hboxLayout = new QHBoxLayout();
hboxLayout->setContentsMargins(0, 4, 0, 0);
m_addButton = new QPushButton(this);
m_addButton->setMenu(new QMenu(this));
hboxLayout->addWidget(m_addButton);
hboxLayout->addStretch(10);
#ifdef Q_OS_MAC
m_addButton->setAttribute(Qt::WA_MacSmallSize);
#endif
m_vbox->addLayout(hboxLayout);
connect(m_addButton->menu(), SIGNAL(aboutToShow()),
this, SLOT(updateAddBuildStepMenu()));
}
void BuildStepListWidget::updateBuildStepButtonsState()
{
for(int i = 0; i < m_buildSteps.count(); ++i) {
BuildStepsWidgetStruct s = m_buildSteps.at(i);
s.removeButton->setEnabled(!m_buildStepList->at(i)->immutable());
m_removeMapper->setMapping(s.removeButton, i);
s.upButton->setEnabled((i > 0)
&& !(m_buildStepList->at(i)->immutable()
&& m_buildStepList->at(i - 1)));
m_upMapper->setMapping(s.upButton, i);
s.downButton->setEnabled((i + 1 < m_buildStepList->count())
&& !(m_buildStepList->at(i)->immutable()
&& m_buildStepList->at(i + 1)->immutable()));
m_downMapper->setMapping(s.downButton, i);
// Only show buttons when needed
s.downButton->setVisible(m_buildStepList->count() != 1);
s.upButton->setVisible(m_buildStepList->count() != 1);
}
}
BuildStepsPage::BuildStepsPage(Target *target, const QString &id) :
BuildConfigWidget(),
m_id(id),
m_widget(new BuildStepListWidget(this))
{
Q_UNUSED(target);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(m_widget);
}
BuildStepsPage::~BuildStepsPage()
{ }
QString BuildStepsPage::displayName() const
{
if (m_id == QLatin1String(Constants::BUILDSTEPS_BUILD))
return tr("Build Steps");
if (m_id == QLatin1String(Constants::BUILDSTEPS_CLEAN))
return tr("Clean Steps");
return QString();
}
void BuildStepsPage::init(BuildConfiguration *bc)
{
m_widget->init(bc->stepList(m_id));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coins.h"
#include "memusage.h"
#include "random.h"
#include "util.h"
#include <assert.h>
/**
* calculate number of bytes for the bitmask, and its number of non-zero bytes
* each bit in the bitmask represents the availability of one output, but the
* availabilities of the first two outputs are encoded separately
*/
void CCoins::CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
if (!vout[2+b*8+i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool CCoins::Spend(uint32_t nPos)
{
if (nPos >= vout.size() || vout[nPos].IsNull())
return false;
vout[nPos].SetNull();
Cleanup();
return true;
}
bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; }
bool CCoinsView::HaveCoins(const uint256 &txid) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return false; }
bool CCoinsView::GetStats(CCoinsStats &stats) const { return false; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); }
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return base->BatchWrite(mapCoins, hashBlock, nChildCachedCoinsUsage); }
bool CCoinsViewBacked::GetStats(CCoinsStats &stats) const { return base->GetStats(stats); }
CCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), cachedCoinsUsage(0) { }
CCoinsViewCache::~CCoinsViewCache()
{
assert(!hasModifier);
}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
LOCK(cs_utxo);
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256 &txid) const {
// requires cs_utxo
CCoinsMap::iterator it = cacheCoins.find(txid);
if (it != cacheCoins.end())
return it;
CCoins tmp;
if (!base->GetCoins(txid, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
tmp.swap(ret->second.coins);
if (ret->second.coins.IsPruned()) {
// The parent only has an empty entry for this txid; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coins.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it != cacheCoins.end()) {
coins = it->second.coins;
return true;
}
return false;
}
CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
LOCK(cs_utxo);
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
size_t cachedCoinUsage = 0;
if (ret.second) {
if (!base->GetCoins(txid, ret.first->second.coins)) {
// The parent view does not have this entry; mark it as fresh.
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
} else if (ret.first->second.coins.IsPruned()) {
// The parent view only has a pruned entry for this; mark it as fresh.
ret.first->second.flags = CCoinsCacheEntry::FRESH;
}
} else {
cachedCoinUsage = ret.first->second.coins.DynamicMemoryUsage();
}
// Assume that whenever ModifyCoins is called, the entry will be modified.
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, cachedCoinUsage);
}
CCoinsModifier CCoinsViewCache::ModifyNewCoins(const uint256 &txid) {
LOCK(cs_utxo);
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, 0);
}
const CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it == cacheCoins.end()) {
return NULL;
} else {
return &it->second.coins;
}
}
bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = FetchCoins(txid);
// We're using vtx.empty() instead of IsPruned here for performance reasons,
// as we only care about the case where a transaction was replaced entirely
// in a reorganization (which wipes vout entirely, as opposed to spending
// which just cleans individual outputs).
return (it != cacheCoins.end() && !it->second.coins.vout.empty());
}
bool CCoinsViewCache::HaveCoinsInCache(const uint256 &txid) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = cacheCoins.find(txid);
return it != cacheCoins.end();
}
uint256 CCoinsViewCache::GetBestBlock() const {
LOCK(cs_utxo);
if (hashBlock.IsNull())
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
LOCK(cs_utxo);
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, size_t &nChildCachedCoinsUsage)
{
assert(!hasModifier);
LOCK(cs_utxo);
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child does
// We can ignore it if it's both FRESH and pruned in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coins.IsPruned())) {
// Otherwise we will need to create it in the parent
// and move the data up and mark it as dirty
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coins.swap(it->second.coins);
cachedCoinsUsage += entry.coins.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH)
entry.flags |= CCoinsCacheEntry::FRESH;
}
} else {
// Found the entry in the parent cache
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
// The grandparent does not have an entry, and the child is
// modified and being pruned. This means we can just delete
// it from the parent.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
itUs->second.coins.swap(it->second.coins);
cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
}
}
// Update the usage of the child cache before deleting the entry in the child cache
nChildCachedCoinsUsage -= it->second.coins.DynamicMemoryUsage();
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
LOCK(cs_utxo);
bool fOk = base->BatchWrite(cacheCoins, hashBlock, cachedCoinsUsage);
return fOk;
}
void CCoinsViewCache::Trim(size_t nTrimSize) const
{
uint64_t nTrimmed = 0;
LOCK(cs_utxo);
CCoinsMap::iterator iter = cacheCoins.begin();
while (cachedCoinsUsage > nTrimSize)
{
if (iter == cacheCoins.end())
break;
// Only erase entries that have not been modified
if (iter->second.flags == 0)
{
cachedCoinsUsage -= iter->second.coins.DynamicMemoryUsage();
CCoinsMap::iterator itOld = iter++;
cacheCoins.erase(itOld);
nTrimmed++;
}
else
iter++;
}
LogPrint("coindb", "Trimmed %ld from the CoinsViewCache, current size after trim: %ld and usage %ld bytes\n", nTrimmed, cacheCoins.size(), cachedCoinsUsage);
}
void CCoinsViewCache::Uncache(const uint256& hash)
{
LOCK(cs_utxo);
CCoinsMap::iterator it = cacheCoins.find(hash);
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coins.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
LOCK(cs_utxo);
return cacheCoins.size();
}
const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const
{
LOCK(cs_utxo);
const CCoins* coins = AccessCoins(input.prevout.hash);
assert(coins && coins->IsAvailable(input.prevout.n));
return coins->vout[input.prevout.n];
}
CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
{
LOCK(cs_utxo);
if (tx.IsCoinBase())
return 0;
CAmount nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += GetOutputFor(tx.vin[i]).nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
LOCK(cs_utxo);
if (!tx.IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins* coins = AccessCoins(prevout.hash);
if (!coins || !coins->IsAvailable(prevout.n)) {
return false;
}
}
}
return true;
}
double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const
{
LOCK(cs_utxo);
inChainInputValue = 0;
if (tx.IsCoinBase())
return 0.0;
double dResult = 0.0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
const CCoins* coins = AccessCoins(txin.prevout.hash);
assert(coins);
if (!coins->IsAvailable(txin.prevout.n)) continue;
if (coins->nHeight <= nHeight) {
dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight);
inChainInputValue += coins->vout[txin.prevout.n].nValue;
}
}
return tx.ComputePriority(dResult);
}
CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage) : cache(cache_), it(it_), cachedCoinUsage(usage) {
assert(!cache.hasModifier);
LOCK(cache.cs_utxo);
cache.hasModifier = true;
}
CCoinsModifier::~CCoinsModifier()
{
assert(cache.hasModifier);
LOCK(cache.cs_utxo);
cache.hasModifier = false;
it->second.coins.Cleanup();
cache.cachedCoinsUsage -= cachedCoinUsage; // Subtract the old usage
if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
cache.cacheCoins.erase(it);
} else {
// If the coin still exists after the modification, add the new usage
cache.cachedCoinsUsage += it->second.coins.DynamicMemoryUsage();
}
}
<commit_msg>Increment Iterator and move locks<commit_after>// Copyright (c) 2012-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coins.h"
#include "memusage.h"
#include "random.h"
#include "util.h"
#include <assert.h>
/**
* calculate number of bytes for the bitmask, and its number of non-zero bytes
* each bit in the bitmask represents the availability of one output, but the
* availabilities of the first two outputs are encoded separately
*/
void CCoins::CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
if (!vout[2+b*8+i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool CCoins::Spend(uint32_t nPos)
{
if (nPos >= vout.size() || vout[nPos].IsNull())
return false;
vout[nPos].SetNull();
Cleanup();
return true;
}
bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; }
bool CCoinsView::HaveCoins(const uint256 &txid) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return false; }
bool CCoinsView::GetStats(CCoinsStats &stats) const { return false; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); }
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return base->BatchWrite(mapCoins, hashBlock, nChildCachedCoinsUsage); }
bool CCoinsViewBacked::GetStats(CCoinsStats &stats) const { return base->GetStats(stats); }
CCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}
CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), cachedCoinsUsage(0) { }
CCoinsViewCache::~CCoinsViewCache()
{
LOCK(cs_utxo);
assert(!hasModifier);
}
size_t CCoinsViewCache::DynamicMemoryUsage() const {
LOCK(cs_utxo);
return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
}
CCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256 &txid) const {
// requires cs_utxo
CCoinsMap::iterator it = cacheCoins.find(txid);
if (it != cacheCoins.end())
return it;
CCoins tmp;
if (!base->GetCoins(txid, tmp))
return cacheCoins.end();
CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
tmp.swap(ret->second.coins);
if (ret->second.coins.IsPruned()) {
// The parent only has an empty entry for this txid; we can consider our
// version as fresh.
ret->second.flags = CCoinsCacheEntry::FRESH;
}
cachedCoinsUsage += ret->second.coins.DynamicMemoryUsage();
return ret;
}
bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it != cacheCoins.end()) {
coins = it->second.coins;
return true;
}
return false;
}
CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
LOCK(cs_utxo);
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
size_t cachedCoinUsage = 0;
if (ret.second) {
if (!base->GetCoins(txid, ret.first->second.coins)) {
// The parent view does not have this entry; mark it as fresh.
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
} else if (ret.first->second.coins.IsPruned()) {
// The parent view only has a pruned entry for this; mark it as fresh.
ret.first->second.flags = CCoinsCacheEntry::FRESH;
}
} else {
cachedCoinUsage = ret.first->second.coins.DynamicMemoryUsage();
}
// Assume that whenever ModifyCoins is called, the entry will be modified.
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, cachedCoinUsage);
}
CCoinsModifier CCoinsViewCache::ModifyNewCoins(const uint256 &txid) {
LOCK(cs_utxo);
assert(!hasModifier);
std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
ret.first->second.coins.Clear();
ret.first->second.flags = CCoinsCacheEntry::FRESH;
ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
return CCoinsModifier(*this, ret.first, 0);
}
const CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = FetchCoins(txid);
if (it == cacheCoins.end()) {
return NULL;
} else {
return &it->second.coins;
}
}
bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = FetchCoins(txid);
// We're using vtx.empty() instead of IsPruned here for performance reasons,
// as we only care about the case where a transaction was replaced entirely
// in a reorganization (which wipes vout entirely, as opposed to spending
// which just cleans individual outputs).
return (it != cacheCoins.end() && !it->second.coins.vout.empty());
}
bool CCoinsViewCache::HaveCoinsInCache(const uint256 &txid) const {
LOCK(cs_utxo);
CCoinsMap::const_iterator it = cacheCoins.find(txid);
return it != cacheCoins.end();
}
uint256 CCoinsViewCache::GetBestBlock() const {
LOCK(cs_utxo);
if (hashBlock.IsNull())
hashBlock = base->GetBestBlock();
return hashBlock;
}
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
LOCK(cs_utxo);
hashBlock = hashBlockIn;
}
bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, size_t &nChildCachedCoinsUsage)
{
assert(!hasModifier);
LOCK(cs_utxo);
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
CCoinsMap::iterator itUs = cacheCoins.find(it->first);
if (itUs == cacheCoins.end()) {
// The parent cache does not have an entry, while the child does
// We can ignore it if it's both FRESH and pruned in the child
if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coins.IsPruned())) {
// Otherwise we will need to create it in the parent
// and move the data up and mark it as dirty
CCoinsCacheEntry& entry = cacheCoins[it->first];
entry.coins.swap(it->second.coins);
cachedCoinsUsage += entry.coins.DynamicMemoryUsage();
entry.flags = CCoinsCacheEntry::DIRTY;
// We can mark it FRESH in the parent if it was FRESH in the child
// Otherwise it might have just been flushed from the parent's cache
// and already exist in the grandparent
if (it->second.flags & CCoinsCacheEntry::FRESH)
entry.flags |= CCoinsCacheEntry::FRESH;
}
} else {
// Found the entry in the parent cache
if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
// The grandparent does not have an entry, and the child is
// modified and being pruned. This means we can just delete
// it from the parent.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
cacheCoins.erase(itUs);
} else {
// A normal modification.
cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
itUs->second.coins.swap(it->second.coins);
cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage();
itUs->second.flags |= CCoinsCacheEntry::DIRTY;
}
}
// Update the usage of the child cache before deleting the entry in the child cache
nChildCachedCoinsUsage -= it->second.coins.DynamicMemoryUsage();
CCoinsMap::iterator itOld = it++;
mapCoins.erase(itOld);
}
else
it++;
}
hashBlock = hashBlockIn;
return true;
}
bool CCoinsViewCache::Flush() {
LOCK(cs_utxo);
bool fOk = base->BatchWrite(cacheCoins, hashBlock, cachedCoinsUsage);
return fOk;
}
void CCoinsViewCache::Trim(size_t nTrimSize) const
{
uint64_t nTrimmed = 0;
LOCK(cs_utxo);
CCoinsMap::iterator iter = cacheCoins.begin();
while (cachedCoinsUsage > nTrimSize)
{
if (iter == cacheCoins.end())
break;
// Only erase entries that have not been modified
if (iter->second.flags == 0)
{
cachedCoinsUsage -= iter->second.coins.DynamicMemoryUsage();
CCoinsMap::iterator itOld = iter++;
cacheCoins.erase(itOld);
nTrimmed++;
}
else
iter++;
}
LogPrint("coindb", "Trimmed %ld from the CoinsViewCache, current size after trim: %ld and usage %ld bytes\n", nTrimmed, cacheCoins.size(), cachedCoinsUsage);
}
void CCoinsViewCache::Uncache(const uint256& hash)
{
LOCK(cs_utxo);
CCoinsMap::iterator it = cacheCoins.find(hash);
if (it != cacheCoins.end() && it->second.flags == 0) {
cachedCoinsUsage -= it->second.coins.DynamicMemoryUsage();
cacheCoins.erase(it);
}
}
unsigned int CCoinsViewCache::GetCacheSize() const {
LOCK(cs_utxo);
return cacheCoins.size();
}
const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const
{
LOCK(cs_utxo);
const CCoins* coins = AccessCoins(input.prevout.hash);
assert(coins && coins->IsAvailable(input.prevout.n));
return coins->vout[input.prevout.n];
}
CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
{
LOCK(cs_utxo);
if (tx.IsCoinBase())
return 0;
CAmount nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
nResult += GetOutputFor(tx.vin[i]).nValue;
return nResult;
}
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
LOCK(cs_utxo);
if (!tx.IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins* coins = AccessCoins(prevout.hash);
if (!coins || !coins->IsAvailable(prevout.n)) {
return false;
}
}
}
return true;
}
double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const
{
LOCK(cs_utxo);
inChainInputValue = 0;
if (tx.IsCoinBase())
return 0.0;
double dResult = 0.0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
const CCoins* coins = AccessCoins(txin.prevout.hash);
assert(coins);
if (!coins->IsAvailable(txin.prevout.n)) continue;
if (coins->nHeight <= nHeight) {
dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight);
inChainInputValue += coins->vout[txin.prevout.n].nValue;
}
}
return tx.ComputePriority(dResult);
}
CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage) : cache(cache_), it(it_), cachedCoinUsage(usage) {
LOCK(cache.cs_utxo);
assert(!cache.hasModifier);
cache.hasModifier = true;
}
CCoinsModifier::~CCoinsModifier()
{
LOCK(cache.cs_utxo);
assert(cache.hasModifier);
cache.hasModifier = false;
it->second.coins.Cleanup();
cache.cachedCoinsUsage -= cachedCoinUsage; // Subtract the old usage
if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
cache.cacheCoins.erase(it);
} else {
// If the coin still exists after the modification, add the new usage
cache.cachedCoinsUsage += it->second.coins.DynamicMemoryUsage();
}
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008-2009 Patrick Spendrin <ps_ml@gmx.de>
//
#include "GeoRendererView.h"
// Marble
#include "GeoDataContainer.h"
#include "GeoDataCoordinates.h"
#include "GeoDataDocument.h"
#include "GeoDataFeature.h"
#include "GeoDataFolder.h"
#include "GeoDataLineStyle.h"
#include "GeoDataObject.h"
#include "GeoDataPlacemark.h"
#include "GeoDataPolygon.h"
#include "GeoDataPolyStyle.h"
#include "GeoDataStyle.h"
#include "GeoDataStyleMap.h"
#include "GeoPainter.h"
// Qt
#include <QtCore/QDebug>
#include <QtGui/QPaintEvent>
using namespace Marble;
GeoRendererView::GeoRendererView( QWidget * parent )
: QAbstractItemView( parent )
{
}
void GeoRendererView::setGeoPainter( GeoPainter* painter )
{
m_painter = painter;
/* the paintEvent function has to called by hand as the view is not
* connected to a widget (where you normally would get the event from) */
if( model() ) paintEvent( 0 );
}
QRect GeoRendererView::visualRect( const QModelIndex &index ) const
{
Q_UNUSED( index )
return QRect();
}
void GeoRendererView::scrollTo( const QModelIndex &index, ScrollHint hint )
{
Q_UNUSED( index )
Q_UNUSED( hint )
}
QModelIndex GeoRendererView::indexAt( const QPoint &point ) const
{
Q_UNUSED( point )
return QModelIndex();
}
QModelIndex GeoRendererView::moveCursor( QAbstractItemView::CursorAction cursorAction,
Qt::KeyboardModifiers modifiers )
{
Q_UNUSED( cursorAction )
Q_UNUSED( modifiers )
return QModelIndex();
}
bool GeoRendererView::isIndexHidden( const QModelIndex &index ) const
{
Q_UNUSED( index )
return false;
}
void GeoRendererView::setSelection( const QRect&, QItemSelectionModel::SelectionFlags command )
{
Q_UNUSED( command )
}
void GeoRendererView::paintEvent( QPaintEvent *event )
{
Q_UNUSED( event )
QModelIndex index = rootIndex();
renderIndex( index );
}
void GeoRendererView::renderIndex( QModelIndex &index )
{
/*
* "render" a specific index - this means going through all children and if
* one can be rendered (if it is a Geometry object which is not a container)
* then call the real render function. For the rest iterate through the
* children and recurse.
*/
GeoDataObject* indexObject = model()->data( rootIndex(), Qt::UserRole + 11 ).value<Marble::GeoDataObject*>();
if( !( dynamic_cast<GeoDataFeature*>( indexObject ) && dynamic_cast<GeoDataFeature*>( indexObject )->isVisible() ) ) return;
int rowCount = model()->rowCount( index );
for ( int row = 0; row < rowCount; ++row )
{
QModelIndex childIndex = model()->index( row, 0, index );
QString output = model()->data( childIndex ).toString();
GeoDataObject* object = model()->data( childIndex, Qt::UserRole + 11 ).value<Marble::GeoDataObject*>();
if( dynamic_cast<GeoDataGeometry*>( object ) ) {
if( static_cast<GeoDataGeometry*>( object )->geometryId() != GeoDataMultiGeometryId ) {
renderGeoDataGeometry( reinterpret_cast<GeoDataGeometry*>( object ), styleUrl );
} else {
if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) {
renderIndex( childIndex );
}
}
}
else if( dynamic_cast<GeoDataFeature*>( object ) ) {
if( dynamic_cast<GeoDataFeature*>( object )->featureId() == GeoDataPlacemarkId ) {
GeoDataPlacemark placemark( *static_cast<GeoDataFeature*>( object ) );
styleUrl = placemark.styleUrl();
}
if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) {
renderIndex( childIndex );
}
}
}
}
QRegion GeoRendererView::visualRegionForSelection( const QItemSelection &selection ) const
{
Q_UNUSED( selection )
return QRegion();
}
void GeoRendererView::setBrushStyle( QString mapped )
{
/* this part has to be reworked:
* Currently the style has to be accessible from the root object of the
* model. This might not be wanted. On the other hand - is a copy of the
* style within every Placemark wanted and how should this be called here?
*/
if( m_currentBrush.color() != m_root->style( mapped ).polyStyle().color() ) {
/* qDebug() << "BrushColor:"
<< m_root->style( mapped ).polyStyle()->color()
<< m_currentBrush.color();*/
m_currentBrush.setColor( m_root->style( mapped ).polyStyle().color() );
m_painter->setBrush( m_currentBrush.color() );
}
}
void GeoRendererView::setPenStyle( QString mapped )
{
/*
* see the note in the setBrushStyle function
*/
if( m_currentPen.color() != m_root->style( mapped ).lineStyle().color() ||
m_currentPen.widthF() != m_root->style( mapped ).lineStyle().width() ) {
/* qDebug() << "PenColor:"
<< m_root->style( mapped ).lineStyle().color()
<< m_currentPen.color();
qDebug() << "PenWidth:"
<< m_root->style( mapped ).lineStyle().width()
<< m_currentPen.widthF();*/
m_currentPen.setColor( m_root->style( mapped ).lineStyle().color() );
m_currentPen.setWidthF( m_root->style( mapped ).lineStyle().width() );
}
if ( m_painter->mapQuality() != Marble::High && m_painter->mapQuality() != Marble::Print )
{
// m_currentPen.setWidth( 0 );
QColor penColor = m_currentPen.color();
penColor.setAlpha( 255 );
m_currentPen.setColor( penColor );
}
m_painter->setPen( m_currentPen );
}
bool GeoRendererView::renderGeoDataGeometry( GeoDataGeometry *object, QString styleUrl )
{
m_painter->save();
m_painter->autoMapQuality();
m_root = dynamic_cast<GeoDataDocument*>( model()->data( rootIndex(),
Qt::UserRole + 11 ).value<Marble::GeoDataObject*>() );
if( !m_root ) {
qWarning() << "root seems to be 0!!!";
return false;
}
/// hard coded to use only the "normal" style
QString mapped = styleUrl;
const GeoDataStyleMap& styleMap = m_root->styleMap( styleUrl.remove( '#' ) );
mapped = styleMap.value( QString( "normal" ) );
mapped.remove( '#' );
if( object->geometryId() == GeoDataPolygonId ) {
setBrushStyle( mapped );
setPenStyle( mapped );
m_painter->drawPolygon( *static_cast<GeoDataPolygon*>( object ) );
}
if( object->geometryId() == GeoDataLinearRingId ) {
m_painter->setBrush( QColor( 0, 0, 0, 0 ) );
setPenStyle( mapped );
m_painter->drawPolygon( *static_cast<GeoDataLinearRing*>( object ) );
}
if( object->geometryId() == GeoDataLineStringId ) {
setPenStyle( mapped );
m_painter->drawPolyline( *static_cast<GeoDataLineString*>( object ) );
}
/* Note: GeoDataMultiGeometry is handled within the model */
m_painter->restore();
return true;
}
<commit_msg>forwardport r981676<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008-2009 Patrick Spendrin <ps_ml@gmx.de>
//
#include "GeoRendererView.h"
// Marble
#include "GeoDataContainer.h"
#include "GeoDataCoordinates.h"
#include "GeoDataDocument.h"
#include "GeoDataFeature.h"
#include "GeoDataFolder.h"
#include "GeoDataLineStyle.h"
#include "GeoDataObject.h"
#include "GeoDataPlacemark.h"
#include "GeoDataPolygon.h"
#include "GeoDataPolyStyle.h"
#include "GeoDataStyle.h"
#include "GeoDataStyleMap.h"
#include "GeoPainter.h"
// Qt
#include <QtCore/QDebug>
#include <QtGui/QPaintEvent>
using namespace Marble;
GeoRendererView::GeoRendererView( QWidget * parent )
: QAbstractItemView( parent )
{
}
void GeoRendererView::setGeoPainter( GeoPainter* painter )
{
m_painter = painter;
/* the paintEvent function has to called by hand as the view is not
* connected to a widget (where you normally would get the event from) */
if( model() ) paintEvent( 0 );
}
QRect GeoRendererView::visualRect( const QModelIndex &index ) const
{
Q_UNUSED( index )
return QRect();
}
void GeoRendererView::scrollTo( const QModelIndex &index, ScrollHint hint )
{
Q_UNUSED( index )
Q_UNUSED( hint )
}
QModelIndex GeoRendererView::indexAt( const QPoint &point ) const
{
Q_UNUSED( point )
return QModelIndex();
}
QModelIndex GeoRendererView::moveCursor( QAbstractItemView::CursorAction cursorAction,
Qt::KeyboardModifiers modifiers )
{
Q_UNUSED( cursorAction )
Q_UNUSED( modifiers )
return QModelIndex();
}
bool GeoRendererView::isIndexHidden( const QModelIndex &index ) const
{
Q_UNUSED( index )
return false;
}
void GeoRendererView::setSelection( const QRect&, QItemSelectionModel::SelectionFlags command )
{
Q_UNUSED( command )
}
void GeoRendererView::paintEvent( QPaintEvent *event )
{
Q_UNUSED( event )
QModelIndex index = rootIndex();
renderIndex( index );
}
void GeoRendererView::renderIndex( QModelIndex &index )
{
/*
* "render" a specific index - this means going through all children and if
* one can be rendered (if it is a Geometry object which is not a container)
* then call the real render function. For the rest iterate through the
* children and recurse.
*/
GeoDataObject* indexObject = model()->data( rootIndex(), Qt::UserRole + 11 ).value<Marble::GeoDataObject*>();
if( !( dynamic_cast<GeoDataFeature*>( indexObject ) && dynamic_cast<GeoDataFeature*>( indexObject )->isVisible() ) ) return;
int rowCount = model()->rowCount( index );
for ( int row = 0; row < rowCount; ++row )
{
QModelIndex childIndex = model()->index( row, 0, index );
QString output = model()->data( childIndex ).toString();
GeoDataObject* object = model()->data( childIndex, Qt::UserRole + 11 ).value<Marble::GeoDataObject*>();
if( dynamic_cast<GeoDataGeometry*>( object ) ) {
if( static_cast<GeoDataGeometry*>( object )->geometryId() != GeoDataMultiGeometryId ) {
renderGeoDataGeometry( reinterpret_cast<GeoDataGeometry*>( object ), styleUrl );
} else {
if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) {
renderIndex( childIndex );
}
}
}
else if( dynamic_cast<GeoDataFeature*>( object ) ) {
if( dynamic_cast<GeoDataFeature*>( object )->featureId() == GeoDataPlacemarkId ) {
GeoDataPlacemark placemark( *static_cast<GeoDataFeature*>( object ) );
styleUrl = placemark.styleUrl();
}
if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) {
renderIndex( childIndex );
}
}
}
}
QRegion GeoRendererView::visualRegionForSelection( const QItemSelection &selection ) const
{
Q_UNUSED( selection )
return QRegion();
}
void GeoRendererView::setBrushStyle( QString mapped )
{
/* this part has to be reworked:
* Currently the style has to be accessible from the root object of the
* model. This might not be wanted. On the other hand - is a copy of the
* style within every Placemark wanted and how should this be called here?
*/
if( m_painter->brush().color() != m_root->style( mapped ).polyStyle().color() ) {
/* qDebug() << "BrushColor:"
<< m_root->style( mapped ).polyStyle()->color()
<< m_painter->brush().color();*/
m_painter->setBrush( m_currentBrush.color() );
}
}
void GeoRendererView::setPenStyle( QString mapped )
{
/*
* see the note in the setBrushStyle function
*/
if( m_currentPen.color() != m_root->style( mapped ).lineStyle().color() ||
m_currentPen.widthF() != m_root->style( mapped ).lineStyle().width() ) {
/* qDebug() << "PenColor:"
<< m_root->style( mapped ).lineStyle().color()
<< m_currentPen.color();
qDebug() << "PenWidth:"
<< m_root->style( mapped ).lineStyle().width()
<< m_currentPen.widthF();*/
m_currentPen.setColor( m_root->style( mapped ).lineStyle().color() );
m_currentPen.setWidthF( m_root->style( mapped ).lineStyle().width() );
}
if ( m_painter->mapQuality() != Marble::High && m_painter->mapQuality() != Marble::Print )
{
// m_currentPen.setWidth( 0 );
QColor penColor = m_currentPen.color();
penColor.setAlpha( 255 );
m_currentPen.setColor( penColor );
}
m_painter->setPen( m_currentPen );
}
bool GeoRendererView::renderGeoDataGeometry( GeoDataGeometry *object, QString styleUrl )
{
m_painter->save();
m_painter->autoMapQuality();
m_root = dynamic_cast<GeoDataDocument*>( model()->data( rootIndex(),
Qt::UserRole + 11 ).value<Marble::GeoDataObject*>() );
if( !m_root ) {
qWarning() << "root seems to be 0!!!";
return false;
}
/// hard coded to use only the "normal" style
QString mapped = styleUrl;
const GeoDataStyleMap& styleMap = m_root->styleMap( styleUrl.remove( '#' ) );
mapped = styleMap.value( QString( "normal" ) );
mapped.remove( '#' );
if( object->geometryId() == GeoDataPolygonId ) {
setBrushStyle( mapped );
setPenStyle( mapped );
m_painter->drawPolygon( *static_cast<GeoDataPolygon*>( object ) );
}
if( object->geometryId() == GeoDataLinearRingId ) {
m_painter->setBrush( QColor( 0, 0, 0, 0 ) );
setPenStyle( mapped );
m_painter->drawPolygon( *static_cast<GeoDataLinearRing*>( object ) );
}
if( object->geometryId() == GeoDataLineStringId ) {
setPenStyle( mapped );
m_painter->drawPolyline( *static_cast<GeoDataLineString*>( object ) );
}
/* Note: GeoDataMultiGeometry is handled within the model */
m_painter->restore();
return true;
}
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/color.hpp"
#include"ork/distribution.hpp"
#if ORK_USE_GLM
#include"glm/vec3.hpp"
namespace ork {
float to_hex_space(const color4&c, const float max, const float chroma) {
/*
Six vertices for hexagon
Define periodic, circular space: red is 0, green is 2, blue is 4
*/
if(chroma == 0.f) {
return 0.f;//By convention, to avoid divide by 0;
}
else if(max == c.r) {//The red third, rotate [+1, -1] about datum 0;
return std::fmod((c.g - c.b) / chroma, 6.f);
}
else if(max == c.g) {//The green third, rotate [+1, -1] about datum 2;
return (c.b - c.r) / chroma + 2.f;
}
else {//max == c.b //The blue third, rotate [+1, -1] about datum 4;
return (c.r - c.g) / chroma + 4.f;
}
}
float hsv_saturation(const float chroma, const float value) {
if(value == 0.f) {
return 0.f;
}
return chroma / value;//(max - min)/max
}
float hsl_saturation(const float chroma, const float lightness) {
if(lightness == 1.f) {
return 0.f;
}
return chroma / (1.f - std::abs(2.f * lightness - 1.f));//(max - min)/(1 - |(max + min) - 1|)
}
glm::vec3 calc_rgb(const float C, const float min, const float h_6) {
const float X = C*(1.f - std::abs(std::fmod(h_6, 2.f) - 1.f));
if(h_6 < 1.f) {
return glm::vec3{C, X, 0.f}+min;
}
else if(h_6 < 2.f) {
return glm::vec3{X, C, 0.f}+min;
}
else if(h_6 < 3.f) {
return glm::vec3{0.f, C, X}+min;
}
else if(h_6 < 4.f) {
return glm::vec3{0.f, X, C}+min;
}
else if(h_6 < 5.f) {
return glm::vec3{X, 0.f, C}+min;
}
else {
return glm::vec3{C, 0.f, X}+min;
}
}
color4 convert(const color4&c, const color_space from_space, const color_space to_space) {
/*
RGB cube, HSV cylinder, HSL cone
In short, turn the cube so 0,0,0 is at bottom and 1,1,1 is at top.
The other 6 points of the cube project onto the corners of a hexagon.
Rotate so that red is at 0 datum.
See https://en.wikipedia.org/wiki/HSL_and_HSV for a good geometric description.
*/
if(from_space == to_space) {//A useful invariant below
return c;
}
if(from_space == color_space::rgb) {
const float min = std::min(c.r, std::min(c.g, c.b));
const float max = std::max(c.r, std::max(c.g, c.b));
const float chroma = max - min;//The normalized scale for color magnitudes
const float hue = to_hex_space(c, max, chroma) / 6.f;//Normalize six-point space to unit interval
const float val_light = to_space == color_space::hsv ? max : (max + min)*0.5f;
const float saturation = to_space == color_space::hsv ? hsv_saturation(chroma, val_light) : hsl_saturation(chroma, val_light);
return color4{hue, saturation, val_light, c.a};
}
else {
const bool is_hsv = from_space == color_space::hsv;//Otherwise HSL
const float chroma = is_hsv
? c.y*c.z//S*V
: (1.f - std::abs(2.f*c.z - 1.f))*c.y//(1 - |2*L - 1|)*S
;
const float h_6 = c.x*6.f;//To hex coordinates
const float min = is_hsv
? c.z - chroma
: c.z - chroma*0.5f
;
const glm::vec3 rgb{calc_rgb(chroma, min, h_6)};
return color4{rgb,c.a};
}
}
ORK_ORK_API const color4 red = {1., 0., 0., 1.};
ORK_ORK_API const color4 green = {0., 1., 0., 1.};
ORK_ORK_API const color4 blue = {0., 0., 1., 1.};
color4 normalized_lightness(const color4&c) {
return normalized_lightness(c, 1.f);
}
color4 normalized_lightness(const color4&c, const float one_norm) {
/*
This is waay simplified, and uses made-up linear coefficients.
Basically, yellow-green appears light and violet-blue appears dark.
*/
const float value = c.r*1.0f + c.g*1.3f + c.b*0.7f;
const glm::vec3 normed(c*one_norm / value);//For debugging
return color4(normed, c.a);//Scale colors, keep alpha
}
color4 normalized_hue(const float value) {//Value is defined on [0, 1]
/*
This is waay simplified, and uses made-up triangle distributions.
We multiply value by 1.5 instead of using thirds.
Each color should be symmetrical and occupy 1.0 width.
We narrow the green spectrum to 0.8.
*/
static ork::triangle_distribution<float>blue_l{-1.0f, -0.5f, 0.1f};//Periodicity
static ork::triangle_distribution<float>red_l{-0.5f, 0.1f, 0.5f};//0.0 should be pure red
static ork::triangle_distribution<float>green{0.1f, 0.5f, 0.9f};//0.5 is pure green
static ork::triangle_distribution<float>blue_h{0.5f, 0.9f, 1.5f};//1.0 should be pure blue
static ork::triangle_distribution<float>red_h{0.9f, 1.5f, 2.0f};//Periodicity
const float rl = red_l(value);
const float rh = red_h(value);
const float g = green(value);
const float bl = blue_l(value);
const float bh = blue_h(value);
const glm::dvec4 normed{rl + rh, g, bl + bh, 1.f};
return normed;
}
color4 normalized_red_green(const float weight) {
const float alpha = std::pow(std::max(0.f, std::min(1.f, weight)), 1.3f);
return (1.f - alpha)*red + alpha*green;
}
std::vector<color4>contrast_array(const size_t size) {
/*
1.
We want max difference between colors, garish is encouraged, so saturation is constant 100%.
As a bonus there will be no grey that might be confused with the 'base' part.
We are down to two dimensions.
2.
Colors with equal contrast with the background are percieved with equal importance.
We want equal importance and assume a white backgrond.
If only this meant constant lightness the problem would be reduced to one dimension, hue.
3.
Colors in proximity are perceived as more different.
Humans process difference more easily bwtween colors in close proximity if variation is smallish.
We can't account for spatial proximity within this function interface, but it is something to think about.
*/
std::vector<color4>retval;
LOOPI(size) {
const float val = float(i) / float(size - 1);
retval.push_back(normalized_lightness(normalized_hue(val)));
}
return std::move(retval);
}
}//namespace ork
namespace glm {
ork::o_stream&operator<<(ork::o_stream&stream, const ork::color4&c) {
stream << ORK("(") << c.r << ORK(", ") << c.g << ORK(", ") << c.b << ORK(", ") << c.a << ORK(")");
return stream;
}
}
#endif//ORK_USE_GLM
<commit_msg>Fixed a divide by 0 calculating HSL saturation<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/color.hpp"
#include"ork/distribution.hpp"
#if ORK_USE_GLM
#include"glm/vec3.hpp"
namespace ork {
float to_hex_space(const color4&c, const float max, const float chroma) {
/*
Six vertices for hexagon
Define periodic, circular space: red is 0, green is 2, blue is 4
*/
if(chroma <= 0.f) {
return 0.f;//By convention, to avoid divide by 0;
}
else if(max <= c.r) {//The red third, rotate [+1, -1] about datum 0;
return std::fmod((c.g - c.b) / chroma, 6.f);
}
else if(max <= c.g) {//The green third, rotate [+1, -1] about datum 2;
return (c.b - c.r) / chroma + 2.f;
}
else {//max <= c.b //The blue third, rotate [+1, -1] about datum 4;
return (c.r - c.g) / chroma + 4.f;
}
}
float hsv_saturation(const float chroma, const float value) {
if(value <= 0.f) {
return 0.f;
}
return chroma / value;//(max - min)/max
}
float hsl_saturation(const float chroma, const float lightness) {
if(lightness <= 0.f || 1.f <= lightness) {
return 0.f;
}
return chroma / (1.f - std::abs(2.f * lightness - 1.f));//(max - min)/(1 - |(max + min) - 1|)
}
glm::vec3 calc_rgb(const float C, const float min, const float h_6) {
const float X = C*(1.f - std::abs(std::fmod(h_6, 2.f) - 1.f));
if(h_6 < 1.f) {
return glm::vec3{C, X, 0.f}+min;
}
else if(h_6 < 2.f) {
return glm::vec3{X, C, 0.f}+min;
}
else if(h_6 < 3.f) {
return glm::vec3{0.f, C, X}+min;
}
else if(h_6 < 4.f) {
return glm::vec3{0.f, X, C}+min;
}
else if(h_6 < 5.f) {
return glm::vec3{X, 0.f, C}+min;
}
else {
return glm::vec3{C, 0.f, X}+min;
}
}
color4 convert(const color4&c, const color_space from_space, const color_space to_space) {
/*
RGB cube, HSV cylinder, HSL cone
In short, turn the cube so 0,0,0 is at bottom and 1,1,1 is at top.
The other 6 points of the cube project onto the corners of a hexagon.
Rotate so that red is at 0 datum.
See https://en.wikipedia.org/wiki/HSL_and_HSV for a good geometric description.
*/
if(from_space == to_space) {//A useful invariant below
return c;
}
if(from_space == color_space::rgb) {
const float min = std::min(c.r, std::min(c.g, c.b));
const float max = std::max(c.r, std::max(c.g, c.b));
const float chroma = max - min;//The normalized scale for color magnitudes
const float hue = to_hex_space(c, max, chroma) / 6.f;//Normalize six-point space to unit interval
const float val_light = to_space == color_space::hsv ? max : (max + min)*0.5f;
const float saturation = to_space == color_space::hsv ? hsv_saturation(chroma, val_light) : hsl_saturation(chroma, val_light);
return color4{hue, saturation, val_light, c.a};
}
else {
const bool is_hsv = from_space == color_space::hsv;//Otherwise HSL
const float chroma = is_hsv
? c.y*c.z//S*V
: (1.f - std::abs(2.f*c.z - 1.f))*c.y//(1 - |2*L - 1|)*S
;
const float h_6 = c.x*6.f;//To hex coordinates
const float min = is_hsv
? c.z - chroma
: c.z - chroma*0.5f
;
const glm::vec3 rgb{calc_rgb(chroma, min, h_6)};
return color4{rgb,c.a};
}
}
ORK_ORK_API const color4 red = {1., 0., 0., 1.};
ORK_ORK_API const color4 green = {0., 1., 0., 1.};
ORK_ORK_API const color4 blue = {0., 0., 1., 1.};
color4 normalized_lightness(const color4&c) {
return normalized_lightness(c, 1.f);
}
color4 normalized_lightness(const color4&c, const float one_norm) {
/*
This is waay simplified, and uses made-up linear coefficients.
Basically, yellow-green appears light and violet-blue appears dark.
*/
const float value = c.r*1.0f + c.g*1.3f + c.b*0.7f;
const glm::vec3 normed(c*one_norm / value);//For debugging
return color4(normed, c.a);//Scale colors, keep alpha
}
color4 normalized_hue(const float value) {//Value is defined on [0, 1]
/*
This is waay simplified, and uses made-up triangle distributions.
We multiply value by 1.5 instead of using thirds.
Each color should be symmetrical and occupy 1.0 width.
We narrow the green spectrum to 0.8.
*/
static ork::triangle_distribution<float>blue_l{-1.0f, -0.5f, 0.1f};//Periodicity
static ork::triangle_distribution<float>red_l{-0.5f, 0.1f, 0.5f};//0.0 should be pure red
static ork::triangle_distribution<float>green{0.1f, 0.5f, 0.9f};//0.5 is pure green
static ork::triangle_distribution<float>blue_h{0.5f, 0.9f, 1.5f};//1.0 should be pure blue
static ork::triangle_distribution<float>red_h{0.9f, 1.5f, 2.0f};//Periodicity
const float rl = red_l(value);
const float rh = red_h(value);
const float g = green(value);
const float bl = blue_l(value);
const float bh = blue_h(value);
const glm::dvec4 normed{rl + rh, g, bl + bh, 1.f};
return normed;
}
color4 normalized_red_green(const float weight) {
const float alpha = std::pow(std::max(0.f, std::min(1.f, weight)), 1.3f);
return (1.f - alpha)*red + alpha*green;
}
std::vector<color4>contrast_array(const size_t size) {
/*
1.
We want max difference between colors, garish is encouraged, so saturation is constant 100%.
As a bonus there will be no grey that might be confused with the 'base' part.
We are down to two dimensions.
2.
Colors with equal contrast with the background are percieved with equal importance.
We want equal importance and assume a white backgrond.
If only this meant constant lightness the problem would be reduced to one dimension, hue.
3.
Colors in proximity are perceived as more different.
Humans process difference more easily bwtween colors in close proximity if variation is smallish.
We can't account for spatial proximity within this function interface, but it is something to think about.
*/
std::vector<color4>retval;
LOOPI(size) {
const float val = float(i) / float(size - 1);
retval.push_back(normalized_lightness(normalized_hue(val)));
}
return std::move(retval);
}
}//namespace ork
namespace glm {
ork::o_stream&operator<<(ork::o_stream&stream, const ork::color4&c) {
stream << ORK("(") << c.r << ORK(", ") << c.g << ORK(", ") << c.b << ORK(", ") << c.a << ORK(")");
return stream;
}
}
#endif//ORK_USE_GLM
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.