text
stringlengths 54
60.6k
|
---|
<commit_before>#include <iostream>
#include "Image.hpp"
size_t Image::getIndex(size_t x, size_t y) const {
return x + width * y;
};
size_t Image::getValueFromChannel1(size_t x, size_t y) {
if (x >= width) {
x = width - 1;
}
if (y >= height) {
y = height - 1;
}
return getValueFromChannel1(getIndex(x, y));
}
size_t Image::getValueFromChannel2(size_t x, size_t y) {
if (x >= width) {
x = width - 1;
}
if (y >= height) {
y = height - 1;
}
return getValueFromChannel2(getIndex(x, y));
}
size_t Image::getValueFromChannel3(size_t x, size_t y) {
if (x >= width) {
x = width - 1;
}
if (y >= height) {
y = height - 1;
}
return getValueFromChannel3(getIndex(x, y));
}
size_t Image::getValueFromChannel1(size_t index) {
return channel1->values[(index * channel1->channelSize) / numberOfPixels];
}
size_t Image::getValueFromChannel2(size_t index) {
return channel2->values[(index * channel2->channelSize) / numberOfPixels];
}
size_t Image::getValueFromChannel3(size_t index) {
return channel3->values[(index * channel3->channelSize) / numberOfPixels];
}
void Image::setValueOnChannel1(size_t x, size_t y, size_t value) {
if (x >= width || y >= height) {
std::cout << "Cant set pixel out of range " << x << " " << y << std::endl;
return;
}
setValueOnChannel1(getIndex(x, y), value);
}
void Image::setValueOnChannel2(size_t x, size_t y, size_t value) {
if (x >= width || y >= height) {
std::cout << "Cant set pixel out of range " << x << " " << y << std::endl;
return;
}
setValueOnChannel2(getIndex(x, y), value);
}
void Image::setValueOnChannel3(size_t x, size_t y, size_t value) {
if (x >= width || y >= height) {
std::cout << "Cant set pixel out of range " << x << " " << y << std::endl;
return;
}
setValueOnChannel3(getIndex(x, y), value);
}
void Image::setValueOnChannel1(size_t index, size_t value) {
channel1->values[index] = value;
}
void Image::setValueOnChannel2(size_t index, size_t value) {
channel2->values[index] = value;
}
void Image::setValueOnChannel3(size_t index, size_t value) {
channel3->values[index] = value;
}
void Image::print() {
std::cout << "Color space: " << colorSpace;
for (int i = 0; i < width * height; ++i) {
if (i % width == 0) {
std::cout << std::endl;
}
std::cout << getValueFromChannel1( size_t (i) ) << " ";
std::cout << getValueFromChannel2( size_t (i) ) << " ";
std::cout << getValueFromChannel3( size_t (i) ) << " ";
}
std::cout << std::endl << std::endl;
}
void Image::reduceBySubSamplingChannel1(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel1->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
reducedChannel->values[i] = channel1->values[i*stepWidth];
}
*channel1 = *reducedChannel;
}
void Image::reduceBySubSamplingChannel2(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel2->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
reducedChannel->values[i] = channel2->values[i*stepWidth];
}
*channel2 = *reducedChannel;
}
void Image::reduceBySubSamplingChannel3(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel3->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
reducedChannel->values[i] = channel3->values[i*stepWidth];
}
*channel3 = *reducedChannel;
}
void Image::reduceByAveragingChannel1(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel1->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
size_t sum = 0;
for ( int k = 0; k < stepWidth; k++ )
{
sum = sum + channel1->values[i*stepWidth + k];
}
reducedChannel->values[i] = (size_t) sum / stepWidth;
}
*channel1 = *reducedChannel;
}
void Image::reduceByAveragingChannel2(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel2->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
size_t sum = 0;
for ( int k = 0; k < stepWidth; k++ )
{
sum = sum + channel2->values[i * stepWidth + k];
}
reducedChannel->values[i] = (size_t) sum / stepWidth;
}
*channel2 = *reducedChannel;
}
void Image::reduceByAveragingChannel3(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel3->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
size_t sum = 0;
for ( int k = 0; k < stepWidth; k++ )
{
sum = sum + channel3->values[i * stepWidth + k];
}
reducedChannel->values[i] = (size_t) sum / stepWidth;
}
*channel3 = *reducedChannel;
}<commit_msg>Reintroduce improved printing<commit_after>#include <iostream>
#include "Image.hpp"
size_t Image::getIndex(size_t x, size_t y) const {
return x + width * y;
};
size_t Image::getValueFromChannel1(size_t x, size_t y) {
if (x >= width) {
x = width - 1;
}
if (y >= height) {
y = height - 1;
}
return getValueFromChannel1(getIndex(x, y));
}
size_t Image::getValueFromChannel2(size_t x, size_t y) {
if (x >= width) {
x = width - 1;
}
if (y >= height) {
y = height - 1;
}
return getValueFromChannel2(getIndex(x, y));
}
size_t Image::getValueFromChannel3(size_t x, size_t y) {
if (x >= width) {
x = width - 1;
}
if (y >= height) {
y = height - 1;
}
return getValueFromChannel3(getIndex(x, y));
}
size_t Image::getValueFromChannel1(size_t index) {
return channel1->values[(index * channel1->channelSize) / numberOfPixels];
}
size_t Image::getValueFromChannel2(size_t index) {
return channel2->values[(index * channel2->channelSize) / numberOfPixels];
}
size_t Image::getValueFromChannel3(size_t index) {
return channel3->values[(index * channel3->channelSize) / numberOfPixels];
}
void Image::setValueOnChannel1(size_t x, size_t y, size_t value) {
if (x >= width || y >= height) {
std::cout << "Cant set pixel out of range " << x << " " << y << std::endl;
return;
}
setValueOnChannel1(getIndex(x, y), value);
}
void Image::setValueOnChannel2(size_t x, size_t y, size_t value) {
if (x >= width || y >= height) {
std::cout << "Cant set pixel out of range " << x << " " << y << std::endl;
return;
}
setValueOnChannel2(getIndex(x, y), value);
}
void Image::setValueOnChannel3(size_t x, size_t y, size_t value) {
if (x >= width || y >= height) {
std::cout << "Cant set pixel out of range " << x << " " << y << std::endl;
return;
}
setValueOnChannel3(getIndex(x, y), value);
}
void Image::setValueOnChannel1(size_t index, size_t value) {
channel1->values[index] = value;
}
void Image::setValueOnChannel2(size_t index, size_t value) {
channel2->values[index] = value;
}
void Image::setValueOnChannel3(size_t index, size_t value) {
channel3->values[index] = value;
}
void Image::print() {
std::cout << "Color space: " << colorSpace;
for (int i = 0; i < width * height; ++i) {
if (i % width == 0) {
std::cout << std::endl;
}
std::cout << getValueFromChannel1( size_t (i) ) << "\t";
std::cout << getValueFromChannel2( size_t (i) ) << "\t";
std::cout << getValueFromChannel3( size_t (i) ) << "\t\t";
}
std::cout << std::endl << std::endl;
}
void Image::reduceBySubSamplingChannel1(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel1->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
reducedChannel->values[i] = channel1->values[i*stepWidth];
}
*channel1 = *reducedChannel;
}
void Image::reduceBySubSamplingChannel2(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel2->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
reducedChannel->values[i] = channel2->values[i*stepWidth];
}
*channel2 = *reducedChannel;
}
void Image::reduceBySubSamplingChannel3(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel3->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
reducedChannel->values[i] = channel3->values[i*stepWidth];
}
*channel3 = *reducedChannel;
}
void Image::reduceByAveragingChannel1(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel1->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
size_t sum = 0;
for ( int k = 0; k < stepWidth; k++ )
{
sum = sum + channel1->values[i*stepWidth + k];
}
reducedChannel->values[i] = (size_t) sum / stepWidth;
}
*channel1 = *reducedChannel;
}
void Image::reduceByAveragingChannel2(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel2->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
size_t sum = 0;
for ( int k = 0; k < stepWidth; k++ )
{
sum = sum + channel2->values[i * stepWidth + k];
}
reducedChannel->values[i] = (size_t) sum / stepWidth;
}
*channel2 = *reducedChannel;
}
void Image::reduceByAveragingChannel3(size_t stepWidth) {
Channel *reducedChannel = new Channel(channel3->channelSize/stepWidth);
for ( int i = 0; i < reducedChannel->channelSize; ++i) {
size_t sum = 0;
for ( int k = 0; k < stepWidth; k++ )
{
sum = sum + channel3->values[i * stepWidth + k];
}
reducedChannel->values[i] = (size_t) sum / stepWidth;
}
*channel3 = *reducedChannel;
}<|endoftext|> |
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/system/index.hpp"
#define SUITE index
#include "test.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/detail/spawn_container_source.hpp"
#include "vast/detail/spawn_generator_source.hpp"
#include "vast/event.hpp"
#include "vast/ids.hpp"
#include "vast/query_options.hpp"
#include "fixtures/actor_system_and_events.hpp"
using caf::after;
using std::chrono_literals::operator""s;
using namespace vast;
using namespace std::chrono;
namespace {
static constexpr size_t partition_size = 100;
static constexpr size_t in_mem_partitions = 8;
static constexpr size_t taste_count = 4;
static constexpr size_t num_collectors = 1;
const timestamp epoch;
using interval = system::partition_index::interval;
auto int_generator(int mod = std::numeric_limits<int>::max()) {
int i = 0;
return [i, mod]() mutable {
auto result = event::make(i % mod, integer_type{}, i);
result.timestamp(epoch + std::chrono::seconds(i));
++i;
return result;
};
}
struct fixture : fixtures::deterministic_actor_system_and_events {
fixture() {
directory /= "index";
index = self->spawn(system::index, directory / "index", partition_size,
in_mem_partitions, taste_count, num_collectors);
}
~fixture() {
anon_send_exit(index, caf::exit_reason::user_shutdown);
}
// Returns the state of the `index`.
system::index_state& state() {
return deref<caf::stateful_actor<system::index_state>>(index).state;
}
auto partition_intervals() {
std::vector<interval> result;
for (auto& kvp : state().part_index.partitions())
result.emplace_back(kvp.second.range);
std::sort(result.begin(), result.end(),
[](auto& x, auto& y) { return x.from < y.from; });
return result;
}
auto receive_query_id() {
std::tuple<uuid, size_t, size_t> result;
self->receive(
[&](uuid& query_id, size_t hits, size_t scheduled) {
result = std::tie(query_id, hits, scheduled);
},
after(0s) >> [&] { FAIL("INDEX did not respond to query"); });
return result;
}
ids receive_result(const uuid& query_id, size_t hits, size_t scheduled) {
ids result;
size_t collected = 0;
auto fetch = [&](size_t chunk) {
for (size_t i = 0; i < chunk; ++i)
self->receive(
[&](ids& sub_result) {
++collected;
result |= sub_result;
},
after(0s) >> [&] {
FAIL("missing sub result #" << (i + 1) << " in partition #"
<< (collected + 1));
}
);
};
fetch(scheduled);
while (collected < hits) {
auto chunk = std::min(hits - collected, taste_count);
self->send(index, query_id, chunk);
run_exhaustively();
fetch(chunk);
}
return result;
}
// Handle to the INDEX actor.
caf::actor index;
};
} // namespace <anonymous>
FIXTURE_SCOPE(index_tests, fixture)
TEST(ingestion) {
MESSAGE("ingest 1000 integers");
auto src = detail::spawn_generator_source(sys, index, 1000, int_generator());
run_exhaustively();
MESSAGE("verify partition index");
REQUIRE_EQUAL(state().part_index.size(), 10u);
auto intervals = partition_intervals();
CHECK_EQUAL(intervals[0], interval(epoch, epoch + 99s));
CHECK_EQUAL(intervals[1], interval(epoch + 100s, epoch + 199s));
CHECK_EQUAL(intervals[2], interval(epoch + 200s, epoch + 299s));
CHECK_EQUAL(intervals[3], interval(epoch + 300s, epoch + 399s));
CHECK_EQUAL(intervals[4], interval(epoch + 400s, epoch + 499s));
CHECK_EQUAL(intervals[5], interval(epoch + 500s, epoch + 599s));
CHECK_EQUAL(intervals[6], interval(epoch + 600s, epoch + 699s));
CHECK_EQUAL(intervals[7], interval(epoch + 700s, epoch + 799s));
CHECK_EQUAL(intervals[8], interval(epoch + 800s, epoch + 899s));
CHECK_EQUAL(intervals[9], interval(epoch + 900s, epoch + 999s));
}
TEST(one-shot integer query result) {
MESSAGE("fill first " << taste_count << " partitions");
auto src = detail::spawn_generator_source(sys, index,
partition_size * taste_count,
int_generator(2));
run_exhaustively();
MESSAGE("query half of the values");
self->send(index, unbox(to<expression>(":int == 1")));
run_exhaustively();
auto [query_id, hits, scheduled] = receive_query_id();
CHECK_EQUAL(query_id, uuid::nil());
CHECK_EQUAL(hits, taste_count);
CHECK_EQUAL(scheduled, taste_count);
ids expected_result;
for (size_t i = 0; i < (partition_size * taste_count) / 2; ++i) {
expected_result.append_bit(false);
expected_result.append_bit(true);
}
auto result = receive_result(query_id, hits, scheduled);
CHECK_EQUAL(result, expected_result);
}
TEST(iterable integer query result) {
MESSAGE("fill first " << (taste_count * 3) << " partitions");
auto src = detail::spawn_generator_source(sys, index,
partition_size * taste_count * 3,
int_generator(2));
run_exhaustively();
MESSAGE("query half of the values");
self->send(index, unbox(to<expression>(":int == 1")));
run_exhaustively();
auto [query_id, hits, scheduled] = receive_query_id();
CHECK_NOT_EQUAL(query_id, uuid::nil());
CHECK_EQUAL(hits, taste_count * 3);
CHECK_EQUAL(scheduled, taste_count);
ids expected_result;
for (size_t i = 0; i < (partition_size * taste_count * 3) / 2; ++i) {
expected_result.append_bit(false);
expected_result.append_bit(true);
}
MESSAGE("collect results");
auto result = receive_result(query_id, hits, scheduled);
CHECK_EQUAL(result, expected_result);
}
TEST(iterable bro conn log query result) {
REQUIRE_EQUAL(bro_conn_log.size(), 8462u);
MESSAGE("ingest conn.log");
detail::spawn_container_source(sys, index, bro_conn_log);
run_exhaustively();
MESSAGE("issue historical query");
auto expected_result
= make_ids({105, 150, 246, 257, 322, 419, 440, 480, 579, 595,
642, 766, 1224, 1251, 1751, 1762, 2670, 3661, 3682, 3820,
6345, 6777, 7677, 7843, 8002, 8286, 8325, 8354},
bro_conn_log.size());
auto expr = to<expression>("service == \"http\" && :addr == 212.227.96.110");
self->send(index, unbox(expr));
run_exhaustively();
auto [query_id, hits, scheduled] = receive_query_id();
CHECK_NOT_EQUAL(query_id, uuid::nil());
auto result = receive_result(query_id, hits, scheduled);
CHECK_EQUAL(rank(expected_result), 28u);
CHECK_EQUAL(rank(result), 28u);
CHECK_EQUAL(result, expected_result);
}
FIXTURE_SCOPE_END()
<commit_msg>Extend INDEX unit test<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/system/index.hpp"
#define SUITE index
#include "test.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/std/chrono.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/detail/spawn_container_source.hpp"
#include "vast/detail/spawn_generator_source.hpp"
#include "vast/event.hpp"
#include "vast/ids.hpp"
#include "vast/query_options.hpp"
#include "fixtures/actor_system_and_events.hpp"
using caf::after;
using std::chrono_literals::operator""s;
using namespace vast;
using namespace std::chrono;
namespace {
static constexpr size_t partition_size = 100;
static constexpr size_t in_mem_partitions = 8;
static constexpr size_t taste_count = 4;
static constexpr size_t num_collectors = 1;
const timestamp epoch;
using interval = system::partition_index::interval;
auto int_generator(int mod = std::numeric_limits<int>::max()) {
int i = 0;
return [i, mod]() mutable {
auto result = event::make(i % mod, integer_type{}, i);
result.timestamp(epoch + std::chrono::seconds(i));
++i;
return result;
};
}
struct fixture : fixtures::deterministic_actor_system_and_events {
fixture() {
directory /= "index";
index = self->spawn(system::index, directory / "index", partition_size,
in_mem_partitions, taste_count, num_collectors);
}
~fixture() {
anon_send_exit(index, caf::exit_reason::user_shutdown);
}
// Returns the state of the `index`.
system::index_state& state() {
return deref<caf::stateful_actor<system::index_state>>(index).state;
}
auto partition_intervals() {
std::vector<interval> result;
for (auto& kvp : state().part_index.partitions())
result.emplace_back(kvp.second.range);
std::sort(result.begin(), result.end(),
[](auto& x, auto& y) { return x.from < y.from; });
return result;
}
auto query(std::string_view expr) {
self->send(index, unbox(to<expression>(expr)));
run_exhaustively();
std::tuple<uuid, size_t, size_t> result;
self->receive(
[&](uuid& query_id, size_t hits, size_t scheduled) {
result = std::tie(query_id, hits, scheduled);
},
after(0s) >> [&] { FAIL("INDEX did not respond to query"); });
return result;
}
ids receive_result(const uuid& query_id, size_t hits, size_t scheduled) {
if (hits == scheduled)
CHECK_EQUAL(query_id, uuid::nil());
else
CHECK_NOT_EQUAL(query_id, uuid::nil());
ids result;
size_t collected = 0;
auto fetch = [&](size_t chunk) {
for (size_t i = 0; i < chunk; ++i)
self->receive(
[&](ids& sub_result) {
++collected;
result |= sub_result;
},
after(0s) >> [&] {
FAIL("missing sub result #" << (i + 1) << " in partition #"
<< (collected + 1));
}
);
};
fetch(scheduled);
while (collected < hits) {
auto chunk = std::min(hits - collected, taste_count);
self->send(index, query_id, chunk);
run_exhaustively();
fetch(chunk);
}
return result;
}
// Handle to the INDEX actor.
caf::actor index;
};
} // namespace <anonymous>
FIXTURE_SCOPE(index_tests, fixture)
TEST(ingestion) {
MESSAGE("ingest 1000 integers");
auto src = detail::spawn_generator_source(sys, index, 1000, int_generator());
run_exhaustively();
MESSAGE("verify partition index");
REQUIRE_EQUAL(state().part_index.size(), 10u);
auto intervals = partition_intervals();
CHECK_EQUAL(intervals[0], interval(epoch, epoch + 99s));
CHECK_EQUAL(intervals[1], interval(epoch + 100s, epoch + 199s));
CHECK_EQUAL(intervals[2], interval(epoch + 200s, epoch + 299s));
CHECK_EQUAL(intervals[3], interval(epoch + 300s, epoch + 399s));
CHECK_EQUAL(intervals[4], interval(epoch + 400s, epoch + 499s));
CHECK_EQUAL(intervals[5], interval(epoch + 500s, epoch + 599s));
CHECK_EQUAL(intervals[6], interval(epoch + 600s, epoch + 699s));
CHECK_EQUAL(intervals[7], interval(epoch + 700s, epoch + 799s));
CHECK_EQUAL(intervals[8], interval(epoch + 800s, epoch + 899s));
CHECK_EQUAL(intervals[9], interval(epoch + 900s, epoch + 999s));
}
TEST(one-shot integer query result) {
MESSAGE("fill first " << taste_count << " partitions");
auto src = detail::spawn_generator_source(sys, index,
partition_size * taste_count,
int_generator(2));
run_exhaustively();
MESSAGE("query half of the values");
auto [query_id, hits, scheduled] = query(":int == 1");
CHECK_EQUAL(query_id, uuid::nil());
CHECK_EQUAL(hits, taste_count);
CHECK_EQUAL(scheduled, taste_count);
ids expected_result;
for (size_t i = 0; i < (partition_size * taste_count) / 2; ++i) {
expected_result.append_bit(false);
expected_result.append_bit(true);
}
auto result = receive_result(query_id, hits, scheduled);
CHECK_EQUAL(result, expected_result);
}
TEST(iterable integer query result) {
MESSAGE("fill first " << (taste_count * 3) << " partitions");
auto src = detail::spawn_generator_source(sys, index,
partition_size * taste_count * 3,
int_generator(2));
run_exhaustively();
MESSAGE("query half of the values");
auto [query_id, hits, scheduled] = query(":int == 1");
CHECK_NOT_EQUAL(query_id, uuid::nil());
CHECK_EQUAL(hits, taste_count * 3);
CHECK_EQUAL(scheduled, taste_count);
ids expected_result;
for (size_t i = 0; i < (partition_size * taste_count * 3) / 2; ++i) {
expected_result.append_bit(false);
expected_result.append_bit(true);
}
MESSAGE("collect results");
auto result = receive_result(query_id, hits, scheduled);
CHECK_EQUAL(result, expected_result);
}
TEST(iterable bro conn log query result) {
REQUIRE_EQUAL(bro_conn_log.size(), 8462u);
MESSAGE("ingest conn.log");
detail::spawn_container_source(sys, index, bro_conn_log);
run_exhaustively();
MESSAGE("issue field type query");
{
auto expected_result = make_ids({680, 682, 719, 720}, bro_conn_log.size());
auto [query_id, hits, scheduled] = query(":addr == 169.254.225.22");
auto result = receive_result(query_id, hits, scheduled);
for (auto id : select(result)) {
printf("%s\n", to_string(bro_conn_log[id]).c_str());
}
CHECK_EQUAL(rank(result), rank(expected_result));
CHECK_EQUAL(result, expected_result);
}
MESSAGE("issue field name query");
{
auto expected_result = make_ids({680, 682, 719, 720}, bro_conn_log.size());
auto [query_id, hits, scheduled] = query("id.orig_h == 169.254.225.22");
auto result = receive_result(query_id, hits, scheduled);
CHECK_EQUAL(rank(result), rank(expected_result));
CHECK_EQUAL(result, expected_result);
}
MESSAGE("issue historical point query with conjunction");
{
auto expected_result
= make_ids({105, 150, 246, 257, 322, 419, 440, 480, 579, 595,
642, 766, 1224, 1251, 1751, 1762, 2670, 3661, 3682, 3820,
6345, 6777, 7677, 7843, 8002, 8286, 8325, 8354},
bro_conn_log.size());
auto [query_id, hits, scheduled] = query("service == \"http\" "
"&& :addr == 212.227.96.110");
auto result = receive_result(query_id, hits, scheduled);
CHECK_EQUAL(rank(expected_result), 28u);
CHECK_EQUAL(rank(result), 28u);
CHECK_EQUAL(result, expected_result);
}
}
FIXTURE_SCOPE_END()
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <set>
#include "vsf.h"
void myscheduler(Host *host, std::set<VM> &vms);
Vsf* framework = Vsf::get_instance();
int main()
{
//set some flags to refresh optional info ahead of time.
//for optional static info, they would be collected when init_host() or init_vms() is called;
//for optional dynamic info, their collecting threads would be started when init_host() or init_vms() is called.
//the corresponding functions of optional info can be called with almost no cost;
//but if other functions are called without set corresponding flags, info would be collected immediately. It would have some performance cost depended on the collecting action/
framework->init({
//<<Optional Host Static Info>>
{ Option::OP_HS_NODE_CORE_HPTHREAD, { } },
{ Option::OP_HS_TOTAL_MEM_SIZE, { } },
{ Option::OP_HS_SYS_NODE_DIST, { } },
{ Option::OP_HS_TEST_NODE_DIST,
{
{ OptionParam::PATH, "." },
{ OptionParam::SIZE_IN_MB, 20 },
{ OptionParam::WORKLOAD_TYPE, WORKLOADTYPE_RANDOM },
{ OptionParam::LOOP, 200 }
}
},
//<<Optional Host Dynamic Info>>
{ Option::OP_HS_CPU_REUSE_RATIO, { } },
{ Option::OP_HS_CPU_USAGE, { } },
{ Option::OP_HS_USED_MEM_SIZE, { } },
//<<Optional VM Static Info>>
{ Option::OP_VM_VNODE, { } },
{ Option::OP_VM_MEM_POLICY, { } },
//<<Optional VM Dynamic Info>>
{ Option::OP_VM_BASE,
{
{ OptionParam::VM_CMD, "qemu-system-x86_64" }
}
},
{ Option::OP_VM_CPU_BINDINFO, { } },
{ Option::OP_VM_MEM_BINDINFO, { } },
{ Option::OP_VM_CPU_USAGE, { } },
{ Option::OP_VM_MISS_RATE, { } },
{ Option::OP_VM_MEM_SAMPLE, { } },
{ Option::OP_VM_USED_MEM_SIZE { } }
});
//refresh <<Optional Host Static Info>>,
//and start threads of <<Optional Host Dynamic Info>>
Host *host = framework->init_host();
while(1) {
//refresh <<Optional VM Static Info>>
//and start threads of <<Optional VM Dynamic Info>>
std::set<VM> vms = framework->init_vms(host);
std::set<VM> vms = framework->init_vms(host, "qemu-system-x86_64");
//your scheduler algorithm
myscheduler(host, vms);
framework->exec_mig(host, vms); //only host parameter may be OK?
sleep(1);
}
return 0;
}
void myscheduler(HOST *host, std::set<VM> &vms)
{
for (auto& vm : vms)
{
//INPUT: available info
//<<host static info>>
//OP_HS_NODE_CORE_HPTHREAD //Yu
host->node_num(); //DONE
host->node_ids();
host->node_id(socket_id); //DONE
host->node_id(core_id); //core_id is a struct with 2 int. It is combined with node_id & core_id.
host->node_id(hpthread_id); //DONE
host->socket_num();
host->socket_num(node_id);
host->socket_ids();
host->socket_ids(node_id);
host->socket_id(core_id);
host->socket_id(hpthread_id);
host->core_num();
host->core_num(node_id);
host->core_ids();
host->core_ids(node_id);
host->core_ids(socket_id);
host->core_id(hpthread_id);
host->hpthread_num(); //DONE
host->hpthread_num(node_id); //DONE
host->hpthread_num(core_id);
host->hpthread_ids();
host->hpthread_ids(node_id); //DONE
host->hpthread_ids(socket_id);
host->hpthread_ids(core_id);
//OP_HS_TOTAL_MEM_SIZE ((( OP_HS_NODE_CORE_HPTHREAD //Zuo
host->total_mem_size();
host->total_mem_size(node_id);
//OP_HS_SYS_NODE_DIST ((( OP_HS_NODE_CORE_HPTHREAD //Yu
host->sys_node_dist(); //DONE
host->sys_node_dist(node_id_0, node_id_1); //DONE
//OP_HS_TEST_NODE_DIST ((( OP_HS_NODE_CORE_HPTHREAD //Yu
host->test_node_dist(); //DONE
host->test_node_dist(MicroParam(".", 20, WORKLOADTYPE_RANDOM, 200)); //DONE
host->test_node_dist(node_id_0, node_id_1); //DONE
host->test_node_dist(node_id_0, node_id_1, MicroParam(".", 20, WORKLOADTYPE_RANDOM, 200)); //DONE
//<<host dynamic info>>
//OP_HS_CPU_REUSE_RATIO ((( OP_HS_NODE_CORE_HPTHREAD /Yu
host->cpu_reuse_ratio();
host->cpu_reuse_ratio(node_id);
host->cpu_reuse_ratio(socket_id);
//OP_HS_CPU_USAGE ((( OP_HS_NODE_CORE_HPTHREAD //Zuo
host->cpu_usage();
host->cpu_usage(node_id);
host->cpu_usage(socket_id);
host->cpu_usage(core_id);
host->cpu_usage(hpthread_id);
//OP_HS_USED_MEM_SIZE ((( OP_HS_NODE_CORE_HPTHREAD //Zuo
host->used_mem_size(); //DONE
host->used_mem_size(node_id); //DONE
//<<VM static info>>
//OP_VM_VNODE ((( OP_VM_BASE //Zuo
vm.vcpu_ids(vnode_id); //vNUMA //DONE
vm.vnode_num(); //vNUMA //DONE
vm.vnode_ids(); //vNUMA //DONE
//OP_VM_MEM_POLICY ((( OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.mem_policy(); //memory policy is static currently, since it is hard to implement dynamicly
vm.bindinfo_mem_node_ids();
//<<VM dynamic info>>
//OP_VM_BASE //Yu
vm.vm_id();
vm.name();//no use
vm.uuid();//no use
vm.total_mem_size();
//Host Perspective
vm.stable_vmthread_num();
vm.stable_vmthread_ids();//vcpu_ids + tgid
vm.volatile_vmthread_num();//volatile vmthreads would change frequently. Hence, its APIs always execute immediately.
vm.volatile_vmthread_ids();
//VM Perspective
vm.vcpu_num();//Currently not support maxcpus. Throw Exception
vm.vcpu_ids();
vm.vsocket_num();//no use //vsocket,vcore,vhpthread 's id may need vnuma's help
vm.vcore_num();//no use
vm.vhpthread_num();//no use
//OP_VM_CPU_BINDINFO ((( OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.bindinfo_hpthread_ids();
vm.bindinfo_hpthread_ids(vcpu_id/vmthread_id);
//OP_VM_MEM_BINDINFO ((( OP_VM_VNODE, OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.bindinfo_mem_node_id(vnode_id); //vNUMA
//OP_VM_CPU_USAGE ((( OP_VM_BASE //Yu
vm.cpu_usage();
vm.cpu_usage(vcpu_id/vmthread_id);
//OP_VM_MISS_RATE ((( OP_VM_BASE //Yu
vm.miss_rate(MISS_RATE_TYPE);
vm.miss_rate(MISS_RATE_TYPE, vcpu_id/vmthread_id);
//OP_VM_MEM_SAMPLE ((( OP_VM_BASE //Yu
vm.mem_sample(); //sample the latest visited page addr
//OP_VM_USED_MEM_SIZE ((( OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.used_mem_size();
vm.used_mem_size(node_id);
//OUTPUT: decide scheduling strategy
framework->set_vcpu_mig(vcpu_id/vmthread_id, hpthread_ids); //Yu
framework->set_mem_mig(vm_id, node_ids); //Zuo
framework->set_mem_mig(vm_id, node_ids, addr_start, page_size); //Zuo
framework->set_mem_mig(vnode_id, node_id); //vNUMA //Zuo
}
return;
}
<commit_msg>modify APIs<commit_after>#include <unistd.h>
#include <set>
#include "vsf.h"
void myscheduler(Host *host, std::set<VM> &vms);
Vsf* framework = Vsf::get_instance();
int main()
{
//set some flags to refresh optional info ahead of time.
//for optional static info, they would be collected when init_host() or init_vms() is called;
//for optional dynamic info, their collecting threads would be started when init_host() or init_vms() is called.
//the corresponding functions of optional info can be called with almost no cost;
//but if other functions are called without set corresponding flags, info would be collected immediately. It would have some performance cost depended on the collecting action/
framework->init({
//<<Optional Host Static Info>>
{ Option::OP_HS_NODE_CORE_HPTHREAD, { } },
{ Option::OP_HS_TOTAL_MEM_SIZE, { } },
{ Option::OP_HS_SYS_NODE_DIST, { } },
{ Option::OP_HS_TEST_NODE_DIST,
{
{ OptionParam::PATH, "." },
{ OptionParam::SIZE_IN_MB, 20 },
{ OptionParam::WORKLOAD_TYPE, WORKLOADTYPE_RANDOM },
{ OptionParam::LOOP, 200 }
}
},
//<<Optional Host Dynamic Info>>
{ Option::OP_HS_CPU_REUSE_RATIO, { } },
{ Option::OP_HS_CPU_USAGE, { } },
{ Option::OP_HS_USED_MEM_SIZE, { } },
//<<Optional VM Static Info>>
{ Option::OP_VM_VNODE, { } },
{ Option::OP_VM_MEM_POLICY, { } },
//<<Optional VM Dynamic Info>>
{ Option::OP_VM_BASE,
{
{ OptionParam::VM_CMD, "qemu-system-x86_64" }
}
},
{ Option::OP_VM_CPU_BINDINFO, { } },
{ Option::OP_VM_MEM_BINDINFO, { } },
{ Option::OP_VM_CPU_USAGE, { } },
{ Option::OP_VM_MISS_RATE, { } },
{ Option::OP_VM_MEM_SAMPLE, { } },
{ Option::OP_VM_USED_MEM_SIZE { } }
});
//refresh <<Optional Host Static Info>>,
//and start threads of <<Optional Host Dynamic Info>>
Host *host = framework->init_host();
while(1) {
//refresh <<Optional VM Static Info>>
//and start threads of <<Optional VM Dynamic Info>>
std::set<VM> vms = framework->init_vms(host);
std::set<VM> vms = framework->init_vms(host, "qemu-system-x86_64");
//your scheduler algorithm
myscheduler(host, vms);
framework->exec_mig(host, vms); //only host parameter may be OK?
sleep(1);
}
return 0;
}
void myscheduler(HOST *host, std::set<VM> &vms)
{
for (auto& vm : vms)
{
//INPUT: available info
//<<host static info>>
//OP_HS_NODE_CORE_HPTHREAD //Yu
host->node_num(); //DONE
host->node_ids();
host->node_id(socket_id); //DONE
host->node_id(core_id); //core_id is a struct with 2 int. It is combined with node_id & core_id.
host->node_id(hpthread_id); //DONE
host->socket_num();
host->socket_num(node_id);
host->socket_ids();
host->socket_ids(node_id);
host->socket_id(core_id);
host->socket_id(hpthread_id);
host->core_num();
host->core_num(node_id);
host->core_ids();
host->core_ids(node_id);
host->core_ids(socket_id);
host->core_id(hpthread_id);
host->hpthread_num(); //DONE
host->hpthread_num(node_id); //DONE
host->hpthread_num(core_id);
host->hpthread_ids();
host->hpthread_ids(node_id); //DONE
host->hpthread_ids(socket_id);
host->hpthread_ids(core_id);
//OP_HS_TOTAL_MEM_SIZE ((( OP_HS_NODE_CORE_HPTHREAD //Zuo
host->total_mem_size();
host->total_mem_size(node_id);
//OP_HS_SYS_NODE_DIST ((( OP_HS_NODE_CORE_HPTHREAD //Yu
host->sys_node_dist(); //DONE
host->sys_node_dist(node_id_0, node_id_1); //DONE
//OP_HS_TEST_NODE_DIST ((( OP_HS_NODE_CORE_HPTHREAD //Yu
host->test_node_dist(); //DONE
host->test_node_dist(MicroParam(".", 20, WORKLOADTYPE_RANDOM, 200)); //DONE
host->test_node_dist(node_id_0, node_id_1); //DONE
host->test_node_dist(node_id_0, node_id_1, MicroParam(".", 20, WORKLOADTYPE_RANDOM, 200)); //DONE
//<<host dynamic info>>
//OP_HS_CPU_REUSE_RATIO ((( OP_HS_NODE_CORE_HPTHREAD /Yu
host->cpu_reuse_ratio();
host->cpu_reuse_ratio(node_id);
host->cpu_reuse_ratio(socket_id);
//OP_HS_CPU_USAGE ((( OP_HS_NODE_CORE_HPTHREAD //Zuo
host->cpu_usage();
host->cpu_usage(node_id);
host->cpu_usage(socket_id);
host->cpu_usage(core_id);
host->cpu_usage(hpthread_id);
//OP_HS_USED_MEM_SIZE ((( OP_HS_NODE_CORE_HPTHREAD //Zuo
host->used_mem_size(); //DONE
host->used_mem_size(node_id); //DONE
//<<VM static info>>
//OP_VM_VNODE ((( OP_VM_BASE //Zuo
vm.vcpu_ids(vnode_id); //vNUMA //DONE
vm.vnode_num(); //vNUMA //DONE
vm.vnode_ids(); //vNUMA //DONE //VnodeId need to have a VM start timestamp, because it would be used by set_mem
//OP_VM_MEM_POLICY ((( OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.mem_policy(); //memory policy is static currently, since it is hard to implement dynamicly
vm.bindinfo_mem_node_ids();
//<<VM dynamic info>>
//OP_VM_BASE //Yu
vm.vm_id();
vm.name();//no use
vm.uuid();//no use
vm.total_mem_size();
//Host Perspective
vm.stable_vmthread_num();//typedef VmthreadId = VmId
vm.stable_vmthread_ids();//vcpu_ids + tgid
vm.volatile_vmthread_num();//volatile vmthreads would change frequently. Hence, its APIs always execute immediately.
vm.volatile_vmthread_ids();
//VM Perspective
vm.vcpu_num();//Currently not support maxcpus. Throw Exception
vm.vcpu_ids();//typedef VcpuId = VmthreadId;
vm.vsocket_num();//no use //vsocket,vcore,vhpthread 's id may need vnuma's help
vm.vcore_num();//no use
vm.vhpthread_num();//no use
//OP_VM_CPU_BINDINFO ((( OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.bindinfo_hpthread_ids();
vm.bindinfo_hpthread_ids(vcpu_id/vmthread_id);
//OP_VM_MEM_BINDINFO ((( OP_VM_VNODE, OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.bindinfo_mem_node_id(vnode_id); //vNUMA
//OP_VM_CPU_USAGE ((( OP_VM_BASE //Yu
vm.cpu_usage();
vm.cpu_usage(vcpu_id/vmthread_id);
//OP_VM_MISS_RATE ((( OP_VM_BASE //Yu
vm.miss_rate(MISS_RATE_TYPE);
vm.miss_rate(MISS_RATE_TYPE, vcpu_id/vmthread_id);
//OP_VM_MEM_SAMPLE ((( OP_VM_BASE //Yu
vm.mem_sample(); //sample the latest visited page addr
//OP_VM_USED_MEM_SIZE ((( OP_HS_NODE_CORE_HPTHREAD, OP_VM_BASE //Zuo
vm.used_mem_size();
vm.used_mem_size(node_id);
//OUTPUT: decide scheduling strategy
framework->set_vcpu_mig(vcpu_id/vmthread_id, hpthread_ids); //Yu
framework->set_mem_mig(vm_id, node_ids); //Zuo
framework->set_mem_mig(vm_id, node_ids, addr_start, page_size); //Zuo
//which one??
framework->set_mem_mig(vm_id, vnode_id, node_id); //vNUMA //Zuo
//framework->set_mem_mig(vnode_id, node_id); //vNUMA //Zuo
}
return;
}
<|endoftext|> |
<commit_before>// Formatting library for C++ - Grisu tests
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#define FMT_USE_GRISU std::numeric_limits<double>::is_iec559
#include "fmt/format.h"
#include "gtest.h"
bool reported_skipped;
#undef TEST
#define TEST(test_fixture, test_name) \
void test_fixture##test_name(); \
GTEST_TEST(test_fixture, test_name) { \
if (FMT_USE_GRISU) { \
test_fixture##test_name(); \
} else if (!reported_skipped) { \
reported_skipped = true; \
fmt::print("Skipping Grisu tests.\n"); \
} \
} \
void test_fixture##test_name()
TEST(GrisuTest, NaN) {
EXPECT_EQ("nan", fmt::format("{}", std::numeric_limits<double>::quiet_NaN()));
}
<commit_msg>Test formatting of special numbers<commit_after>// Formatting library for C++ - Grisu tests
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#define FMT_USE_GRISU std::numeric_limits<double>::is_iec559
#include "fmt/format.h"
#include "gtest.h"
bool reported_skipped;
#undef TEST
#define TEST(test_fixture, test_name) \
void test_fixture##test_name(); \
GTEST_TEST(test_fixture, test_name) { \
if (FMT_USE_GRISU) { \
test_fixture##test_name(); \
} else if (!reported_skipped) { \
reported_skipped = true; \
fmt::print("Skipping Grisu tests.\n"); \
} \
} \
void test_fixture##test_name()
TEST(GrisuTest, NaN) {
auto nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_EQ("nan", fmt::format("{}", nan));
EXPECT_EQ("-nan", fmt::format("{}", -nan));
}
TEST(GrisuTest, Inf) {
auto inf = std::numeric_limits<double>::infinity();
EXPECT_EQ("inf", fmt::format("{}", inf));
EXPECT_EQ("-inf", fmt::format("{}", -inf));
}
TEST(GrisuTest, Zero) {
EXPECT_EQ("0", fmt::format("{}", 0.0));
}
<|endoftext|> |
<commit_before>#define NEU_DISABLE_ASSERT
//#define NEU_DISABLE_ASSERT_FOR_HEAVY_CALCULATION
#include <iostream>
#include <boost/timer.hpp>
#include <boost/program_options.hpp>
#include <neu/vector_io.hpp>
#include <neu/layers_algorithm.hpp>
#include <neu/kernel.hpp>
//#include <neu/learning_rate_gen/subtract_delta_weight.hpp>
//#include <neu/learning_rate_gen/fixed_learning_rate_gen.hpp>
//#include <neu/learning_rate_gen/weight_decay.hpp>
#include <neu/learning_rate_gen/weight_decay_and_momentum.hpp>
#include <neu/activation_func/sigmoid.hpp>
#include <neu/activation_func/rectifier.hpp>
#include <neu/activation_func/identity.hpp>
#include <neu/activation_func/softmax_loss.hpp>
#include <neu/activation_layer.hpp>
#include <neu/convolution_layer.hpp>
#include <neu/max_pooling_layer.hpp>
#include <neu/average_pooling_layer.hpp>
#include <neu/fully_connected_layer.hpp>
#include <neu/layer.hpp>
#include <neu/load_data_set/load_cifar10.hpp>
#include <neu/data_set.hpp>
int main(int argc, char** argv) {
namespace po = boost::program_options;
constexpr auto label_num = 10u;
constexpr auto input_dim = 32u*32u*3u;
constexpr auto test_data_num_per_label = 1000;
int data_num_per_label;
int iteration_limit;
neu::scalar base_lr;
neu::scalar momentum;
//neu::scalar weight_decay = 0.004;
neu::scalar weight_decay;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("data_num_per_label", po::value<int>(&data_num_per_label)->default_value(10), "set number of data per label for Batch SGD")
("iteration_limit", po::value<int>(&iteration_limit)->default_value(5000), "set training iteration limit")
("base_lr", po::value<neu::scalar>(&base_lr)->default_value(0.001), "set base learning rate")
("momentum", po::value<neu::scalar>(&momentum)->default_value(0.9), "set momentum rate")
("weight_decay", po::value<neu::scalar>(&weight_decay)->default_value(0.), "set weight decay rate")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
auto batch_size = label_num * data_num_per_label;
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
std::cout << "data_num_per_label was set to " << data_num_per_label << ".";
std::cout << "(so batch_size was set to 10*" << data_num_per_label << "=" << batch_size << ".)\n";
std::cout << "iteration_limit was set to " << iteration_limit << ".\n";
std::cout << "base_lr was set to " << base_lr << ".\n";
std::cout << "momentum was set to " << momentum << ".\n";
std::cout << "weight_decay was set to " << weight_decay << ".\n";
//std::random_device rd; std::mt19937 rand(rd());
std::mt19937 rand(3); std::cout << "INFO: fixed random engine" << std::endl;
auto train_data = neu::load_cifar10_train_data("../../../data/cifar-10-batches-bin/");
for(auto& labeled : train_data) {
for(auto& d : labeled) {
std::transform(d.begin(), d.end(), d.begin(),
[](auto e){ return (e-127.); });
}
}
auto train_ds = neu::make_data_set(
label_num, data_num_per_label, input_dim, train_data, rand);
auto test_data = neu::load_cifar10_test_data("../../../data/cifar-10-batches-bin/");
for(auto& labeled : test_data) {
for(auto& d : labeled) {
std::transform(d.begin(), d.end(), d.begin(),
[](auto e){ return (e-127.); });
}
}
auto test_ds = neu::make_data_set(
label_num, test_data_num_per_label, input_dim, test_data, rand);
auto conv1_param = neu::convolution_layer_parameter()
.input_width(32).input_channel_num(3).output_channel_num(32)
.filter_width(5).stride(1).pad(2).batch_size(batch_size);
auto pool1_param = neu::make_max_pooling_layer_parameter(conv1_param)
.filter_width(3).stride(2).pad(1);
auto relu1_param = neu::make_activation_layer_parameter(pool1_param);
auto conv2_param = neu::make_convolution_layer_parameter(pool1_param)
.output_channel_num(32).filter_width(5).stride(1).pad(2);
auto relu2_param = neu::make_activation_layer_parameter(conv2_param);
auto pool2_param = neu::make_average_pooling_layer_parameter(conv2_param)
.filter_width(3).stride(2).pad(1);
auto conv3_param = neu::make_convolution_layer_parameter(pool2_param)
.output_channel_num(64).filter_width(5).stride(1).pad(2);
auto relu3_param = neu::make_activation_layer_parameter(conv3_param);
auto pool3_param = neu::make_average_pooling_layer_parameter(conv3_param)
.filter_width(3).stride(2).pad(1);
auto fc1_param = neu::make_fully_connected_layer_parameter(pool3_param)
.output_dim(64);
auto fc2_param = neu::make_fully_connected_layer_parameter(fc1_param)
.output_dim(label_num);
auto softmax_loss_param = neu::make_activation_layer_parameter(fc2_param);
auto conv1_g = [&rand, dist=std::normal_distribution<>(0.f, 0.0001f)]
() mutable { return dist(rand); };
auto conv23_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)]
() mutable { return dist(rand); };
auto fc12_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)]
() mutable { return dist(rand); };
auto constant_g = [](){ return 0.f; };
auto conv1 = neu::make_convolution_layer(conv1_param, conv1_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
conv1_param.weight_dim(), conv1_param.bias_dim()));
auto pool1 = neu::make_max_pooling_layer(pool1_param);
auto relu1 = neu::make_activation_layer<neu::rectifier>(relu1_param);
auto conv2 = neu::make_convolution_layer(conv2_param, conv23_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
conv2_param.weight_dim(), conv2_param.bias_dim()));
auto relu2 = neu::make_activation_layer<neu::rectifier>(relu2_param);
auto pool2 = neu::make_uniform_average_pooling_layer(pool2_param);
auto conv3 = neu::make_convolution_layer(conv3_param, conv23_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
conv3_param.weight_dim(), conv3_param.bias_dim()));
auto relu3 = neu::make_activation_layer<neu::rectifier>(relu3_param);
auto pool3 = neu::make_uniform_average_pooling_layer(pool3_param);
auto fc1 = neu::make_fully_connected_layer(fc1_param, fc12_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
fc1_param.weight_dim(), fc1_param.bias_dim()));
auto fc2 = neu::make_fully_connected_layer(fc2_param, fc12_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
fc2_param.weight_dim(), fc2_param.bias_dim()));
std::cout << "fc2 output dim directly: " << fc2.get_next_input().size() << std::endl;
auto softmax_loss = neu::make_activation_layer<neu::softmax_loss>(softmax_loss_param);
auto layers = std::vector<neu::layer>{
std::ref(conv1),
pool1,
relu1,
std::ref(conv2),
relu2,
pool2,
std::ref(conv3),
relu3,
pool3,
std::ref(fc1),
std::ref(fc2),
softmax_loss
};
std::ofstream mse_log("mean_square_error.txt");
std::ofstream cel_log("cross_entropy_loss.txt");
std::ofstream test_accuracy_log("test_accuracy.txt");
std::ofstream test_cel_log("test_cross_entropy_loss.txt"); std::ofstream log("log.txt");
make_next_batch(train_ds);
make_next_batch(test_ds);
boost::timer timer;
boost::timer update_timer;
for(auto i = 0; i < iteration_limit; ++i) {
timer.restart();
auto batch = train_ds.get_batch();
const auto input = batch.train_data;
const auto teach = batch.teach_data;
auto make_next_batch_future = train_ds.async_make_next_batch();
std::cout << "forward..." << std::endl;
neu::layers_forward(layers, input);
std::cout << "forward finished " << timer.elapsed() << std::endl;
auto output = layers.back().get_next_input();
auto error = neu::calc_last_layer_delta(output, teach);
std::cout << "backward..." << std::endl;
timer.restart();
neu::layers_backward(layers, error);
std::cout << "backward finished" << timer.elapsed() << std::endl;
std::cout << "update..." << std::endl;
timer.restart();
neu::layers_update(layers);
std::cout << "update finished" << timer.elapsed() << std::endl;
std::cout << "calc error..." << std::endl;
timer.restart();
auto mse = neu::mean_square_error(error);
std::cout << i << ":mean square error: " << mse << std::endl;
mse_log << i << "\t" << mse << std::endl;
auto cel = neu::cross_entropy_loss(output, teach);
cel_log << i << "\t" << cel << std::endl;
std::cout << "cross entropy loss: " << cel << std::endl;
std::cout << "error calculation finished" << timer.elapsed() << std::endl;
if(i%100 == 0) {
auto test_batch = test_ds.get_batch();
const auto test_input = batch.train_data;
const auto test_teach = batch.teach_data;
std::cout << "test forward..." << std::endl;
neu::layers_forward(layers, test_input);
std::cout << "test forward finished " << timer.elapsed() << std::endl;
auto test_output = layers.back().get_next_input();
auto test_cel = neu::cross_entropy_loss(test_output, test_teach);
test_cel_log << i << "\t" << test_cel << std::endl;
std::cout << "test cross entropy loss: " << test_cel << std::endl;
std::cout << "test error calculation finished" << timer.elapsed() << std::endl;
test_accuracy_log << neu::accuracy(
label_num, test_data_num_per_label*label_num, test_output, test_teach) << std::endl;
}
make_next_batch_future.wait();
}
}
<commit_msg>add program_option<commit_after>#define NEU_DISABLE_ASSERT
//#define NEU_DISABLE_ASSERT_FOR_HEAVY_CALCULATION
#include <iostream>
#include <boost/timer.hpp>
#include <boost/program_options.hpp>
#include <neu/vector_io.hpp>
#include <neu/layers_algorithm.hpp>
#include <neu/kernel.hpp>
//#include <neu/learning_rate_gen/subtract_delta_weight.hpp>
//#include <neu/learning_rate_gen/fixed_learning_rate_gen.hpp>
//#include <neu/learning_rate_gen/weight_decay.hpp>
#include <neu/learning_rate_gen/weight_decay_and_momentum.hpp>
#include <neu/activation_func/sigmoid.hpp>
#include <neu/activation_func/rectifier.hpp>
#include <neu/activation_func/identity.hpp>
#include <neu/activation_func/softmax_loss.hpp>
#include <neu/activation_layer.hpp>
#include <neu/convolution_layer.hpp>
#include <neu/max_pooling_layer.hpp>
#include <neu/average_pooling_layer.hpp>
#include <neu/fully_connected_layer.hpp>
#include <neu/layer.hpp>
#include <neu/load_data_set/load_cifar10.hpp>
#include <neu/data_set.hpp>
int main(int argc, char** argv) {
namespace po = boost::program_options;
constexpr auto label_num = 10u;
constexpr auto input_dim = 32u*32u*3u;
constexpr auto test_data_num_per_label = 1000;
int data_num_per_label;
int iteration_limit;
neu::scalar base_lr;
neu::scalar momentum;
//neu::scalar weight_decay = 0.004;
neu::scalar weight_decay;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("data_num_per_label", po::value<int>(&data_num_per_label)->default_value(10),
"set number of data per label for Batch SGD")
("iteration_limit", po::value<int>(&iteration_limit)->default_value(5000),
"set training iteration limit")
("base_lr", po::value<neu::scalar>(&base_lr)->default_value(0.001),
"set base learning rate")
("momentum", po::value<neu::scalar>(&momentum)->default_value(0.9),
"set momentum rate")
("weight_decay", po::value<neu::scalar>(&weight_decay)->default_value(0.),
"set weight decay rate")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
auto batch_size = label_num * data_num_per_label;
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
std::cout << "data_num_per_label was set to " << data_num_per_label << ".";
std::cout << "(so batch_size was set to 10*" << data_num_per_label
<< "=" << batch_size << ".)\n";
std::cout << "iteration_limit was set to " << iteration_limit << ".\n";
std::cout << "base_lr was set to " << base_lr << ".\n";
std::cout << "momentum was set to " << momentum << ".\n";
std::cout << "weight_decay was set to " << weight_decay << ".\n";
//std::random_device rd; std::mt19937 rand(rd());
std::mt19937 rand(3); std::cout << "INFO: fixed random engine" << std::endl;
auto train_data = neu::load_cifar10_train_data("../../../data/cifar-10-batches-bin/");
for(auto& labeled : train_data) {
for(auto& d : labeled) {
std::transform(d.begin(), d.end(), d.begin(),
[](auto e){ return (e-127.); });
}
}
auto train_ds = neu::make_data_set(
label_num, data_num_per_label, input_dim, train_data, rand);
auto test_data = neu::load_cifar10_test_data("../../../data/cifar-10-batches-bin/");
for(auto& labeled : test_data) {
for(auto& d : labeled) {
std::transform(d.begin(), d.end(), d.begin(),
[](auto e){ return (e-127.); });
}
}
auto test_ds = neu::make_data_set(
label_num, test_data_num_per_label, input_dim, test_data, rand);
auto conv1_param = neu::convolution_layer_parameter()
.input_width(32).input_channel_num(3).output_channel_num(32)
.filter_width(5).stride(1).pad(2).batch_size(batch_size);
auto pool1_param = neu::make_max_pooling_layer_parameter(conv1_param)
.filter_width(3).stride(2).pad(1);
auto relu1_param = neu::make_activation_layer_parameter(pool1_param);
auto conv2_param = neu::make_convolution_layer_parameter(pool1_param)
.output_channel_num(32).filter_width(5).stride(1).pad(2);
auto relu2_param = neu::make_activation_layer_parameter(conv2_param);
auto pool2_param = neu::make_average_pooling_layer_parameter(conv2_param)
.filter_width(3).stride(2).pad(1);
auto conv3_param = neu::make_convolution_layer_parameter(pool2_param)
.output_channel_num(64).filter_width(5).stride(1).pad(2);
auto relu3_param = neu::make_activation_layer_parameter(conv3_param);
auto pool3_param = neu::make_average_pooling_layer_parameter(conv3_param)
.filter_width(3).stride(2).pad(1);
auto fc1_param = neu::make_fully_connected_layer_parameter(pool3_param)
.output_dim(64);
auto fc2_param = neu::make_fully_connected_layer_parameter(fc1_param)
.output_dim(label_num);
auto softmax_loss_param = neu::make_activation_layer_parameter(fc2_param);
auto conv1_g = [&rand, dist=std::normal_distribution<>(0.f, 0.0001f)]
() mutable { return dist(rand); };
auto conv23_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)]
() mutable { return dist(rand); };
auto fc12_g = [&rand, dist=std::normal_distribution<>(0.f, 0.01f)]
() mutable { return dist(rand); };
auto constant_g = [](){ return 0.f; };
auto conv1 = neu::make_convolution_layer(conv1_param, conv1_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
conv1_param.weight_dim(), conv1_param.bias_dim()));
auto pool1 = neu::make_max_pooling_layer(pool1_param);
auto relu1 = neu::make_activation_layer<neu::rectifier>(relu1_param);
auto conv2 = neu::make_convolution_layer(conv2_param, conv23_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
conv2_param.weight_dim(), conv2_param.bias_dim()));
auto relu2 = neu::make_activation_layer<neu::rectifier>(relu2_param);
auto pool2 = neu::make_uniform_average_pooling_layer(pool2_param);
auto conv3 = neu::make_convolution_layer(conv3_param, conv23_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
conv3_param.weight_dim(), conv3_param.bias_dim()));
auto relu3 = neu::make_activation_layer<neu::rectifier>(relu3_param);
auto pool3 = neu::make_uniform_average_pooling_layer(pool3_param);
auto fc1 = neu::make_fully_connected_layer(fc1_param, fc12_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
fc1_param.weight_dim(), fc1_param.bias_dim()));
auto fc2 = neu::make_fully_connected_layer(fc2_param, fc12_g, constant_g,
neu::make_weight_decay_and_momentum(base_lr, momentum, weight_decay,
fc2_param.weight_dim(), fc2_param.bias_dim()));
std::cout << "fc2 output dim directly: " << fc2.get_next_input().size() << std::endl;
auto softmax_loss = neu::make_activation_layer<neu::softmax_loss>(softmax_loss_param);
auto layers = std::vector<neu::layer>{
std::ref(conv1),
pool1,
relu1,
std::ref(conv2),
relu2,
pool2,
std::ref(conv3),
relu3,
pool3,
std::ref(fc1),
std::ref(fc2),
softmax_loss
};
std::ofstream mse_log("mean_square_error.txt");
std::ofstream cel_log("cross_entropy_loss.txt");
std::ofstream test_accuracy_log("test_accuracy.txt");
std::ofstream test_cel_log("test_cross_entropy_loss.txt"); std::ofstream log("log.txt");
make_next_batch(train_ds);
make_next_batch(test_ds);
boost::timer timer;
boost::timer update_timer;
for(auto i = 0; i < iteration_limit; ++i) {
timer.restart();
auto batch = train_ds.get_batch();
const auto input = batch.train_data;
const auto teach = batch.teach_data;
auto make_next_batch_future = train_ds.async_make_next_batch();
std::cout << "forward..." << std::endl;
neu::layers_forward(layers, input);
std::cout << "forward finished " << timer.elapsed() << std::endl;
auto output = layers.back().get_next_input();
auto error = neu::calc_last_layer_delta(output, teach);
std::cout << "backward..." << std::endl;
timer.restart();
neu::layers_backward(layers, error);
std::cout << "backward finished" << timer.elapsed() << std::endl;
std::cout << "update..." << std::endl;
timer.restart();
neu::layers_update(layers);
std::cout << "update finished" << timer.elapsed() << std::endl;
std::cout << "calc error..." << std::endl;
timer.restart();
auto mse = neu::mean_square_error(error);
std::cout << i << ":mean square error: " << mse << std::endl;
mse_log << i << "\t" << mse << std::endl;
auto cel = neu::cross_entropy_loss(output, teach);
cel_log << i << "\t" << cel << std::endl;
std::cout << "cross entropy loss: " << cel << std::endl;
std::cout << "error calculation finished" << timer.elapsed() << std::endl;
/*
if(i%100 == 0) {
auto test_batch = test_ds.get_batch();
const auto test_input = batch.train_data;
const auto test_teach = batch.teach_data;
std::cout << "test forward..." << std::endl;
neu::layers_test_forward(layers, test_input);
std::cout << "test forward finished " << timer.elapsed() << std::endl;
auto test_output = layers.back().get_next_input();
auto test_cel = neu::cross_entropy_loss(test_output, test_teach);
test_cel_log << i << "\t" << test_cel << std::endl;
std::cout << "test cross entropy loss: " << test_cel << std::endl;
std::cout << "test error calculation finished" << timer.elapsed() << std::endl;
std::cout << test_output.size() << std::endl;
//test_accuracy_log << neu::accuracy(
// label_num, test_data_num_per_label*label_num, test_output, test_teach) << std::endl;
}
*/
make_next_batch_future.wait();
}
}
<|endoftext|> |
<commit_before><commit_msg>Convert FileVersionInfo NOTIMPLEMENTED()s into a bug.<commit_after><|endoftext|> |
<commit_before>
#pragma once
#include "base/push_deserializer.hpp"
#include <algorithm>
#include "glog/logging.h"
namespace principia {
using std::swap;
namespace base {
namespace internal {
inline DelegatingArrayInputStream::DelegatingArrayInputStream(
std::function<Bytes()> on_empty)
: on_empty_(std::move(on_empty)),
byte_count_(0),
position_(0),
last_returned_size_(0) {}
inline bool DelegatingArrayInputStream::Next(void const** const data,
int* const size) {
if (position_ == bytes_.size) {
// We're at the end of the array. Obtain a new one.
bytes_ = on_empty_();
position_ = 0;
last_returned_size_ = 0; // Don't let caller back up.
if (bytes_.size == 0) {
// At end of input data.
return false;
}
}
CHECK_LT(position_, bytes_.size);
last_returned_size_ = bytes_.size - position_;
*data = &bytes_.data[position_];
*size = static_cast<int>(last_returned_size_);
byte_count_ += last_returned_size_;
position_ += last_returned_size_;
return true;
}
inline void DelegatingArrayInputStream::BackUp(int const count) {
CHECK_GT(last_returned_size_, 0)
<< "BackUp() can only be called after a successful Next().";
CHECK_LE(count, last_returned_size_);
CHECK_GE(count, 0);
position_ -= count;
byte_count_ -= count;
last_returned_size_ = 0; // Don't let caller back up.
}
inline bool DelegatingArrayInputStream::Skip(int const count) {
CHECK_GE(count, 0);
last_returned_size_ = 0; // Don't let caller back up.
std::int64_t remaining = count;
while (remaining > bytes_.size - position_) {
byte_count_ += bytes_.size - position_;
remaining -= bytes_.size - position_;
// We're at the end of the array. Obtain a new one.
bytes_ = on_empty_();
position_ = 0;
if (bytes_.size == 0) {
// At end of input data.
return false;
}
}
byte_count_ += remaining;
position_ += remaining;
return true;
}
inline std::int64_t DelegatingArrayInputStream::ByteCount() const {
return byte_count_;
}
} // namespace internal
inline PushDeserializer::PushDeserializer(int const chunk_size,
int const number_of_chunks)
: chunk_size_(chunk_size),
number_of_chunks_(number_of_chunks),
stream_(std::bind(&PushDeserializer::Pull, this)) {
// This sentinel ensures that the two queue are correctly out of step.
done_.push(nullptr);
}
inline PushDeserializer::~PushDeserializer() {
if (thread_ != nullptr) {
thread_->join();
}
}
inline void PushDeserializer::Start(
not_null<std::unique_ptr<google::protobuf::Message>> message,
std::function<void(google::protobuf::Message const&)> done) {
CHECK(thread_ == nullptr);
message_ = std::move(message);
thread_ = std::make_unique<std::thread>([this, done](){
CHECK(message_->ParseFromZeroCopyStream(&stream_));
// Run any remainining chunk callback.
std::unique_lock<std::mutex> l(lock_);
CHECK_EQ(1, done_.size());
auto const done_front = done_.front();
if (done_front != nullptr) {
done_front();
}
done_.pop();
// Run the final callback.
if (done != nullptr) {
done(*message_);
}
});
}
inline void PushDeserializer::Push(Bytes const bytes,
std::function<void()> done) {
// Slice the incoming data in chunks of size at most |chunk_size|. Release
// the lock after each chunk to give the deserializer a chance to run. This
// method should be called with |bytes| of size 0 to terminate the
// deserialization, but it never generates a chunk of size 0 in other
// circumstances. The |done| callback is attached to the last chunk.
Bytes current = bytes;
CHECK_LE(0, bytes.size);
bool is_last;
do {
{
is_last = current.size <= chunk_size_;
std::unique_lock<std::mutex> l(lock_);
queue_has_room_.wait(l, [this]() {
return queue_.size() < static_cast<size_t>(number_of_chunks_);
});
queue_.emplace(current.data,
std::min(current.size,
static_cast<std::int64_t>(chunk_size_)));
done_.emplace(is_last ? std::move(done) : nullptr);
}
queue_has_elements_.notify_all();
current.data = ¤t.data[chunk_size_];
current.size -= chunk_size_;
} while (!is_last);
}
inline Bytes PushDeserializer::Pull() {
Bytes result;
{
std::unique_lock<std::mutex> l(lock_);
queue_has_elements_.wait(l, [this]() { return !queue_.empty(); });
// The front of |done_| is the callback for the |Bytes| object that was just
// processed. Run it now.
CHECK(!done_.empty());
auto const done = done_.front();
if (done != nullptr) {
done();
}
done_.pop();
// Get the next |Bytes| object to process and remove it from |queue_|.
result = queue_.front();
queue_.pop();
}
queue_has_room_.notify_all();
return result;
}
} // namespace base
} // namespace principia
<commit_msg>512 MB.<commit_after>
#pragma once
#include "base/push_deserializer.hpp"
#include <algorithm>
#include "glog/logging.h"
#include "google/protobuf/io/coded_stream_inl.h"
namespace principia {
using std::swap;
namespace base {
namespace internal {
inline DelegatingArrayInputStream::DelegatingArrayInputStream(
std::function<Bytes()> on_empty)
: on_empty_(std::move(on_empty)),
byte_count_(0),
position_(0),
last_returned_size_(0) {}
inline bool DelegatingArrayInputStream::Next(void const** const data,
int* const size) {
if (position_ == bytes_.size) {
// We're at the end of the array. Obtain a new one.
bytes_ = on_empty_();
position_ = 0;
last_returned_size_ = 0; // Don't let caller back up.
if (bytes_.size == 0) {
// At end of input data.
return false;
}
}
CHECK_LT(position_, bytes_.size);
last_returned_size_ = bytes_.size - position_;
*data = &bytes_.data[position_];
*size = static_cast<int>(last_returned_size_);
byte_count_ += last_returned_size_;
position_ += last_returned_size_;
return true;
}
inline void DelegatingArrayInputStream::BackUp(int const count) {
CHECK_GT(last_returned_size_, 0)
<< "BackUp() can only be called after a successful Next().";
CHECK_LE(count, last_returned_size_);
CHECK_GE(count, 0);
position_ -= count;
byte_count_ -= count;
last_returned_size_ = 0; // Don't let caller back up.
}
inline bool DelegatingArrayInputStream::Skip(int const count) {
CHECK_GE(count, 0);
last_returned_size_ = 0; // Don't let caller back up.
std::int64_t remaining = count;
while (remaining > bytes_.size - position_) {
byte_count_ += bytes_.size - position_;
remaining -= bytes_.size - position_;
// We're at the end of the array. Obtain a new one.
bytes_ = on_empty_();
position_ = 0;
if (bytes_.size == 0) {
// At end of input data.
return false;
}
}
byte_count_ += remaining;
position_ += remaining;
return true;
}
inline std::int64_t DelegatingArrayInputStream::ByteCount() const {
return byte_count_;
}
} // namespace internal
inline PushDeserializer::PushDeserializer(int const chunk_size,
int const number_of_chunks)
: chunk_size_(chunk_size),
number_of_chunks_(number_of_chunks),
stream_(std::bind(&PushDeserializer::Pull, this)) {
// This sentinel ensures that the two queue are correctly out of step.
done_.push(nullptr);
}
inline PushDeserializer::~PushDeserializer() {
if (thread_ != nullptr) {
thread_->join();
}
}
inline void PushDeserializer::Start(
not_null<std::unique_ptr<google::protobuf::Message>> message,
std::function<void(google::protobuf::Message const&)> done) {
CHECK(thread_ == nullptr);
message_ = std::move(message);
thread_ = std::make_unique<std::thread>([this, done]() {
// It is a well-known annoyance that, in order to set the total byte limit,
// we have to copy code from MessageLite::ParseFromZeroCopyStream. Blame
// Kenton.
google::protobuf::io::CodedInputStream decoder(&stream_);
decoder.SetTotalBytesLimit(1 << 29, 1<< 29);
CHECK(message_->ParseFromCodedStream(&decoder));
CHECK(decoder.ConsumedEntireMessage());
// Run any remainining chunk callback.
std::unique_lock<std::mutex> l(lock_);
CHECK_EQ(1, done_.size());
auto const done_front = done_.front();
if (done_front != nullptr) {
done_front();
}
done_.pop();
// Run the final callback.
if (done != nullptr) {
done(*message_);
}
});
}
inline void PushDeserializer::Push(Bytes const bytes,
std::function<void()> done) {
// Slice the incoming data in chunks of size at most |chunk_size|. Release
// the lock after each chunk to give the deserializer a chance to run. This
// method should be called with |bytes| of size 0 to terminate the
// deserialization, but it never generates a chunk of size 0 in other
// circumstances. The |done| callback is attached to the last chunk.
Bytes current = bytes;
CHECK_LE(0, bytes.size);
bool is_last;
do {
{
is_last = current.size <= chunk_size_;
std::unique_lock<std::mutex> l(lock_);
queue_has_room_.wait(l, [this]() {
return queue_.size() < static_cast<size_t>(number_of_chunks_);
});
queue_.emplace(current.data,
std::min(current.size,
static_cast<std::int64_t>(chunk_size_)));
done_.emplace(is_last ? std::move(done) : nullptr);
}
queue_has_elements_.notify_all();
current.data = ¤t.data[chunk_size_];
current.size -= chunk_size_;
} while (!is_last);
}
inline Bytes PushDeserializer::Pull() {
Bytes result;
{
std::unique_lock<std::mutex> l(lock_);
queue_has_elements_.wait(l, [this]() { return !queue_.empty(); });
// The front of |done_| is the callback for the |Bytes| object that was just
// processed. Run it now.
CHECK(!done_.empty());
auto const done = done_.front();
if (done != nullptr) {
done();
}
done_.pop();
// Get the next |Bytes| object to process and remove it from |queue_|.
result = queue_.front();
queue_.pop();
}
queue_has_room_.notify_all();
return result;
}
} // namespace base
} // namespace principia
<|endoftext|> |
<commit_before>#include <chrono>
#include <cstdint>
#include <map>
#include <string>
#include <thread>
#include <utility>
#include <uv.h>
#include "../log.h"
#include "../message_buffer.h"
#include "../result.h"
#include "../status.h"
#include "../thread.h"
#include "polled_root.h"
#include "polling_thread.h"
using std::endl;
using std::move;
using std::string;
using std::to_string;
PollingThread::PollingThread(uv_async_t *main_callback) :
Thread("polling thread", main_callback),
poll_interval{DEFAULT_POLL_INTERVAL},
poll_throttle{DEFAULT_POLL_THROTTLE}
{
//
}
void PollingThread::collect_status(Status &status)
{
status.polling_thread_state = state_name();
status.polling_thread_ok = get_error();
status.polling_in_size = get_in_queue_size();
status.polling_in_ok = get_in_queue_error();
status.polling_out_size = get_out_queue_size();
status.polling_out_ok = get_out_queue_error();
}
Result<> PollingThread::body()
{
while (true) {
LOGGER << "Handling commands." << endl;
Result<size_t> cr = handle_commands();
if (cr.is_error()) {
LOGGER << "Unable to process incoming commands: " << cr << endl;
} else if (is_stopping()) {
LOGGER << "Polling thread stopping." << endl;
return ok_result();
}
cycle();
if (is_healthy()) {
LOGGER << "Sleeping for " << poll_interval.count() << "ms." << endl;
std::this_thread::sleep_for(poll_interval);
}
}
}
Result<> PollingThread::cycle()
{
MessageBuffer buffer;
size_t remaining = poll_throttle;
size_t roots_left = roots.size();
LOGGER << "Polling " << plural(roots_left, "root") << " with " << plural(poll_throttle, "throttle slot") << "."
<< endl;
for (auto &it : roots) {
PolledRoot &root = it.second;
size_t allotment = remaining / roots_left;
LOGGER << "Polling " << root << " with an allotment of " << plural(allotment, "throttle slot") << "." << endl;
size_t progress = root.advance(buffer, allotment);
remaining -= progress;
if (progress != allotment) {
LOGGER << root << " only consumed " << plural(progress, "throttle slot") << "." << endl;
}
roots_left--;
}
// Ack any commands whose roots are now fully populated.
for (auto &split : pending_splits) {
const ChannelID &channel_id = split.first;
const PendingSplit &pending_split = split.second;
size_t populated_roots = 0;
auto channel_roots = roots.equal_range(channel_id);
for (auto root = channel_roots.first; root != channel_roots.second; ++root) {
if (root->second.is_all_populated()) populated_roots++;
}
if (populated_roots >= pending_split.second) {
buffer.ack(pending_split.first, channel_id, true, "");
pending_splits.erase(channel_id);
}
}
return emit_all(buffer.begin(), buffer.end());
}
Result<Thread::OfflineCommandOutcome> PollingThread::handle_offline_command(const CommandPayload *command)
{
Result<OfflineCommandOutcome> r = Thread::handle_offline_command(command);
if (r.is_error()) return r;
if (command->get_action() == COMMAND_ADD) {
return ok_result(TRIGGER_RUN);
}
if (command->get_action() == COMMAND_POLLING_INTERVAL) {
handle_polling_interval_command(command);
}
if (command->get_action() == COMMAND_POLLING_THROTTLE) {
handle_polling_throttle_command(command);
}
return ok_result(OFFLINE_ACK);
}
Result<Thread::CommandOutcome> PollingThread::handle_add_command(const CommandPayload *command)
{
LOGGER << "Adding poll root at path " << command->get_root() << " to channel " << command->get_channel_id()
<< " with " << plural(command->get_split_count(), "split") << "." << endl;
roots.emplace(std::piecewise_construct,
std::forward_as_tuple(command->get_channel_id()),
std::forward_as_tuple(string(command->get_root()), command->get_channel_id()));
auto existing = pending_splits.find(command->get_channel_id());
if (existing != pending_splits.end()) {
bool inconsistent = false;
string msg("Inconsistent split ADD command received by polling thread: ");
const CommandID &existing_command_id = existing->second.first;
const size_t &split_count = existing->second.second;
if (existing_command_id != command->get_id()) {
inconsistent = true;
msg += " command ID (";
msg += to_string(existing_command_id);
msg += " => ";
msg += to_string(command->get_id());
msg += ")";
}
if (split_count != command->get_split_count()) {
if (inconsistent) {
msg += " and";
}
msg += " split count (";
msg += to_string(split_count);
msg += " => ";
msg += to_string(command->get_split_count());
msg += ")";
}
if (inconsistent) {
return Result<CommandOutcome>::make_error(move(msg));
}
return ok_result(NOTHING);
}
if (command->get_id() != NULL_COMMAND_ID) {
pending_splits.emplace(std::piecewise_construct,
std::forward_as_tuple(command->get_channel_id()),
std::forward_as_tuple(command->get_id(), command->get_split_count()));
if (command->get_split_count() == 0u) {
return ok_result(ACK);
}
}
return ok_result(NOTHING);
}
Result<Thread::CommandOutcome> PollingThread::handle_remove_command(const CommandPayload *command)
{
const ChannelID &channel_id = command->get_channel_id();
LOGGER << "Removing poll roots at channel " << channel_id << "." << endl;
roots.erase(command->get_channel_id());
// Ensure that we ack the ADD command even if the REMOVE command arrives before all of its splits populate.
auto pending = pending_splits.find(channel_id);
if (pending != pending_splits.end()) {
const PendingSplit &split = pending->second;
const CommandID &add_command_id = split.first;
Result<> r0 = emit(Message(AckPayload(add_command_id, channel_id, false, "Command cancelled")));
pending_splits.erase(pending);
if (r0.is_error()) return r0.propagate<CommandOutcome>();
}
if (roots.empty()) {
LOGGER << "Final root removed." << endl;
return ok_result(TRIGGER_STOP);
}
return ok_result(ACK);
}
Result<Thread::CommandOutcome> PollingThread::handle_polling_interval_command(const CommandPayload *command)
{
poll_interval = std::chrono::milliseconds(command->get_arg());
return ok_result(ACK);
}
Result<Thread::CommandOutcome> PollingThread::handle_polling_throttle_command(const CommandPayload *command)
{
poll_throttle = command->get_arg();
return ok_result(ACK);
}
<commit_msg>MacOS doesn't like erasing the current element<commit_after>#include <chrono>
#include <cstdint>
#include <map>
#include <vector>
#include <string>
#include <thread>
#include <utility>
#include <uv.h>
#include "../log.h"
#include "../message_buffer.h"
#include "../result.h"
#include "../status.h"
#include "../thread.h"
#include "polled_root.h"
#include "polling_thread.h"
using std::endl;
using std::move;
using std::string;
using std::vector;
using std::to_string;
PollingThread::PollingThread(uv_async_t *main_callback) :
Thread("polling thread", main_callback),
poll_interval{DEFAULT_POLL_INTERVAL},
poll_throttle{DEFAULT_POLL_THROTTLE}
{
//
}
void PollingThread::collect_status(Status &status)
{
status.polling_thread_state = state_name();
status.polling_thread_ok = get_error();
status.polling_in_size = get_in_queue_size();
status.polling_in_ok = get_in_queue_error();
status.polling_out_size = get_out_queue_size();
status.polling_out_ok = get_out_queue_error();
}
Result<> PollingThread::body()
{
while (true) {
LOGGER << "Handling commands." << endl;
Result<size_t> cr = handle_commands();
if (cr.is_error()) {
LOGGER << "Unable to process incoming commands: " << cr << endl;
} else if (is_stopping()) {
LOGGER << "Polling thread stopping." << endl;
return ok_result();
}
cycle();
if (is_healthy()) {
LOGGER << "Sleeping for " << poll_interval.count() << "ms." << endl;
std::this_thread::sleep_for(poll_interval);
}
}
}
Result<> PollingThread::cycle()
{
MessageBuffer buffer;
size_t remaining = poll_throttle;
size_t roots_left = roots.size();
LOGGER << "Polling " << plural(roots_left, "root") << " with " << plural(poll_throttle, "throttle slot") << "."
<< endl;
for (auto &it : roots) {
PolledRoot &root = it.second;
size_t allotment = remaining / roots_left;
LOGGER << "Polling " << root << " with an allotment of " << plural(allotment, "throttle slot") << "." << endl;
size_t progress = root.advance(buffer, allotment);
remaining -= progress;
if (progress != allotment) {
LOGGER << root << " only consumed " << plural(progress, "throttle slot") << "." << endl;
}
roots_left--;
}
// Ack any commands whose roots are now fully populated.
vector<ChannelID> to_erase;
for (auto &split : pending_splits) {
const ChannelID &channel_id = split.first;
const PendingSplit &pending_split = split.second;
size_t populated_roots = 0;
auto channel_roots = roots.equal_range(channel_id);
for (auto root = channel_roots.first; root != channel_roots.second; ++root) {
if (root->second.is_all_populated()) populated_roots++;
}
if (populated_roots >= pending_split.second) {
buffer.ack(pending_split.first, channel_id, true, "");
to_erase.push_back(channel_id);
}
}
for (ChannelID &channel_id : to_erase) {
pending_splits.erase(channel_id);
}
return emit_all(buffer.begin(), buffer.end());
}
Result<Thread::OfflineCommandOutcome> PollingThread::handle_offline_command(const CommandPayload *command)
{
Result<OfflineCommandOutcome> r = Thread::handle_offline_command(command);
if (r.is_error()) return r;
if (command->get_action() == COMMAND_ADD) {
return ok_result(TRIGGER_RUN);
}
if (command->get_action() == COMMAND_POLLING_INTERVAL) {
handle_polling_interval_command(command);
}
if (command->get_action() == COMMAND_POLLING_THROTTLE) {
handle_polling_throttle_command(command);
}
return ok_result(OFFLINE_ACK);
}
Result<Thread::CommandOutcome> PollingThread::handle_add_command(const CommandPayload *command)
{
LOGGER << "Adding poll root at path " << command->get_root() << " to channel " << command->get_channel_id()
<< " with " << plural(command->get_split_count(), "split") << "." << endl;
roots.emplace(std::piecewise_construct,
std::forward_as_tuple(command->get_channel_id()),
std::forward_as_tuple(string(command->get_root()), command->get_channel_id()));
auto existing = pending_splits.find(command->get_channel_id());
if (existing != pending_splits.end()) {
bool inconsistent = false;
string msg("Inconsistent split ADD command received by polling thread: ");
const CommandID &existing_command_id = existing->second.first;
const size_t &split_count = existing->second.second;
if (existing_command_id != command->get_id()) {
inconsistent = true;
msg += " command ID (";
msg += to_string(existing_command_id);
msg += " => ";
msg += to_string(command->get_id());
msg += ")";
}
if (split_count != command->get_split_count()) {
if (inconsistent) {
msg += " and";
}
msg += " split count (";
msg += to_string(split_count);
msg += " => ";
msg += to_string(command->get_split_count());
msg += ")";
}
if (inconsistent) {
return Result<CommandOutcome>::make_error(move(msg));
}
return ok_result(NOTHING);
}
if (command->get_id() != NULL_COMMAND_ID) {
pending_splits.emplace(std::piecewise_construct,
std::forward_as_tuple(command->get_channel_id()),
std::forward_as_tuple(command->get_id(), command->get_split_count()));
if (command->get_split_count() == 0u) {
return ok_result(ACK);
}
}
return ok_result(NOTHING);
}
Result<Thread::CommandOutcome> PollingThread::handle_remove_command(const CommandPayload *command)
{
const ChannelID &channel_id = command->get_channel_id();
LOGGER << "Removing poll roots at channel " << channel_id << "." << endl;
roots.erase(command->get_channel_id());
// Ensure that we ack the ADD command even if the REMOVE command arrives before all of its splits populate.
auto pending = pending_splits.find(channel_id);
if (pending != pending_splits.end()) {
const PendingSplit &split = pending->second;
const CommandID &add_command_id = split.first;
Result<> r0 = emit(Message(AckPayload(add_command_id, channel_id, false, "Command cancelled")));
pending_splits.erase(pending);
if (r0.is_error()) return r0.propagate<CommandOutcome>();
}
if (roots.empty()) {
LOGGER << "Final root removed." << endl;
return ok_result(TRIGGER_STOP);
}
return ok_result(ACK);
}
Result<Thread::CommandOutcome> PollingThread::handle_polling_interval_command(const CommandPayload *command)
{
poll_interval = std::chrono::milliseconds(command->get_arg());
return ok_result(ACK);
}
Result<Thread::CommandOutcome> PollingThread::handle_polling_throttle_command(const CommandPayload *command)
{
poll_throttle = command->get_arg();
return ok_result(ACK);
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkThread.h"
#include <pthread.h>
#include <errno.h>
#ifndef SK_BUILD_FOR_ANDROID
/**
We prefer the GCC intrinsic implementation of the atomic operations over the
SkMutex-based implementation. The SkMutex version suffers from static
destructor ordering problems.
Note clang also defines the GCC version macros and implements the intrinsics.
TODO: Verify that gcc-style __sync_* intrinsics work on ARM
According to this the intrinsics are supported on ARM in LLVM 2.7+
http://llvm.org/releases/2.7/docs/ReleaseNotes.html
*/
#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || __GNUC__ > 4
#if (defined(__x86_64) || defined(__i386__))
#define GCC_INTRINSIC
#endif
#endif
#if defined(GCC_INTRINSIC)
int32_t sk_atomic_inc(int32_t* addr)
{
return __sync_fetch_and_add(addr, 1);
}
int32_t sk_atomic_dec(int32_t* addr)
{
return __sync_fetch_and_add(addr, -1);
}
#else
SkMutex gAtomicMutex;
int32_t sk_atomic_inc(int32_t* addr)
{
SkAutoMutexAcquire ac(gAtomicMutex);
int32_t value = *addr;
*addr = value + 1;
return value;
}
int32_t sk_atomic_dec(int32_t* addr)
{
SkAutoMutexAcquire ac(gAtomicMutex);
int32_t value = *addr;
*addr = value - 1;
return value;
}
#endif
#endif // SK_BUILD_FOR_ANDROID
//////////////////////////////////////////////////////////////////////////////
static void print_pthread_error(int status) {
switch (status) {
case 0: // success
break;
case EINVAL:
SkDebugf("pthread error [%d] EINVAL\n", status);
break;
case EBUSY:
SkDebugf("pthread error [%d] EBUSY\n", status);
break;
default:
SkDebugf("pthread error [%d] unknown\n", status);
break;
}
}
#ifdef SK_USE_POSIX_THREADS
SkMutex::SkMutex() {
int status;
status = pthread_mutex_init(&fMutex, NULL);
if (status != 0) {
print_pthread_error(status);
SkASSERT(0 == status);
}
}
SkMutex::~SkMutex() {
int status = pthread_mutex_destroy(&fMutex);
// only report errors on non-global mutexes
if (status != 0) {
print_pthread_error(status);
SkASSERT(0 == status);
}
}
#else // !SK_USE_POSIX_THREADS
SkMutex::SkMutex() {
if (sizeof(pthread_mutex_t) > sizeof(fStorage)) {
SkDEBUGF(("pthread mutex size = %d\n", sizeof(pthread_mutex_t)));
SkDEBUGFAIL("mutex storage is too small");
}
int status;
pthread_mutexattr_t attr;
status = pthread_mutexattr_init(&attr);
print_pthread_error(status);
SkASSERT(0 == status);
status = pthread_mutex_init((pthread_mutex_t*)fStorage, &attr);
print_pthread_error(status);
SkASSERT(0 == status);
}
SkMutex::~SkMutex() {
int status = pthread_mutex_destroy((pthread_mutex_t*)fStorage);
#if 0
// only report errors on non-global mutexes
if (!fIsGlobal) {
print_pthread_error(status);
SkASSERT(0 == status);
}
#endif
}
void SkMutex::acquire() {
int status = pthread_mutex_lock((pthread_mutex_t*)fStorage);
print_pthread_error(status);
SkASSERT(0 == status);
}
void SkMutex::release() {
int status = pthread_mutex_unlock((pthread_mutex_t*)fStorage);
print_pthread_error(status);
SkASSERT(0 == status);
}
#endif // !SK_USE_POSIX_THREADS
///////////////////////////////////////////////////////////////////////////////
static pthread_key_t gSkTLSKey;
static pthread_once_t gSkTLSKey_Once = PTHREAD_ONCE_INIT;
static void sk_tls_make_key() {
(void)pthread_key_create(&gSkTLSKey, SkTLS::Destructor);
}
void* SkTLS::PlatformGetSpecific() {
(void)pthread_once(&gSkTLSKey_Once, sk_tls_make_key);
return pthread_getspecific(gSkTLSKey);
}
void SkTLS::PlatformSetSpecific(void* ptr) {
(void)pthread_setspecific(gSkTLSKey, ptr);
}
<commit_msg>must include SkTLS.h<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkThread.h"
#include "SkTLS.h"
#include <pthread.h>
#include <errno.h>
#ifndef SK_BUILD_FOR_ANDROID
/**
We prefer the GCC intrinsic implementation of the atomic operations over the
SkMutex-based implementation. The SkMutex version suffers from static
destructor ordering problems.
Note clang also defines the GCC version macros and implements the intrinsics.
TODO: Verify that gcc-style __sync_* intrinsics work on ARM
According to this the intrinsics are supported on ARM in LLVM 2.7+
http://llvm.org/releases/2.7/docs/ReleaseNotes.html
*/
#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || __GNUC__ > 4
#if (defined(__x86_64) || defined(__i386__))
#define GCC_INTRINSIC
#endif
#endif
#if defined(GCC_INTRINSIC)
int32_t sk_atomic_inc(int32_t* addr)
{
return __sync_fetch_and_add(addr, 1);
}
int32_t sk_atomic_dec(int32_t* addr)
{
return __sync_fetch_and_add(addr, -1);
}
#else
SkMutex gAtomicMutex;
int32_t sk_atomic_inc(int32_t* addr)
{
SkAutoMutexAcquire ac(gAtomicMutex);
int32_t value = *addr;
*addr = value + 1;
return value;
}
int32_t sk_atomic_dec(int32_t* addr)
{
SkAutoMutexAcquire ac(gAtomicMutex);
int32_t value = *addr;
*addr = value - 1;
return value;
}
#endif
#endif // SK_BUILD_FOR_ANDROID
//////////////////////////////////////////////////////////////////////////////
static void print_pthread_error(int status) {
switch (status) {
case 0: // success
break;
case EINVAL:
SkDebugf("pthread error [%d] EINVAL\n", status);
break;
case EBUSY:
SkDebugf("pthread error [%d] EBUSY\n", status);
break;
default:
SkDebugf("pthread error [%d] unknown\n", status);
break;
}
}
#ifdef SK_USE_POSIX_THREADS
SkMutex::SkMutex() {
int status;
status = pthread_mutex_init(&fMutex, NULL);
if (status != 0) {
print_pthread_error(status);
SkASSERT(0 == status);
}
}
SkMutex::~SkMutex() {
int status = pthread_mutex_destroy(&fMutex);
// only report errors on non-global mutexes
if (status != 0) {
print_pthread_error(status);
SkASSERT(0 == status);
}
}
#else // !SK_USE_POSIX_THREADS
SkMutex::SkMutex() {
if (sizeof(pthread_mutex_t) > sizeof(fStorage)) {
SkDEBUGF(("pthread mutex size = %d\n", sizeof(pthread_mutex_t)));
SkDEBUGFAIL("mutex storage is too small");
}
int status;
pthread_mutexattr_t attr;
status = pthread_mutexattr_init(&attr);
print_pthread_error(status);
SkASSERT(0 == status);
status = pthread_mutex_init((pthread_mutex_t*)fStorage, &attr);
print_pthread_error(status);
SkASSERT(0 == status);
}
SkMutex::~SkMutex() {
int status = pthread_mutex_destroy((pthread_mutex_t*)fStorage);
#if 0
// only report errors on non-global mutexes
if (!fIsGlobal) {
print_pthread_error(status);
SkASSERT(0 == status);
}
#endif
}
void SkMutex::acquire() {
int status = pthread_mutex_lock((pthread_mutex_t*)fStorage);
print_pthread_error(status);
SkASSERT(0 == status);
}
void SkMutex::release() {
int status = pthread_mutex_unlock((pthread_mutex_t*)fStorage);
print_pthread_error(status);
SkASSERT(0 == status);
}
#endif // !SK_USE_POSIX_THREADS
///////////////////////////////////////////////////////////////////////////////
static pthread_key_t gSkTLSKey;
static pthread_once_t gSkTLSKey_Once = PTHREAD_ONCE_INIT;
static void sk_tls_make_key() {
(void)pthread_key_create(&gSkTLSKey, SkTLS::Destructor);
}
void* SkTLS::PlatformGetSpecific() {
(void)pthread_once(&gSkTLSKey_Once, sk_tls_make_key);
return pthread_getspecific(gSkTLSKey);
}
void SkTLS::PlatformSetSpecific(void* ptr) {
(void)pthread_setspecific(gSkTLSKey, ptr);
}
<|endoftext|> |
<commit_before><?hh //strict
namespace Diff;
use HackPack\HackUnit\Core\Expectation;
use HackPack\HackUnit\Core\TestCase;
class DifferTest extends TestCase
{
public function testDiffReturnsStringOutput(): void
{
$expected = "--- Original\n+++ New\n@@ @@\n-bc\n+abc\n";
$differ = new Differ();
$actual = $differ->diff("bc", "abc");
$this->expect($actual)->toEqual($expected);
}
public function testDiffReturnsDifferentHeader(): void
{
$customHeader = "--- Expected\n+++ Actual\n";
$expected = $customHeader."@@ @@\n-bc\n+abc\n";
$differ = new Differ($customHeader);
$actual = $differ->diff("bc", "abc");
$this->expect($actual)->toEqual($expected);
}
public function testDiffReturnsStringVsArrayOutput():void
{
$string = "Hello World";
$array = [];
$expected = "--- Original\n+++ New\n@@ @@\n-<string> $string\n+<array>\n";
$differ = new Differ();
$actual = $differ->diff($string, $array);
$this->expect($actual)->toEqual($expected);
}
}
<commit_msg>Remove old test<commit_after><?hh //strict
namespace Diff;
use HackPack\HackUnit\Core\Expectation;
use HackPack\HackUnit\Core\TestCase;
class DifferTest extends TestCase
{
public function testDiffReturnsStringOutput(): void
{
$expected = "--- Original\n+++ New\n@@ @@\n-bc\n+abc\n";
$differ = new Differ();
$actual = $differ->diff("bc", "abc");
$this->expect($actual)->toEqual($expected);
}
public function testDiffReturnsDifferentHeader(): void
{
$customHeader = "--- Expected\n+++ Actual\n";
$expected = $customHeader."@@ @@\n-bc\n+abc\n";
$differ = new Differ($customHeader);
$actual = $differ->diff("bc", "abc");
$this->expect($actual)->toEqual($expected);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2009 Dan Leinir Turthra Jensen <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "metainfo.h"
#include "gluonobject.h"
using namespace GluonCore;
class MetaInfo::MetaInfoPrivate
{
public:
MetaInfoPrivate() {};
~MetaInfoPrivate() {};
QHash<QString, qreal> propertyRangeMin;
QHash<QString, qreal> propertyRangeMax;
QHash<QString, quint32> propertySteps;
};
MetaInfo::MetaInfo(GluonObject* parent)
: QObject(parent)
, d(new MetaInfoPrivate())
{
}
MetaInfo::MetaInfo(const GluonCore::MetaInfo& other)
{
delete(d);
}
MetaInfo::~MetaInfo()
{
}
void
MetaInfo::setPropertyRange(const QString& property, qreal min, qreal max)
{
d->propertyRangeMin.insert(property, min);
d->propertyRangeMax.insert(property, max);
}
bool
MetaInfo::hasPropertyRange(const QString& property) const
{
return d->propertyRangeMin.keys().contains(property);
}
qreal
MetaInfo::propertyRangeMin(const QString& property) const
{
// This will return 0 if we do not have a property range for this property
// name - but anybody using it should have checked beforehand
return d->propertyRangeMin.value(property);
}
qreal
MetaInfo::propertyRangeMax(const QString& property) const
{
// This will return 0 if we do not have a property range for this property
// name - but anybody using it should have checked beforehand
return d->propertyRangeMax.value(property);
}
void
MetaInfo::removePropertyRange(const QString& property)
{
d->propertyRangeMin.remove(property);
d->propertyRangeMax.remove(property);
}
qreal
MetaInfo::applyRange(const QString& property, qreal newValue) const
{
if(!hasPropertyRange(property))
return newValue;
qBound(d->propertyRangeMin[property], newValue, d->propertyRangeMax[property]);
}
void
MetaInfo::setPropertySteps(const QString& property, quint32 steps)
{
d->propertySteps.insert(property, steps);
}
bool
MetaInfo::hasPropertySteps(const QString& property) const
{
return d->propertySteps.keys().contains(property);
}
quint32
MetaInfo::propertySteps(const QString& property) const
{
// This will return 0 if we do not have a property step for this property
// name - but anybody using it should have checked beforehand
return d->propertySteps.value(property);
}
void
MetaInfo::removePropertySteps(const QString& property)
{
d->propertySteps.remove(property);
}
qreal
MetaInfo::applySteps(const QString& property, qreal newValue) const
{
if(!hasPropertySteps(property) || !hasPropertyRange(property))
return newValue;
// Bit of help from Morten Justesen on this one, nice bit of mathematics ;)
const qreal step = (d->propertyRangeMax.value(property) - d->propertyRangeMin.value(property)) / d->propertySteps.value(property);
return qRound64(newValue / step) * step;
}
qreal
MetaInfo::applyRangeAndStep(const QString& property, qreal newValue) const
{
if(!hasPropertySteps(property) || !hasPropertyRange(property))
return newValue;
// Bit of help from Morten Justesen on this one, nice bit of mathematics ;)
const qreal step = (d->propertyRangeMax.value(property) - d->propertyRangeMin.value(property)) / d->propertySteps.value(property);
return qRound64(qBound(d->propertyRangeMin[property], newValue, d->propertyRangeMax[property]) / step) * step;
}
#include "metainfo.moc"
<commit_msg>Fix RPMLINT warning<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2009 Dan Leinir Turthra Jensen <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "metainfo.h"
#include "gluonobject.h"
using namespace GluonCore;
class MetaInfo::MetaInfoPrivate
{
public:
MetaInfoPrivate() {};
~MetaInfoPrivate() {};
QHash<QString, qreal> propertyRangeMin;
QHash<QString, qreal> propertyRangeMax;
QHash<QString, quint32> propertySteps;
};
MetaInfo::MetaInfo(GluonObject* parent)
: QObject(parent)
, d(new MetaInfoPrivate())
{
}
MetaInfo::MetaInfo(const GluonCore::MetaInfo& other)
{
delete(d);
}
MetaInfo::~MetaInfo()
{
}
void
MetaInfo::setPropertyRange(const QString& property, qreal min, qreal max)
{
d->propertyRangeMin.insert(property, min);
d->propertyRangeMax.insert(property, max);
}
bool
MetaInfo::hasPropertyRange(const QString& property) const
{
return d->propertyRangeMin.keys().contains(property);
}
qreal
MetaInfo::propertyRangeMin(const QString& property) const
{
// This will return 0 if we do not have a property range for this property
// name - but anybody using it should have checked beforehand
return d->propertyRangeMin.value(property);
}
qreal
MetaInfo::propertyRangeMax(const QString& property) const
{
// This will return 0 if we do not have a property range for this property
// name - but anybody using it should have checked beforehand
return d->propertyRangeMax.value(property);
}
void
MetaInfo::removePropertyRange(const QString& property)
{
d->propertyRangeMin.remove(property);
d->propertyRangeMax.remove(property);
}
qreal
MetaInfo::applyRange(const QString& property, qreal newValue) const
{
if(!hasPropertyRange(property))
return newValue;
qBound(d->propertyRangeMin[property], newValue, d->propertyRangeMax[property]);
return 0;
}
void
MetaInfo::setPropertySteps(const QString& property, quint32 steps)
{
d->propertySteps.insert(property, steps);
}
bool
MetaInfo::hasPropertySteps(const QString& property) const
{
return d->propertySteps.keys().contains(property);
}
quint32
MetaInfo::propertySteps(const QString& property) const
{
// This will return 0 if we do not have a property step for this property
// name - but anybody using it should have checked beforehand
return d->propertySteps.value(property);
}
void
MetaInfo::removePropertySteps(const QString& property)
{
d->propertySteps.remove(property);
}
qreal
MetaInfo::applySteps(const QString& property, qreal newValue) const
{
if(!hasPropertySteps(property) || !hasPropertyRange(property))
return newValue;
// Bit of help from Morten Justesen on this one, nice bit of mathematics ;)
const qreal step = (d->propertyRangeMax.value(property) - d->propertyRangeMin.value(property)) / d->propertySteps.value(property);
return qRound64(newValue / step) * step;
}
qreal
MetaInfo::applyRangeAndStep(const QString& property, qreal newValue) const
{
if(!hasPropertySteps(property) || !hasPropertyRange(property))
return newValue;
// Bit of help from Morten Justesen on this one, nice bit of mathematics ;)
const qreal step = (d->propertyRangeMax.value(property) - d->propertyRangeMin.value(property)) / d->propertySteps.value(property);
return qRound64(qBound(d->propertyRangeMin[property], newValue, d->propertyRangeMax[property]) / step) * step;
}
#include "metainfo.moc"
<|endoftext|> |
<commit_before>/*
kissStepper - a lightweight library for the Easy Driver, Big Easy Driver, Allegro stepper motor drivers and others that use a Step/Dir interface
Written by Rylee Isitt. September 21, 2015
License: GNU Lesser General Public License (LGPL) V2.1
Despite the existence of several excellent libraries for driving stepper motors, I created this one to fulfill the following needs:
- Simplicity
- Handling of enable, step, and dir pins
- Based around an external loop
- Approximately linear acceleration using a fast algorithm
- High step frequency (or reasonably so, given the overhead involved)
- Use AVR/ARM libraries and port access to increase performance while keeping the API Arduino-friendly
- Teensy (Teensyduino) compatibility
Acceleration approximation math is based on Aryeh Eiderman's "Real Time Stepper Motor Linear Ramping Just by Addition and Multiplication", available at http://hwml.com/LeibRamp.pdf
*/
/*
Optimization notes:
- Keeping an integer copy of stepInterval improves performance at a cost of some memory
- Making stepInterval an integer instead of float greatly decreases accuracy of accel/decel and doesn't make a noticeable difference in performance
*/
#include "kissStepper.h"
#ifndef TEENSYDUINO
#include <util/delay_basic.h>
#endif
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// kissStepper without acceleration
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
kissStepperNoAccel::kissStepperNoAccel(uint8_t PIN_DIR, uint8_t PIN_STEP, uint8_t PIN_ENABLE) :
m_forwardLimit(DEFAULT_FORWARD_LIMIT),
m_reverseLimit(DEFAULT_REVERSE_LIMIT),
m_maxSpeed(DEFAULT_SPEED),
PIN_DIR(PIN_DIR),
PIN_STEP(PIN_STEP),
PIN_ENABLE(PIN_ENABLE),
m_distMoved(0),
m_pos(0),
m_stepBit(digitalPinToBitMask(PIN_STEP)),
m_stepOut(portOutputRegister(digitalPinToPort(PIN_STEP)))
{}
// ----------------------------------------------------------------------------------------------------
// Initialize the motor in a default state
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::begin(void)
{
// set pins to output
pinMode(PIN_DIR, OUTPUT);
pinMode(PIN_STEP, OUTPUT);
if (PIN_ENABLE != 255) pinMode(PIN_ENABLE, OUTPUT);
// initial STEP pin state
digitalWrite(PIN_STEP, LOW);
// set to move forwards (DIR pin low)
setDir(true);
// start with motor controller disabled
disable();
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::enable(void)
{
if (PIN_ENABLE != 255) digitalWrite(PIN_ENABLE, LOW);
m_enabled = true;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::disable(void)
{
stop();
if (PIN_ENABLE != 255) digitalWrite(PIN_ENABLE, HIGH);
m_enabled = false;
}
// ----------------------------------------------------------------------------------------------------
// Does some basic checks, enforces limits, calculates the step interval, and switches to STATE_STARTING
// ----------------------------------------------------------------------------------------------------
bool kissStepperNoAccel::prepareMove(int32_t target)
{
// only continue if not already moving
if (m_kissState == STATE_STOPPED)
{
// constrain the target between reverseLimit and forwardLimit
target = constrain(target, m_reverseLimit, m_forwardLimit);
// only continue if movement is required (positive distance) and possible (positive speed)
if ((target != m_pos) && (m_maxSpeed > 0))
{
// enable the motor controller if necessary
if (!m_enabled) enable();
// set the direction
setDir(target > m_pos);
// set initial state
m_kissState = STATE_STARTING;
m_stepIntervalCorrectionCounter = 0;
// calculate speed profile
m_distTotal = (target > m_pos) ? (target - m_pos) : (m_pos - target);
// start motor at full speed
// don't need to set float version of stepInterval since it isn't used during run
m_stepIntervalWhole = ONE_SECOND / m_maxSpeed;
m_stepIntervalRemainder = ONE_SECOND % m_maxSpeed;
return true;
}
}
return false;
}
/* ----------------------------------------------------------------------------------------------------
Makes the motor move. Call repeatedly and often for smooth motion.
Returns the kissStepper's state.
---------------------------------------------------------------------------------------------------- */
kissState_t kissStepperNoAccel::move(void)
{
uint32_t curTime = micros();
if (m_kissState == STATE_RUN)
{
// between pulses (step pin low), check timing against stepIntervalWhole
// Adding stepIntervalWhole to lastStepTime produces more accurate timing than setting lastStepTime = curTime
if (curTime - m_lastStepTime >= m_stepIntervalWhole)
{
// increment lastStepTime
m_lastStepTime += m_stepIntervalWhole;
// correct lastStepTime
if (m_stepIntervalCorrectionCounter < m_stepIntervalRemainder) m_lastStepTime++;
m_stepIntervalCorrectionCounter += INTERVAL_CORRECTION_INCREMENT;
/*
Do the step pulse.
Using a pointer to a port isn't perfect, but it's still better than digitalWrite()
We need to wait an additional number of clock cycles to make the step pulse the needed width.
See data sheets of Allegro A3967, A4983, A4988, TI DRV8825 for minimum pulse width.
Allegro A3967, A4983, A4988: 1 us minimum
TI DRV8825: 1.9 us minimum
*/
cli();
uint8_t oldStepOut = *m_stepOut;
*m_stepOut |= m_stepBit;
#ifdef TEENSYDUINO
delayMicroseconds(PULSE_WIDTH_US);
#else
_delay_loop_1(PULSE_WIDTH_LOOP_COUNT); // busy wait
#endif
*m_stepOut = oldStepOut;
sei();
// adjust position
m_distMoved++;
// progress through speed profile
if (m_distMoved == m_distTotal)
stop();
}
}
else if (m_kissState == STATE_STARTING)
{
m_lastStepTime = curTime;
m_kissState = STATE_RUN;
}
return m_kissState;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::stop(void)
{
updatePos();
m_distTotal = 0;
m_kissState = STATE_STOPPED;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// kissStepper WITH acceleration
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
kissStepper::kissStepper(uint8_t PIN_DIR, uint8_t PIN_STEP, uint8_t PIN_ENABLE) :
kissStepperNoAccel(PIN_DIR, PIN_STEP, PIN_ENABLE),
m_accel(DEFAULT_ACCEL)
{}
/* ----------------------------------------------------------------------------------------------------
Does some basic checks, enforces limits, calculates the step interval, and switches to STATE_STARTING.
This method also calculates the distance for acceleration (distAccel), constant velocity (distRun),
and total distance (distTotal).
The values are the cumulative number of step pin pulses produced before it's time to change state.
---------------------------------------------------------------------------------------------------- */
bool kissStepper::prepareMove(int32_t target)
{
// only continue if not already moving
if (m_kissState == STATE_STOPPED)
{
// constrain the target between reverseLimit and forwardLimit
target = constrain(target, m_reverseLimit, m_forwardLimit);
// only continue if movement is required (positive distance) and possible (positive speed)
if ((target != m_pos) && (m_maxSpeed > 0))
{
// enable the motor controller if necessary
if (!m_enabled) enable();
// set the direction
setDir(target > m_pos);
// set initial state
m_kissState = STATE_STARTING;
// calculations for the step interval at max speed
uint32_t maxSpeedStepInterval = ONE_SECOND / m_maxSpeed;
m_stepIntervalRemainder = ONE_SECOND % m_maxSpeed;
m_stepIntervalCorrectionCounter = 0;
// calculate total distance
m_distTotal = (target > m_pos) ? (target - m_pos) : (m_pos - target);
// split the total distance across accel, run, and decel
if (m_accel != 0)
{
// calculate distance for accel/decel
// this is the distance of accel/decel between 0 st/s and maxSpeed
uint32_t maxAccelDist = calcMaxAccelDist();
// if maxAccelDist >= half the total distance, use a triangular speed profile (accelerate then decelerate)
// otherwise use a trapezoidal profile (accelerate, then run, then decelerate)
if (maxAccelDist >= (m_distTotal / 2))
{
m_distAccel = m_distTotal / 2;
m_distRun = m_distAccel;
}
else
{
m_distAccel = maxAccelDist;
m_distRun = m_distTotal - m_distAccel;
}
// calculate constant multiplier
m_constMult = ((float)m_accel / ONE_SECOND) / ONE_SECOND;
// calculate step interval at min speed (initial step delay)
// min speed stepInterval = ONE_SECOND / sqrt(V0^2 + 2a)
// because initial velocity is 0:
// min speed stepInterval = ONE_SECOND / sqrt(2a)
m_stepIntervalWhole = m_stepInterval = ONE_SECOND / sqrt(2.0 * m_accel);
// calculate step interval at max speed
m_maxSpeedStepInterval = maxSpeedStepInterval;
}
else
{
// no acceleration or deceleration
m_distAccel = 0;
m_distRun = m_distTotal;
// if not accelerating, start motor at full speed
// don't need to set float version of stepInterval since it isn't used during run
m_stepIntervalWhole = maxSpeedStepInterval;
}
return true;
}
}
return false;
}
/* ----------------------------------------------------------------------------------------------------
Makes the motor move. Call repeatedly and often for smooth motion.
Returns the kissStepper's state.
---------------------------------------------------------------------------------------------------- */
kissState_t kissStepper::move(void)
{
uint32_t curTime = micros();
if (m_kissState > STATE_STARTING)
{
// between pulses (step pin low), check timing against stepIntervalWhole
// Adding stepIntervalWhole to lastStepTime produces more accurate timing than setting lastStepTime = curTime
if (curTime - m_lastStepTime >= m_stepIntervalWhole)
{
// increment lastStepTime
m_lastStepTime += m_stepIntervalWhole;
/*
Do the step pulse.
Using a pointer to a port isn't perfect, but it's still better than digitalWrite()
We need to wait an additional number of clock cycles to make the step pulse the needed width.
See data sheets of Allegro A3967, A4983, A4988, TI DRV8825 for minimum pulse width.
Allegro A3967, A4983, A4988: 1 us minimum
TI DRV8825: 1.9 us minimum
*/
cli();
uint8_t oldStepOut = *m_stepOut;
*m_stepOut |= m_stepBit;
#ifdef TEENSYDUINO
delayMicroseconds(PULSE_WIDTH_US);
#else
_delay_loop_1(PULSE_WIDTH_LOOP_COUNT); // busy wait
#endif
*m_stepOut = oldStepOut;
sei();
// adjust position
m_distMoved++;
// progress through speed profile
if (m_kissState == STATE_RUN)
{
// correct lastStepTime
if (m_stepIntervalCorrectionCounter < m_stepIntervalRemainder) m_lastStepTime++;
m_stepIntervalCorrectionCounter += INTERVAL_CORRECTION_INCREMENT;
if (m_distMoved == m_distRun)
{
if (m_distTotal == m_distRun)
stop();
else
{
m_kissState = STATE_DECEL;
m_stepIntervalWhole = m_stepInterval = decelStep(m_stepInterval, m_constMult);
}
}
}
else if (m_kissState == STATE_ACCEL)
{
if (m_distMoved == m_distAccel)
{
// if the run part of the profile has non-zero distance, the value of distRun will be greater than distAccel
if (m_distRun != m_distAccel)
{
m_kissState = STATE_RUN;
// set stepInterval to maxSpeedStepInterval when entering run
m_stepInterval = m_stepIntervalWhole = m_maxSpeedStepInterval;
}
else
{
m_kissState = STATE_DECEL;
m_stepIntervalWhole = m_stepInterval = decelStep(m_stepInterval, m_constMult);
}
}
else
m_stepIntervalWhole = m_stepInterval = accelStep(m_stepInterval, m_constMult);
}
else
{
if (m_distMoved == m_distTotal)
stop();
else
m_stepIntervalWhole = m_stepInterval = decelStep(m_stepInterval, m_constMult);
}
}
}
else if (m_kissState == STATE_STARTING)
{
// start with the first part of the profile with non-zero length
m_lastStepTime = curTime;
if (m_distAccel != 0)
m_kissState = STATE_ACCEL;
else if (m_distRun != 0)
m_kissState = STATE_RUN;
else if (m_distTotal != 0)
m_kissState = STATE_DECEL;
else // this should never happen... but fail gracefully if it does
stop();
}
return m_kissState;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepper::decelerate(void)
{
if (m_kissState > STATE_STARTING)
{
if (m_accel > 0)
{
uint32_t distRemaining = getDistRemaining();
uint32_t maxDecelDist = calcDecelDist();
uint32_t decelDist = (maxDecelDist > distRemaining) ? distRemaining : maxDecelDist;
m_distAccel = 0;
m_distRun = 0;
m_distTotal = m_distMoved + decelDist;
m_kissState = STATE_DECEL;
}
else
stop();
}
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepper::stop(void)
{
updatePos();
m_distAccel = m_distRun = m_distTotal = 0;
m_kissState = STATE_STOPPED;
}
<commit_msg>Added explicit initialization of several member variables to constructors<commit_after>/*
kissStepper - a lightweight library for the Easy Driver, Big Easy Driver, Allegro stepper motor drivers and others that use a Step/Dir interface
Written by Rylee Isitt. September 21, 2015
License: GNU Lesser General Public License (LGPL) V2.1
Despite the existence of several excellent libraries for driving stepper motors, I created this one to fulfill the following needs:
- Simplicity
- Handling of enable, step, and dir pins
- Based around an external loop
- Approximately linear acceleration using a fast algorithm
- High step frequency (or reasonably so, given the overhead involved)
- Use AVR/ARM libraries and port access to increase performance while keeping the API Arduino-friendly
- Teensy (Teensyduino) compatibility
Acceleration approximation math is based on Aryeh Eiderman's "Real Time Stepper Motor Linear Ramping Just by Addition and Multiplication", available at http://hwml.com/LeibRamp.pdf
*/
/*
Optimization notes:
- Keeping an integer copy of stepInterval for timing comparisons improves performance at a cost of some memory
- Making stepInterval an integer instead of float greatly decreases accuracy of accel/decel and doesn't make a noticeable difference in performance
*/
#include "kissStepper.h"
#ifndef TEENSYDUINO
#include <util/delay_basic.h>
#endif
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// kissStepper without acceleration
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
kissStepperNoAccel::kissStepperNoAccel(uint8_t PIN_DIR, uint8_t PIN_STEP, uint8_t PIN_ENABLE) :
m_forwardLimit(DEFAULT_FORWARD_LIMIT),
m_reverseLimit(DEFAULT_REVERSE_LIMIT),
m_maxSpeed(DEFAULT_SPEED),
PIN_DIR(PIN_DIR),
PIN_STEP(PIN_STEP),
PIN_ENABLE(PIN_ENABLE),
m_kissState(STATE_STOPPED),
m_distTotal(0),
m_distMoved(0),
m_forwards(false),
m_pos(0),
m_stepBit(digitalPinToBitMask(PIN_STEP)),
m_stepOut(portOutputRegister(digitalPinToPort(PIN_STEP))),
m_stepIntervalWhole(0),
m_stepIntervalRemainder(0),
m_stepIntervalCorrectionCounter(0),
m_enabled(false),
m_lastStepTime(0)
{}
// ----------------------------------------------------------------------------------------------------
// Initialize the motor in a default state
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::begin(void)
{
// set pins to output
pinMode(PIN_DIR, OUTPUT);
pinMode(PIN_STEP, OUTPUT);
if (PIN_ENABLE != 255) pinMode(PIN_ENABLE, OUTPUT);
// initial STEP pin state
digitalWrite(PIN_STEP, LOW);
// set to move forwards (DIR pin low)
setDir(true);
// start with motor controller disabled
disable();
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::enable(void)
{
if (PIN_ENABLE != 255) digitalWrite(PIN_ENABLE, LOW);
m_enabled = true;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::disable(void)
{
stop();
if (PIN_ENABLE != 255) digitalWrite(PIN_ENABLE, HIGH);
m_enabled = false;
}
// ----------------------------------------------------------------------------------------------------
// Does some basic checks, enforces limits, calculates the step interval, and switches to STATE_STARTING
// ----------------------------------------------------------------------------------------------------
bool kissStepperNoAccel::prepareMove(int32_t target)
{
// only continue if not already moving
if (m_kissState == STATE_STOPPED)
{
// constrain the target between reverseLimit and forwardLimit
target = constrain(target, m_reverseLimit, m_forwardLimit);
// only continue if movement is required (positive distance) and possible (positive speed)
if ((target != m_pos) && (m_maxSpeed > 0))
{
// enable the motor controller if necessary
if (!m_enabled) enable();
// set the direction
setDir(target > m_pos);
// set initial state
m_kissState = STATE_STARTING;
m_stepIntervalCorrectionCounter = 0;
// calculate speed profile
m_distTotal = (target > m_pos) ? (target - m_pos) : (m_pos - target);
// start motor at full speed
// don't need to set float version of stepInterval since it isn't used during run
m_stepIntervalWhole = ONE_SECOND / m_maxSpeed;
m_stepIntervalRemainder = ONE_SECOND % m_maxSpeed;
return true;
}
}
return false;
}
/* ----------------------------------------------------------------------------------------------------
Makes the motor move. Call repeatedly and often for smooth motion.
Returns the kissStepper's state.
---------------------------------------------------------------------------------------------------- */
kissState_t kissStepperNoAccel::move(void)
{
uint32_t curTime = micros();
if (m_kissState == STATE_RUN)
{
// between pulses (step pin low), check timing against stepIntervalWhole
// Adding stepIntervalWhole to lastStepTime produces more accurate timing than setting lastStepTime = curTime
if (curTime - m_lastStepTime >= m_stepIntervalWhole)
{
// increment lastStepTime
m_lastStepTime += m_stepIntervalWhole;
// correct lastStepTime
if (m_stepIntervalCorrectionCounter < m_stepIntervalRemainder) m_lastStepTime++;
m_stepIntervalCorrectionCounter += INTERVAL_CORRECTION_INCREMENT;
/*
Do the step pulse.
Using a pointer to a port isn't perfect, but it's still better than digitalWrite()
We need to wait an additional number of clock cycles to make the step pulse the needed width.
See data sheets of Allegro A3967, A4983, A4988, TI DRV8825 for minimum pulse width.
Allegro A3967, A4983, A4988: 1 us minimum
TI DRV8825: 1.9 us minimum
*/
cli();
uint8_t oldStepOut = *m_stepOut;
*m_stepOut |= m_stepBit;
#ifdef TEENSYDUINO
delayMicroseconds(PULSE_WIDTH_US);
#else
_delay_loop_1(PULSE_WIDTH_LOOP_COUNT); // busy wait
#endif
*m_stepOut = oldStepOut;
sei();
// adjust position
m_distMoved++;
// progress through speed profile
if (m_distMoved == m_distTotal)
stop();
}
}
else if (m_kissState == STATE_STARTING)
{
m_lastStepTime = curTime;
m_kissState = STATE_RUN;
}
return m_kissState;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepperNoAccel::stop(void)
{
updatePos();
m_distTotal = 0;
m_kissState = STATE_STOPPED;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// kissStepper WITH acceleration
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
kissStepper::kissStepper(uint8_t PIN_DIR, uint8_t PIN_STEP, uint8_t PIN_ENABLE) :
kissStepperNoAccel(PIN_DIR, PIN_STEP, PIN_ENABLE),
m_distAccel(0),
m_distRun(0),
m_maxSpeedStepInterval(0),
m_stepInterval(0),
m_constMult(0),
m_accel(DEFAULT_ACCEL)
{}
/* ----------------------------------------------------------------------------------------------------
Does some basic checks, enforces limits, calculates the step interval, and switches to STATE_STARTING.
This method also calculates the distance for acceleration (distAccel), constant velocity (distRun),
and total distance (distTotal).
The values are the cumulative number of step pin pulses produced before it's time to change state.
---------------------------------------------------------------------------------------------------- */
bool kissStepper::prepareMove(int32_t target)
{
// only continue if not already moving
if (m_kissState == STATE_STOPPED)
{
// constrain the target between reverseLimit and forwardLimit
target = constrain(target, m_reverseLimit, m_forwardLimit);
// only continue if movement is required (positive distance) and possible (positive speed)
if ((target != m_pos) && (m_maxSpeed > 0))
{
// enable the motor controller if necessary
if (!m_enabled) enable();
// set the direction
setDir(target > m_pos);
// set initial state
m_kissState = STATE_STARTING;
// calculations for the step interval at max speed
uint32_t maxSpeedStepInterval = ONE_SECOND / m_maxSpeed;
m_stepIntervalRemainder = ONE_SECOND % m_maxSpeed;
m_stepIntervalCorrectionCounter = 0;
// calculate total distance
m_distTotal = (target > m_pos) ? (target - m_pos) : (m_pos - target);
// split the total distance across accel, run, and decel
if (m_accel != 0)
{
// calculate distance for accel/decel
// this is the distance of accel/decel between 0 st/s and maxSpeed
uint32_t maxAccelDist = calcMaxAccelDist();
// if maxAccelDist >= half the total distance, use a triangular speed profile (accelerate then decelerate)
// otherwise use a trapezoidal profile (accelerate, then run, then decelerate)
if (maxAccelDist >= (m_distTotal / 2))
{
m_distAccel = m_distTotal / 2;
m_distRun = m_distAccel;
}
else
{
m_distAccel = maxAccelDist;
m_distRun = m_distTotal - m_distAccel;
}
// calculate constant multiplier
m_constMult = ((float)m_accel / ONE_SECOND) / ONE_SECOND;
// calculate step interval at min speed (initial step delay)
// min speed stepInterval = ONE_SECOND / sqrt(V0^2 + 2a)
// because initial velocity is 0:
// min speed stepInterval = ONE_SECOND / sqrt(2a)
m_stepIntervalWhole = m_stepInterval = ONE_SECOND / sqrt(2.0 * m_accel);
// calculate step interval at max speed
m_maxSpeedStepInterval = maxSpeedStepInterval;
}
else
{
// no acceleration or deceleration
m_distAccel = 0;
m_distRun = m_distTotal;
// if not accelerating, start motor at full speed
// don't need to set float version of stepInterval since it isn't used during run
m_stepIntervalWhole = maxSpeedStepInterval;
}
return true;
}
}
return false;
}
/* ----------------------------------------------------------------------------------------------------
Makes the motor move. Call repeatedly and often for smooth motion.
Returns the kissStepper's state.
---------------------------------------------------------------------------------------------------- */
kissState_t kissStepper::move(void)
{
uint32_t curTime = micros();
if (m_kissState > STATE_STARTING)
{
// between pulses (step pin low), check timing against stepIntervalWhole
// Adding stepIntervalWhole to lastStepTime produces more accurate timing than setting lastStepTime = curTime
if (curTime - m_lastStepTime >= m_stepIntervalWhole)
{
// increment lastStepTime
m_lastStepTime += m_stepIntervalWhole;
/*
Do the step pulse.
Using a pointer to a port isn't perfect, but it's still better than digitalWrite()
We need to wait an additional number of clock cycles to make the step pulse the needed width.
See data sheets of Allegro A3967, A4983, A4988, TI DRV8825 for minimum pulse width.
Allegro A3967, A4983, A4988: 1 us minimum
TI DRV8825: 1.9 us minimum
*/
cli();
uint8_t oldStepOut = *m_stepOut;
*m_stepOut |= m_stepBit;
#ifdef TEENSYDUINO
delayMicroseconds(PULSE_WIDTH_US);
#else
_delay_loop_1(PULSE_WIDTH_LOOP_COUNT); // busy wait
#endif
*m_stepOut = oldStepOut;
sei();
// adjust position
m_distMoved++;
// progress through speed profile
if (m_kissState == STATE_RUN)
{
// correct lastStepTime
if (m_stepIntervalCorrectionCounter < m_stepIntervalRemainder) m_lastStepTime++;
m_stepIntervalCorrectionCounter += INTERVAL_CORRECTION_INCREMENT;
if (m_distMoved == m_distRun)
{
if (m_distTotal == m_distRun)
stop();
else
{
m_kissState = STATE_DECEL;
m_stepIntervalWhole = m_stepInterval = decelStep(m_stepInterval, m_constMult);
}
}
}
else if (m_kissState == STATE_ACCEL)
{
if (m_distMoved == m_distAccel)
{
// if the run part of the profile has non-zero distance, the value of distRun will be greater than distAccel
if (m_distRun != m_distAccel)
{
m_kissState = STATE_RUN;
// set stepInterval to maxSpeedStepInterval when entering run
m_stepInterval = m_stepIntervalWhole = m_maxSpeedStepInterval;
}
else
{
m_kissState = STATE_DECEL;
m_stepIntervalWhole = m_stepInterval = decelStep(m_stepInterval, m_constMult);
}
}
else
m_stepIntervalWhole = m_stepInterval = accelStep(m_stepInterval, m_constMult);
}
else
{
if (m_distMoved == m_distTotal)
stop();
else
m_stepIntervalWhole = m_stepInterval = decelStep(m_stepInterval, m_constMult);
}
}
}
else if (m_kissState == STATE_STARTING)
{
// start with the first part of the profile with non-zero length
m_lastStepTime = curTime;
if (m_distAccel != 0)
m_kissState = STATE_ACCEL;
else if (m_distRun != 0)
m_kissState = STATE_RUN;
else if (m_distTotal != 0)
m_kissState = STATE_DECEL;
else // this should never happen... but fail gracefully if it does
stop();
}
return m_kissState;
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepper::decelerate(void)
{
if (m_kissState > STATE_STARTING)
{
if (m_accel > 0)
{
uint32_t distRemaining = getDistRemaining();
uint32_t maxDecelDist = calcDecelDist();
uint32_t decelDist = (maxDecelDist > distRemaining) ? distRemaining : maxDecelDist;
m_distAccel = 0;
m_distRun = 0;
m_distTotal = m_distMoved + decelDist;
m_kissState = STATE_DECEL;
}
else
stop();
}
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------
void kissStepper::stop(void)
{
updatePos();
m_distAccel = m_distRun = m_distTotal = 0;
m_kissState = STATE_STOPPED;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: thesdsp.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:56:05 $
*
* 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 _LANG_HXX //autogen wg. LANGUAGE_ENGLISH_US
#include <tools/lang.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#ifndef _SVTOOLS_LNGMISC_HXX_
#include <svtools/lngmisc.hxx>
#endif
#include <cppuhelper/factory.hxx> // helper for factories
#include <com/sun/star/registry/XRegistryKey.hpp>
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#include "thesdsp.hxx"
#include "lngprops.hxx"
using namespace utl;
using namespace osl;
using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::linguistic2;
using namespace linguistic;
///////////////////////////////////////////////////////////////////////////
static BOOL SvcListHasLanguage(
const Sequence< Reference< XThesaurus > > &rRefs,
const Locale &rLocale )
{
BOOL bHasLanguage = FALSE;
const Reference< XThesaurus > *pRef = rRefs.getConstArray();
INT32 nLen = rRefs.getLength();
for (INT32 k = 0; k < nLen && !bHasLanguage; ++k)
{
if (pRef[k].is())
bHasLanguage = pRef[k]->hasLocale( rLocale );
}
return bHasLanguage;
}
///////////////////////////////////////////////////////////////////////////
SeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes()
{
}
SeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes(
const Sequence< OUString > &rSvcImplNames ) :
aSvcImplNames ( rSvcImplNames ),
aSvcRefs ( rSvcImplNames.getLength() )
{
}
///////////////////////////////////////////////////////////////////////////
ThesaurusDispatcher::ThesaurusDispatcher()
{
}
ThesaurusDispatcher::~ThesaurusDispatcher()
{
ClearSvcList();
}
void ThesaurusDispatcher::ClearSvcList()
{
// release memory for each table entry
SeqLangSvcEntry_Thes *pItem = aSvcList.First();
while (pItem)
{
SeqLangSvcEntry_Thes *pTmp = pItem;
pItem = aSvcList.Next();
delete pTmp;
}
}
Sequence< Locale > SAL_CALL
ThesaurusDispatcher::getLocales()
throw(RuntimeException)
{
MutexGuard aGuard( GetLinguMutex() );
ULONG nCnt = aSvcList.Count();
Sequence< Locale > aLocales( nCnt );
Locale *pItem = aLocales.getArray();
SeqLangSvcEntry_Thes *pEntry = aSvcList.First();
for (ULONG i = 0; i < nCnt; i++)
{
DBG_ASSERT( pEntry, "lng : pEntry is NULL pointer" );
pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) );
pEntry = aSvcList.Next();
}
return aLocales;
}
sal_Bool SAL_CALL
ThesaurusDispatcher::hasLocale( const Locale& rLocale )
throw(RuntimeException)
{
MutexGuard aGuard( GetLinguMutex() );
return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) );
}
Sequence< Reference< XMeaning > > SAL_CALL
ThesaurusDispatcher::queryMeanings(
const OUString& rTerm, const Locale& rLocale,
const PropertyValues& rProperties )
throw(IllegalArgumentException, RuntimeException)
{
MutexGuard aGuard( GetLinguMutex() );
Sequence< Reference< XMeaning > > aMeanings;
INT16 nLanguage = LocaleToLanguage( rLocale );
if (nLanguage == LANGUAGE_NONE || !rTerm.getLength())
return aMeanings;
// search for entry with that language
SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );
if (!pEntry)
{
#ifdef LINGU_EXCEPTIONS
throw IllegalArgumentException();
#endif
}
else
{
OUString aChkWord( rTerm );
aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' );
RemoveHyphens( aChkWord );
if (IsIgnoreControlChars( rProperties, GetPropSet() ))
RemoveControlChars( aChkWord );
INT32 nLen = pEntry->aSvcRefs.getLength();
DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(),
"lng : sequence length mismatch");
DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen,
"lng : index out of range");
INT32 i = 0;
// try already instantiated services first
{
const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray();
while (i <= pEntry->aFlags.nLastTriedSvcIndex
&& aMeanings.getLength() == 0)
{
if (pRef[i].is() && pRef[i]->hasLocale( rLocale ))
aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties );
++i;
}
}
// if still no result instantiate new services and try those
if (aMeanings.getLength() == 0
&& pEntry->aFlags.nLastTriedSvcIndex < nLen - 1)
{
const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray();
Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray();
Reference< XMultiServiceFactory > xMgr( getProcessServiceFactory() );
if (xMgr.is())
{
// build service initialization argument
Sequence< Any > aArgs(1);
aArgs.getArray()[0] <<= GetPropSet();
while (i < nLen && aMeanings.getLength() == 0)
{
// create specific service via it's implementation name
Reference< XThesaurus > xThes(
xMgr->createInstanceWithArguments(
pImplNames[i], aArgs ),
UNO_QUERY );
pRef[i] = xThes;
if (xThes.is() && xThes->hasLocale( rLocale ))
aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties );
pEntry->aFlags.nLastTriedSvcIndex = (INT16) i;
++i;
}
// if language is not supported by any of the services
// remove it from the list.
if (i == nLen && aMeanings.getLength() == 0)
{
if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale ))
aSvcList.Remove( nLanguage );
}
}
}
}
return aMeanings;
}
void ThesaurusDispatcher::SetServiceList( const Locale &rLocale,
const Sequence< OUString > &rSvcImplNames )
{
MutexGuard aGuard( GetLinguMutex() );
INT16 nLanguage = LocaleToLanguage( rLocale );
if (0 == rSvcImplNames.getLength())
// remove entry
aSvcList.Remove( nLanguage );
else
{
// modify/add entry
SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );
if (pEntry)
{
pEntry->aSvcImplNames = rSvcImplNames;
pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >(
rSvcImplNames.getLength() );
pEntry->aFlags = SvcFlags();
}
else
{
pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames );
aSvcList.Insert( nLanguage, pEntry );
DBG_ASSERT( aSvcList.Get( nLanguage ), "lng : Insert failed" );
}
}
}
Sequence< OUString >
ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const
{
MutexGuard aGuard( GetLinguMutex() );
Sequence< OUString > aRes;
// search for entry with that language and use data from that
INT16 nLanguage = LocaleToLanguage( rLocale );
ThesaurusDispatcher *pThis = (ThesaurusDispatcher *) this;
const SeqLangSvcEntry_Thes *pEntry = pThis->aSvcList.Get( nLanguage );
if (pEntry)
aRes = pEntry->aSvcImplNames;
return aRes;
}
ThesaurusDispatcher::DspType
ThesaurusDispatcher::GetDspType() const
{
return DSP_THES;
}
///////////////////////////////////////////////////////////////////////////
<commit_msg>INTEGRATION: CWS internatiodel (1.10.26); FILE MERGED 2006/02/10 19:27:24 er 1.10.26.1: #i52115# move LangIDs and ISO conversion from tools to i18npool; introduce class MsLangId and libi18nisolang<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: thesdsp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2006-04-07 13:51:55 $
*
* 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 INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#ifndef _SVTOOLS_LNGMISC_HXX_
#include <svtools/lngmisc.hxx>
#endif
#include <cppuhelper/factory.hxx> // helper for factories
#include <com/sun/star/registry/XRegistryKey.hpp>
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#include "thesdsp.hxx"
#include "lngprops.hxx"
using namespace utl;
using namespace osl;
using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::linguistic2;
using namespace linguistic;
///////////////////////////////////////////////////////////////////////////
static BOOL SvcListHasLanguage(
const Sequence< Reference< XThesaurus > > &rRefs,
const Locale &rLocale )
{
BOOL bHasLanguage = FALSE;
const Reference< XThesaurus > *pRef = rRefs.getConstArray();
INT32 nLen = rRefs.getLength();
for (INT32 k = 0; k < nLen && !bHasLanguage; ++k)
{
if (pRef[k].is())
bHasLanguage = pRef[k]->hasLocale( rLocale );
}
return bHasLanguage;
}
///////////////////////////////////////////////////////////////////////////
SeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes()
{
}
SeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes(
const Sequence< OUString > &rSvcImplNames ) :
aSvcImplNames ( rSvcImplNames ),
aSvcRefs ( rSvcImplNames.getLength() )
{
}
///////////////////////////////////////////////////////////////////////////
ThesaurusDispatcher::ThesaurusDispatcher()
{
}
ThesaurusDispatcher::~ThesaurusDispatcher()
{
ClearSvcList();
}
void ThesaurusDispatcher::ClearSvcList()
{
// release memory for each table entry
SeqLangSvcEntry_Thes *pItem = aSvcList.First();
while (pItem)
{
SeqLangSvcEntry_Thes *pTmp = pItem;
pItem = aSvcList.Next();
delete pTmp;
}
}
Sequence< Locale > SAL_CALL
ThesaurusDispatcher::getLocales()
throw(RuntimeException)
{
MutexGuard aGuard( GetLinguMutex() );
ULONG nCnt = aSvcList.Count();
Sequence< Locale > aLocales( nCnt );
Locale *pItem = aLocales.getArray();
SeqLangSvcEntry_Thes *pEntry = aSvcList.First();
for (ULONG i = 0; i < nCnt; i++)
{
DBG_ASSERT( pEntry, "lng : pEntry is NULL pointer" );
pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) );
pEntry = aSvcList.Next();
}
return aLocales;
}
sal_Bool SAL_CALL
ThesaurusDispatcher::hasLocale( const Locale& rLocale )
throw(RuntimeException)
{
MutexGuard aGuard( GetLinguMutex() );
return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) );
}
Sequence< Reference< XMeaning > > SAL_CALL
ThesaurusDispatcher::queryMeanings(
const OUString& rTerm, const Locale& rLocale,
const PropertyValues& rProperties )
throw(IllegalArgumentException, RuntimeException)
{
MutexGuard aGuard( GetLinguMutex() );
Sequence< Reference< XMeaning > > aMeanings;
INT16 nLanguage = LocaleToLanguage( rLocale );
if (nLanguage == LANGUAGE_NONE || !rTerm.getLength())
return aMeanings;
// search for entry with that language
SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );
if (!pEntry)
{
#ifdef LINGU_EXCEPTIONS
throw IllegalArgumentException();
#endif
}
else
{
OUString aChkWord( rTerm );
aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' );
RemoveHyphens( aChkWord );
if (IsIgnoreControlChars( rProperties, GetPropSet() ))
RemoveControlChars( aChkWord );
INT32 nLen = pEntry->aSvcRefs.getLength();
DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(),
"lng : sequence length mismatch");
DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen,
"lng : index out of range");
INT32 i = 0;
// try already instantiated services first
{
const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray();
while (i <= pEntry->aFlags.nLastTriedSvcIndex
&& aMeanings.getLength() == 0)
{
if (pRef[i].is() && pRef[i]->hasLocale( rLocale ))
aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties );
++i;
}
}
// if still no result instantiate new services and try those
if (aMeanings.getLength() == 0
&& pEntry->aFlags.nLastTriedSvcIndex < nLen - 1)
{
const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray();
Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray();
Reference< XMultiServiceFactory > xMgr( getProcessServiceFactory() );
if (xMgr.is())
{
// build service initialization argument
Sequence< Any > aArgs(1);
aArgs.getArray()[0] <<= GetPropSet();
while (i < nLen && aMeanings.getLength() == 0)
{
// create specific service via it's implementation name
Reference< XThesaurus > xThes(
xMgr->createInstanceWithArguments(
pImplNames[i], aArgs ),
UNO_QUERY );
pRef[i] = xThes;
if (xThes.is() && xThes->hasLocale( rLocale ))
aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties );
pEntry->aFlags.nLastTriedSvcIndex = (INT16) i;
++i;
}
// if language is not supported by any of the services
// remove it from the list.
if (i == nLen && aMeanings.getLength() == 0)
{
if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale ))
aSvcList.Remove( nLanguage );
}
}
}
}
return aMeanings;
}
void ThesaurusDispatcher::SetServiceList( const Locale &rLocale,
const Sequence< OUString > &rSvcImplNames )
{
MutexGuard aGuard( GetLinguMutex() );
INT16 nLanguage = LocaleToLanguage( rLocale );
if (0 == rSvcImplNames.getLength())
// remove entry
aSvcList.Remove( nLanguage );
else
{
// modify/add entry
SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );
if (pEntry)
{
pEntry->aSvcImplNames = rSvcImplNames;
pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >(
rSvcImplNames.getLength() );
pEntry->aFlags = SvcFlags();
}
else
{
pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames );
aSvcList.Insert( nLanguage, pEntry );
DBG_ASSERT( aSvcList.Get( nLanguage ), "lng : Insert failed" );
}
}
}
Sequence< OUString >
ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const
{
MutexGuard aGuard( GetLinguMutex() );
Sequence< OUString > aRes;
// search for entry with that language and use data from that
INT16 nLanguage = LocaleToLanguage( rLocale );
ThesaurusDispatcher *pThis = (ThesaurusDispatcher *) this;
const SeqLangSvcEntry_Thes *pEntry = pThis->aSvcList.Get( nLanguage );
if (pEntry)
aRes = pEntry->aSvcImplNames;
return aRes;
}
ThesaurusDispatcher::DspType
ThesaurusDispatcher::GetDspType() const
{
return DSP_THES;
}
///////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*********************************************************************************
- Contact: Brigitte Cheynis [email protected]
- Link: http
- Raw data test file :
- Reference run number :
- Run Type: STANDALONE
- DA Type: LDC
- Number of events needed: 500
- Input Files: argument list
- Output Files: local file V0_Tuning2.dat
FXS file V0_Tuning2.dat
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/
/**********************************************************************************
* *
* VZERO Detector Algorithm used for tuning FEE parameters *
* *
* This program reads data on the LDC *
* It cumulates mean ADC responses (above pedestals), populates local *
* "./V0_Tuning2.dat" file and exports it to the FES. * *
* We have 128 channels instead of 64 as expected for V0 due to the two sets of *
* charge integrators which are used by the FEE ... *
* The program reports about its processing progress. *
* *
***********************************************************************************/
// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"
//AliRoot
#include <AliVZERORawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>
// standard
#include <stdio.h>
#include <stdlib.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TH1F.h>
#include <TMath.h>
/* Main routine --- Arguments: iteration number, data file */
int main(int argc, char **argv) {
/* magic line from Cvetan */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
int status;
Float_t ADC_Mean[128];
for(Int_t i=0; i<128; i++) {
ADC_Mean[i] = 0.0;
}
/* log start of process */
printf("VZERO DA program started - Tuning FEE parameters\n");
/* check that we got some arguments = list of files */
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;}
/* open pedestal data file to read pedestal values for zero suppression */
FILE *file=NULL;
file=fopen("./V0_Ped_Width_Gain.dat","read");
if (file==NULL) {
printf("Failed to open pedestal data file\n");
return -1;}
float Pedestal[128], Sigma[128];
for(Int_t j=0; j<128; j++){
fscanf(file,"%f %f ", &Pedestal[j], &Sigma[j]);
// printf("Pedestals = %f %f\n",Pedestal[j], Sigma[j]);
}
fclose(file);
/* end of pedestal data retrieval */
/* open result file to be exported to FES */
FILE *fp=NULL;
fp=fopen("./V0_Tuning2.dat","a");
if (fp==NULL) {
printf("Failed to open result file\n");
return -1;}
/* open log file to inform user */
FILE *flog=NULL;
flog=fopen("./V00log.txt","a");
if (flog==NULL) {
printf("Failed to open log file\n");
return -1; }
/* report progress */
daqDA_progressReport(10);
/* init counters on events */
int nevents_physics=0;
int nevents_total=0;
/* read the data */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1; }
/* report progress */
daqDA_progressReport(50);
/* read the data file */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* get next event */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) break; /* end of monitoring file has been reached */
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
return -1; }
/* retry if got no event */
if (event==NULL) break;
/* decode event */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
printf("End Of Run detected\n");
break;
case PHYSICS_EVENT:
nevents_physics++;
// fprintf(flog,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n",
// (unsigned long)event->eventRunNb,
// (unsigned long)event->eventSize,
// EVENT_ID_GET_BUNCH_CROSSING(event->eventId),
// EVENT_ID_GET_ORBIT(event->eventId),
// EVENT_ID_GET_PERIOD(event->eventId) );
AliRawReader *rawReader = new AliRawReaderDate((void*)event);
AliVZERORawStream* rawStream = new AliVZERORawStream(rawReader);
rawStream->Next();
for(Int_t i=0; i<64; i++) {
if(!rawStream->GetIntegratorFlag(i,10))
{
if((rawStream->GetADC(i)-Pedestal[i]) > (Pedestal[i]+3*Sigma[i]) )
ADC_Mean[i]=ADC_Mean[i]+(rawStream->GetADC(i)-Pedestal[i]); // even integrator
}
else
{
if((rawStream->GetADC(i)-Pedestal[i+64]) > (Pedestal[i+64]+3*Sigma[i+64]) )
ADC_Mean[i+64]=ADC_Mean[i+64]+(rawStream->GetADC(i)-Pedestal[i+64]); // odd integrator
}
}
delete rawStream;
rawStream = 0x0;
delete rawReader;
rawReader = 0x0;
} // end of switch on event type
nevents_total++;
/* free resources */
free(event);
} // loop over events
//________________________________________________________________________
// Computes mean values, dumps them into the output text file
for(Int_t i=0; i<128; i++) {
ADC_Mean[i]=ADC_Mean[i]/nevents_physics;
fprintf(fp," %d %d %f\n",argc,i,ADC_Mean[i]);
fprintf(flog," %d %d %f\n",argc,i,ADC_Mean[i]);
}
//________________________________________________________________________
/* write report */
fprintf(flog,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
printf("Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
/* close result and log files */
fclose(fp);
fclose(flog);
/* report progress */
daqDA_progressReport(90);
/* export result file to FES */
status=daqDA_FES_storeFile("./V0_Tuning2.dat","V00da_results");
if (status) {
printf("Failed to export file : %d\n",status);
return -1; }
/* report progress */
daqDA_progressReport(100);
return status;
}
<commit_msg>Removed unnecessary zero suppression<commit_after>/*********************************************************************************
- Contact: Brigitte Cheynis [email protected]
- Link: http
- Raw data test file :
- Reference run number :
- Run Type: STANDALONE
- DA Type: LDC
- Number of events needed: 500
- Input Files: argument list
- Output Files: local file V0_Tuning2.dat
FXS file V0_Tuning2.dat
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/
/**********************************************************************************
* *
* VZERO Detector Algorithm used for tuning FEE parameters *
* *
* This program reads data on the LDC *
* It cumulates mean ADC responses (above pedestals), populates local *
* "./V0_Tuning2.dat" file and exports it to the FES. * *
* We have 128 channels instead of 64 as expected for V0 due to the two sets of *
* charge integrators which are used by the FEE ... *
* The program reports about its processing progress. *
* *
***********************************************************************************/
// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"
//AliRoot
#include <AliVZERORawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>
// standard
#include <stdio.h>
#include <stdlib.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TH1F.h>
#include <TMath.h>
/* Main routine --- Arguments: iteration number, data file */
int main(int argc, char **argv) {
/* magic line from Cvetan */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
int status;
Float_t ADC_Mean[128];
for(Int_t i=0; i<128; i++) {
ADC_Mean[i] = 0.0;
}
/* log start of process */
printf("VZERO DA program started - Tuning FEE parameters\n");
/* check that we got some arguments = list of files */
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;}
/* open result file to be exported to FES */
FILE *fp=NULL;
fp=fopen("./V0_Tuning2.dat","a");
if (fp==NULL) {
printf("Failed to open result file\n");
return -1;}
/* open log file to inform user */
FILE *flog=NULL;
flog=fopen("./V00log.txt","a");
if (flog==NULL) {
printf("Failed to open log file\n");
return -1; }
/* report progress */
daqDA_progressReport(10);
/* init counters on events */
int nevents_physics=0;
int nevents_total=0;
/* read the data */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1; }
/* report progress */
daqDA_progressReport(50);
/* read the data file */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* get next event */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) break; /* end of monitoring file has been reached */
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
return -1; }
/* retry if got no event */
if (event==NULL) break;
/* decode event */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
printf("End Of Run detected\n");
break;
case PHYSICS_EVENT:
nevents_physics++;
AliRawReader *rawReader = new AliRawReaderDate((void*)event);
AliVZERORawStream* rawStream = new AliVZERORawStream(rawReader);
rawStream->Next();
for(Int_t i=0; i<64; i++) {
if(!rawStream->GetIntegratorFlag(i,10))
{
ADC_Mean[i]=ADC_Mean[i]+rawStream->GetADC(i); // even integrator
}
else
{
ADC_Mean[i+64]=ADC_Mean[i+64]+rawStream->GetADC(i); // odd integrator
}
}
delete rawStream;
rawStream = 0x0;
delete rawReader;
rawReader = 0x0;
} // end of switch on event type
nevents_total++;
/* free resources */
free(event);
} // loop over events
//________________________________________________________________________
// Computes mean values, dumps them into the output text file
for(Int_t i=0; i<128; i++) {
ADC_Mean[i]=ADC_Mean[i]/nevents_physics;
fprintf(fp," %d %d %f\n",argc,i,ADC_Mean[i]);
fprintf(flog," %d %d %f\n",argc,i,ADC_Mean[i]);
}
//________________________________________________________________________
/* write report */
fprintf(flog,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
printf("Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
/* close result and log files */
fclose(fp);
fclose(flog);
/* report progress */
daqDA_progressReport(90);
/* export result file to FES */
status=daqDA_FES_storeFile("./V0_Tuning2.dat","V00da_results");
if (status) {
printf("Failed to export file : %d\n",status);
return -1; }
/* report progress */
daqDA_progressReport(100);
return status;
}
<|endoftext|> |
<commit_before>#include "newanalysis.h"
#include "ui_newanalysis.h"
NewAnalysis::NewAnalysis(MainWindow *mainwindow, FileHandler *file_handler, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::NewAnalysis) {
ui->setupUi(this);
this->mainwindow = mainwindow;
this->file_handler = file_handler;
ui->analysis_choise_list->addItem("Movement");
ui->analysis_choise_list->addItem("Face detection");
/*for(auto analys = video->analysis.begin(); analys != video->analysis.end(); ++analys) {
ui->analysi_list->addItem(analys.second());
}*/
}
/**
* @brief NewAnalysis::~NewAnalysis
* Destructor
*/
NewAnalysis::~NewAnalysis() {
delete ui;
}
/**
* @brief NewAnalysis::on_ok_button_clicked
* Adds the selected analysis type to the analysis list.
*/
void NewAnalysis::on_add_button_clicked() {
if(!ui->name_input->text().isEmpty()) {
mainwindow->add_analysis_to_tree(ui->name_input->text());
ui->analysis_list->addItem(ui->name_input->text());
} else set_status_bar("No name given.");
}
/**
* @brief MakeProject::set_status_bar
* @param status text to show in the statusbar
* @param timer time to show it in the bar in ms, 750ms is standard
*/
void NewAnalysis::set_status_bar(std::string status, int timer){
ui->statusbar->showMessage(QString::fromStdString(status), timer);
mainwindow->set_status_bar(status, timer);
}
/**
* @brief NewAnalysis::get_fps
* Requests the user to enter FPS.
* @return Returns the FPS, or -1 if cancelled.
*/
float NewAnalysis::get_fps() {
float fps = FPS_DEFAULT;
// Create the texts shown in the dialog
QString fps_text = QString("FPS [");
fps_text.append(QString::number(FPS_MIN));
fps_text.append(" - ");
fps_text.append(QString::number(FPS_MAX));
fps_text.append("]: ");
// Create the dialog
CustomDialog dialog("FPS", this);
dialog.addLabel("Enter value:");
dialog.addDblSpinBoxF(fps_text, FPS_MIN, FPS_MAX, &fps, FPS_DECIMALS, FPS_STEP,
"Choose FPS value with the input box.");
// Show the dialog (execution will stop here until the dialog is finished)
dialog.exec();
if (dialog.wasCancelled()) {
return -1;
}
return fps;
}
<commit_msg>Edited comments.<commit_after>#include "newanalysis.h"
#include "ui_newanalysis.h"
NewAnalysis::NewAnalysis(MainWindow *mainwindow, FileHandler *file_handler, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::NewAnalysis) {
ui->setupUi(this);
this->mainwindow = mainwindow;
this->file_handler = file_handler;
ui->analysis_choise_list->addItem("Movement");
ui->analysis_choise_list->addItem("Face detection");
/*for(auto analys = video->analysis.begin(); analys != video->analysis.end(); ++analys) {
ui->analysi_list->addItem(analys.second());
}*/
}
/**
* @brief NewAnalysis::~NewAnalysis
* Destructor
*/
NewAnalysis::~NewAnalysis() {
delete ui;
}
/**
* @brief NewAnalysis::on_ok_button_clicked
* Adds the selected analysis type to the analysis list.
*/
void NewAnalysis::on_add_button_clicked() {
if(!ui->name_input->text().isEmpty()) {
mainwindow->add_analysis_to_tree(ui->name_input->text());
ui->analysis_list->addItem(ui->name_input->text());
} else set_status_bar("No name given.");
}
/**
* @brief MakeProject::set_status_bar
* @param status text to show in the statusbar
* @param timer time to show it in the bar in ms, 750ms is standard
*/
void NewAnalysis::set_status_bar(std::string status, int timer){
ui->statusbar->showMessage(QString::fromStdString(status), timer);
mainwindow->set_status_bar(status, timer);
}
/**
* @brief NewAnalysis::get_fps
* Requests the user to enter FPS.
* @return Returns the FPS, or -1 if cancelled.
*/
float NewAnalysis::get_fps() {
float fps = FPS_DEFAULT;
// Create the text shown in the dialog
QString fps_text = QString("FPS [");
fps_text.append(QString::number(FPS_MIN));
fps_text.append(" - ");
fps_text.append(QString::number(FPS_MAX));
fps_text.append("]: ");
// Create the dialog
CustomDialog dialog("FPS", this);
dialog.addLabel("Enter value:");
dialog.addDblSpinBoxF(fps_text, FPS_MIN, FPS_MAX, &fps, FPS_DECIMALS, FPS_STEP,
"Choose FPS value with the input box.");
// Show the dialog (execution will stop here until the dialog is finished)
dialog.exec();
if (dialog.wasCancelled()) {
return -1;
}
return fps;
}
<|endoftext|> |
<commit_before>///
/// @file PrimeFinder.cpp
/// @brief Callback, print and count primes and prime k-tuplets
/// (twin primes, prime triplets, ...).
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/PrimeFinder.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/PrimeSieve-lock.hpp>
#include <primesieve/Callback.hpp>
#include <primesieve/callback_t.hpp>
#include <primesieve/SieveOfEratosthenes.hpp>
#include <primesieve/SieveOfEratosthenes-inline.hpp>
#include <primesieve/littleendian_cast.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
namespace primesieve {
/// forward declaration
uint64_t popcount(const uint64_t* array, uint64_t size);
const uint_t PrimeFinder::kBitmasks_[7][5] =
{
{ END },
{ 0x06, 0x18, 0xc0, END }, // Twin prime bitmasks, i.e. b00000110, b00011000, b11000000
{ 0x07, 0x0e, 0x1c, 0x38, END }, // Prime triplet bitmasks, i.e. b00000111, b00001110, ...
{ 0x1e, END }, // Prime quadruplet bitmasks
{ 0x1f, 0x3e, END }, // Prime quintuplet bitmasks
{ 0x3f, END }, // Prime sextuplet bitmasks
{ 0xfe, END } // Prime septuplet bitmasks
};
PrimeFinder::PrimeFinder(PrimeSieve& ps) :
SieveOfEratosthenes(std::max<uint64_t>(7, ps.getStart()),
ps.getStop(),
ps.getSieveSize()),
ps_(ps)
{
if (ps_.isFlag(ps_.COUNT_TWINS, ps_.COUNT_SEPTUPLETS))
init_kCounts();
}
/// Calculate the number of twins, triplets, ... (bitmask matches)
/// for each possible byte value 0 - 255.
///
void PrimeFinder::init_kCounts()
{
for (uint_t i = 1; i < ps_.counts_.size(); i++)
{
if (ps_.isCount(i))
{
kCounts_[i].resize(256);
for (uint_t j = 0; j < kCounts_[i].size(); j++)
{
uint_t bitmaskCount = 0;
for (const uint_t* b = kBitmasks_[i]; *b <= j; b++)
{
if ((j & *b) == *b)
bitmaskCount++;
}
kCounts_[i][j] = bitmaskCount;
}
}
}
}
/// Executed after each sieved segment.
/// @see sieveSegment() in SieveOfEratosthenes.cpp
///
void PrimeFinder::segmentFinished(const byte_t* sieve, uint_t sieveSize)
{
if (ps_.isCallback())
callbackPrimes(sieve, sieveSize);
if (ps_.isCount())
count(sieve, sieveSize);
if (ps_.isPrint())
print(sieve, sieveSize);
if (ps_.isStatus())
ps_.updateStatus(sieveSize * NUMBERS_PER_BYTE, /* waitForLock = */ false);
}
/// Reconstruct prime numbers from 1 bits of the sieve array and
/// call a callback function for each prime.
///
template <typename T>
inline void PrimeFinder::callbackPrimes(T callback, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
callback(getNextPrime(&bits, i));
}
}
template <>
inline void PrimeFinder::callbackPrimes(Callback<uint64_t>* cobj, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
cobj->callback(getNextPrime(&bits, i));
}
}
template <typename T>
inline void PrimeFinder::callbackPrimes(T callback, int threadNum, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
callback(getNextPrime(&bits, i), threadNum);
}
}
template <>
inline void PrimeFinder::callbackPrimes(Callback<uint64_t, int>* cobj_tn, int threadNum, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
cobj_tn->callback(getNextPrime(&bits, i), threadNum);
}
}
/// Callback the primes within the current segment.
/// @note primes < 7 are handled in PrimeSieve::doSmallPrime()
///
void PrimeFinder::callbackPrimes(const byte_t* sieve, uint_t sieveSize) const
{
if (ps_.isFlag(ps_.CALLBACK_PRIMES_OBJ)) { LockGuard lock(ps_); callbackPrimes(ps_.cobj_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_OBJ_TN)) { /* No Locking */ callbackPrimes(ps_.cobj_tn_, ps_.threadNum_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES)) { LockGuard lock(ps_); callbackPrimes(ps_.callback_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_TN)) { /* No Locking */ callbackPrimes(ps_.callback_tn_, ps_.threadNum_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_C)) { LockGuard lock(ps_); callbackPrimes(reinterpret_cast<callback_c_t>(ps_.callback_), sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_C_TN)) { /* No Locking */ callbackPrimes(reinterpret_cast<callback_c_tn_t>(ps_.callback_tn_), ps_.threadNum_, sieve, sieveSize); }
}
/// Count the primes and prime k-tuplets within
/// the current segment.
///
void PrimeFinder::count(const byte_t* sieve, uint_t sieveSize)
{
// count prime numbers (1 bits), see popcount.cpp
if (ps_.isFlag(ps_.COUNT_PRIMES))
ps_.counts_[0] += popcount(reinterpret_cast<const uint64_t*>(sieve), (sieveSize + 7) / 8);
// count prime k-tuplets (i = 1 twins, i = 2 triplets, ...)
for (uint_t i = 1; i < ps_.counts_.size(); i++)
{
if (ps_.isCount(i)) {
uint_t sum0 = 0;
uint_t sum1 = 0;
uint_t sum2 = 0;
uint_t sum3 = 0;
for (uint_t j = 0; j < sieveSize; j += 4)
{
sum0 += kCounts_[i][sieve[j+0]];
sum1 += kCounts_[i][sieve[j+1]];
sum2 += kCounts_[i][sieve[j+2]];
sum3 += kCounts_[i][sieve[j+3]];
}
ps_.counts_[i] += (sum0 + sum1) + (sum2 + sum3);
}
}
}
void PrimeFinder::printPrime(uint64_t prime)
{
std::cout << prime << '\n';
}
/// Print primes and prime k-tuplets to cout.
/// @note primes < 7 are handled in PrimeSieve::doSmallPrime()
///
void PrimeFinder::print(const byte_t* sieve, uint_t sieveSize) const
{
if (ps_.isFlag(ps_.PRINT_PRIMES))
{
LockGuard lock(ps_);
callbackPrimes(printPrime, sieve, sieveSize);
}
// print prime k-tuplets
if (ps_.isFlag(ps_.PRINT_TWINS, ps_.PRINT_SEPTUPLETS))
{
uint_t i = 1; // i = 1 twins, i = 2 triplets, ...
for (; !ps_.isPrint(i); i++)
;
for (uint_t j = 0; j < sieveSize; j++)
{
for (const uint_t* bitmask = kBitmasks_[i]; *bitmask <= sieve[j]; bitmask++)
{
if ((sieve[j] & *bitmask) == *bitmask)
{
std::ostringstream kTuplet;
kTuplet << "(";
uint64_t bits = *bitmask;
while (bits != 0)
{
kTuplet << getNextPrime(&bits, j);
kTuplet << ((bits != 0) ? ", " : ")\n");
}
std::cout << kTuplet.str();
}
}
}
}
}
} // namespace primesieve
<commit_msg>Update PrimeFinder.cpp<commit_after>///
/// @file PrimeFinder.cpp
/// @brief Callback, print and count primes and prime k-tuplets
/// (twin primes, prime triplets, ...).
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/PrimeFinder.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/PrimeSieve-lock.hpp>
#include <primesieve/Callback.hpp>
#include <primesieve/callback_t.hpp>
#include <primesieve/SieveOfEratosthenes.hpp>
#include <primesieve/SieveOfEratosthenes-inline.hpp>
#include <primesieve/littleendian_cast.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#include <iostream>
#include <sstream>
namespace primesieve {
/// forward declaration
uint64_t popcount(const uint64_t* array, uint64_t size);
const uint_t PrimeFinder::kBitmasks_[7][5] =
{
{ END },
{ 0x06, 0x18, 0xc0, END }, // Twin prime bitmasks, i.e. b00000110, b00011000, b11000000
{ 0x07, 0x0e, 0x1c, 0x38, END }, // Prime triplet bitmasks, i.e. b00000111, b00001110, ...
{ 0x1e, END }, // Prime quadruplet bitmasks
{ 0x1f, 0x3e, END }, // Prime quintuplet bitmasks
{ 0x3f, END }, // Prime sextuplet bitmasks
{ 0xfe, END } // Prime septuplet bitmasks
};
PrimeFinder::PrimeFinder(PrimeSieve& ps) :
SieveOfEratosthenes(std::max<uint64_t>(7, ps.getStart()),
ps.getStop(),
ps.getSieveSize()),
ps_(ps)
{
if (ps_.isFlag(ps_.COUNT_TWINS, ps_.COUNT_SEPTUPLETS))
init_kCounts();
}
/// Calculate the number of twins, triplets, ... (bitmask matches)
/// for each possible byte value 0 - 255.
///
void PrimeFinder::init_kCounts()
{
for (uint_t i = 1; i < ps_.counts_.size(); i++)
{
if (ps_.isCount(i))
{
kCounts_[i].resize(256);
for (uint_t j = 0; j < kCounts_[i].size(); j++)
{
uint_t bitmaskCount = 0;
for (const uint_t* b = kBitmasks_[i]; *b <= j; b++)
{
if ((j & *b) == *b)
bitmaskCount++;
}
kCounts_[i][j] = bitmaskCount;
}
}
}
}
/// Executed after each sieved segment.
/// @see sieveSegment() in SieveOfEratosthenes.cpp
///
void PrimeFinder::segmentFinished(const byte_t* sieve, uint_t sieveSize)
{
if (ps_.isCallback())
callbackPrimes(sieve, sieveSize);
if (ps_.isCount())
count(sieve, sieveSize);
if (ps_.isPrint())
print(sieve, sieveSize);
if (ps_.isStatus())
ps_.updateStatus(sieveSize * NUMBERS_PER_BYTE, /* waitForLock = */ false);
}
/// Reconstruct prime numbers from 1 bits of the sieve array and
/// call a callback function for each prime.
///
template <typename T>
inline void PrimeFinder::callbackPrimes(T callback, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
callback(getNextPrime(&bits, i));
}
}
template <>
inline void PrimeFinder::callbackPrimes(Callback<uint64_t>* cobj, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
cobj->callback(getNextPrime(&bits, i));
}
}
template <typename T>
inline void PrimeFinder::callbackPrimes(T callback, int threadNum, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
callback(getNextPrime(&bits, i), threadNum);
}
}
template <>
inline void PrimeFinder::callbackPrimes(Callback<uint64_t, int>* cobj_tn, int threadNum, const byte_t* sieve, uint_t sieveSize) const
{
for (uint_t i = 0; i < sieveSize; i += 8)
{
uint64_t bits = littleendian_cast<uint64_t>(&sieve[i]);
while (bits != 0)
cobj_tn->callback(getNextPrime(&bits, i), threadNum);
}
}
/// Callback the primes within the current segment.
/// @note primes < 7 are handled in PrimeSieve::doSmallPrime()
///
void PrimeFinder::callbackPrimes(const byte_t* sieve, uint_t sieveSize) const
{
if (ps_.isFlag(ps_.CALLBACK_PRIMES_OBJ)) { LockGuard lock(ps_); callbackPrimes(ps_.cobj_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_OBJ_TN)) { /* No Locking */ callbackPrimes(ps_.cobj_tn_, ps_.threadNum_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES)) { LockGuard lock(ps_); callbackPrimes(ps_.callback_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_TN)) { /* No Locking */ callbackPrimes(ps_.callback_tn_, ps_.threadNum_, sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_C)) { LockGuard lock(ps_); callbackPrimes(reinterpret_cast<callback_c_t>(ps_.callback_), sieve, sieveSize); }
if (ps_.isFlag(ps_.CALLBACK_PRIMES_C_TN)) { /* No Locking */ callbackPrimes(reinterpret_cast<callback_c_tn_t>(ps_.callback_tn_), ps_.threadNum_, sieve, sieveSize); }
}
/// Count the primes and prime k-tuplets within
/// the current segment.
///
void PrimeFinder::count(const byte_t* sieve, uint_t sieveSize)
{
// count prime numbers (1 bits), see popcount.cpp
if (ps_.isFlag(ps_.COUNT_PRIMES))
ps_.counts_[0] += popcount(reinterpret_cast<const uint64_t*>(sieve), (sieveSize + 7) / 8);
// count prime k-tuplets (i = 1 twins, i = 2 triplets, ...)
for (uint_t i = 1; i < ps_.counts_.size(); i++)
{
if (ps_.isCount(i))
{
uint_t sum0 = 0;
uint_t sum1 = 0;
uint_t sum2 = 0;
uint_t sum3 = 0;
for (uint_t j = 0; j < sieveSize; j += 4)
{
sum0 += kCounts_[i][sieve[j+0]];
sum1 += kCounts_[i][sieve[j+1]];
sum2 += kCounts_[i][sieve[j+2]];
sum3 += kCounts_[i][sieve[j+3]];
}
ps_.counts_[i] += (sum0 + sum1) + (sum2 + sum3);
}
}
}
void PrimeFinder::printPrime(uint64_t prime)
{
std::cout << prime << '\n';
}
/// Print primes and prime k-tuplets to cout.
/// @note primes < 7 are handled in PrimeSieve::doSmallPrime()
///
void PrimeFinder::print(const byte_t* sieve, uint_t sieveSize) const
{
if (ps_.isFlag(ps_.PRINT_PRIMES))
{
LockGuard lock(ps_);
callbackPrimes(printPrime, sieve, sieveSize);
}
// print prime k-tuplets
if (ps_.isFlag(ps_.PRINT_TWINS, ps_.PRINT_SEPTUPLETS))
{
uint_t i = 1; // i = 1 twins, i = 2 triplets, ...
for (; !ps_.isPrint(i); i++)
;
for (uint_t j = 0; j < sieveSize; j++)
{
for (const uint_t* bitmask = kBitmasks_[i]; *bitmask <= sieve[j]; bitmask++)
{
if ((sieve[j] & *bitmask) == *bitmask)
{
std::ostringstream kTuplet;
kTuplet << "(";
uint64_t bits = *bitmask;
while (bits != 0)
{
kTuplet << getNextPrime(&bits, j);
kTuplet << ((bits != 0) ? ", " : ")\n");
}
std::cout << kTuplet.str();
}
}
}
}
}
} // namespace primesieve
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK 2017
* Written by Pascal Giorgi <[email protected]>
* and Clement Pernet <[email protected]>
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*.
*/
#define __FFLASFFPACK_SEQUENTIAL
#define ENABLE_ALL_CHECKINGS 1
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <givaro/modular-integer.h>
#include <iomanip>
#include <iostream>
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/utils/test-utils.h"
#include <givaro/modular.h>
#include <givaro/modular-balanced.h>
using namespace std;
using namespace FFPACK;
using Givaro::Modular;
using Givaro::ModularBalanced;
template<typename Field, class RandIter>
bool check_ftrmm (const Field &F, size_t m, size_t n, const typename Field::Element &alpha, FFLAS::FFLAS_SIDE side, FFLAS::FFLAS_UPLO uplo, FFLAS::FFLAS_TRANSPOSE trans, FFLAS::FFLAS_DIAG diag, RandIter& Rand){
typedef typename Field::Element Element;
Element * A, *B, *B2, *C;
size_t k = (side==FFLAS::FflasLeft?m:n);
size_t lda,ldb,ldc;
lda=k+13;
ldb=n+14;
ldc=n+15;
A = FFLAS::fflas_new(F,k,lda);
B = FFLAS::fflas_new(F,m,ldb);
B2 = FFLAS::fflas_new(F,m,ldb);
C = FFLAS::fflas_new(F,m,ldc);
RandomTriangularMatrix (F, k, k, uplo, diag, true, A, lda, Rand);
RandomMatrix (F, m, n, B, ldb, Rand);
FFLAS::fassign (F, m, n, B, ldb, B2, ldb);
string ss=string((uplo == FFLAS::FflasLower)?"Lower_":"Upper_")+string((side == FFLAS::FflasLeft)?"Left_":"Right_")+string((trans == FFLAS::FflasTrans)?"Trans_":"NoTrans_")+string((diag == FFLAS::FflasUnit)?"Unit":"NonUnit");
cout<<std::left<<"Checking FTRMM_";
cout.fill('.');
cout.width(35);
cout<<ss;
FFLAS::Timer t; t.clear();
double time=0.0;
t.clear();
t.start();
FFLAS::ftrmm (F, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb);
t.stop();
time+=t.usertime();
if (side == FFLAS::FflasLeft)
FFLAS::fgemm(F, trans, FFLAS::FflasNoTrans, m, n, m, alpha, A, lda, B2, ldb, F.zero, C, ldc);
else
FFLAS::fgemm(F, FFLAS::FflasNoTrans, trans, m, n, n, alpha, B2, ldb, A, lda, F.zero, C, ldc);
bool ok = true;
if (FFLAS::fequal (F, m, n, B, ldb, C, ldc)){
//cout << "\033[1;32mPASSED\033[0m ("<<time<<")"<<endl;
cout << "PASSED ("<<time<<")"<<endl;
//cerr<<"PASSED ("<<time<<")"<<endl;
} else{
//cout << "\033[1;31mFAILED\033[0m ("<<time<<")"<<endl;
cout << "FAILED ("<<time<<")"<<endl;
ok=false;
//cerr<<"FAILED ("<<time<<")"<<endl;
}
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(B);
FFLAS::fflas_delete(B2);
FFLAS::fflas_delete(C);
return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t n, uint64_t a, size_t iters, uint64_t seed){
bool ok = true ;
int nbit=(int)iters;
while (ok && nbit){
//typedef typename Field::Element Element ;
// choose Field
Field* F= chooseField<Field>(q,b);
typename Field::RandIter G(*F,0,seed);
if (F==nullptr)
return true;
typename Field::Element alpha;
F->init (alpha, (typename Field::Element)a);
cout<<"Checking with ";F->write(cout)<<endl;
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
nbit--;
delete F;
}
return ok;
}
int main(int argc, char** argv)
{
cerr<<setprecision(10);
Givaro::Integer q=-1;
size_t b=0;
size_t m=128;
size_t n=128;
size_t a=1;
size_t iters=1;
bool loop=false;
uint64_t seed = time(NULL);
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b },
{ 'm', "-m M", "Set the row dimension of unknown matrix.", TYPE_INT , &m },
{ 'n', "-n N", "Set the column dimension of the unknown matrix.", TYPE_INT , &n },
{ 'a', "-a A", "Set the scaling of trmm", TYPE_INT , &a },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
bool ok = true;
do{
ok = ok && run_with_field<Modular<double> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<double> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<float> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<float> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<int32_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<int32_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<int64_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<int64_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<Givaro::Integer> >(q,5,m/4+1,n/4+1,a,iters,seed);
ok = ok && run_with_field<Modular<Givaro::Integer> >(q,(b?b:512),m/4+1,n/4+1,a,iters,seed);
} while (loop && ok);
return !ok ;
}
<commit_msg>disable ALL_CHECKINGS causing travis to segfault.<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK 2017
* Written by Pascal Giorgi <[email protected]>
* and Clement Pernet <[email protected]>
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*.
*/
#define __FFLASFFPACK_SEQUENTIAL
// CP: disabling ALL_CHECKINGS as they create
// - conditional jumps on unitialized values (valgrind)
// - segfaults on travis virtual machines
// TODO: fix this (unsuccessful so far) https://github.com/linbox-team/fflas-ffpack/issues/123
//#define ENABLE_ALL_CHECKINGS 1
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <givaro/modular-integer.h>
#include <iomanip>
#include <iostream>
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/utils/test-utils.h"
#include <givaro/modular.h>
#include <givaro/modular-balanced.h>
using namespace std;
using namespace FFPACK;
using Givaro::Modular;
using Givaro::ModularBalanced;
template<typename Field, class RandIter>
bool check_ftrmm (const Field &F, size_t m, size_t n, const typename Field::Element &alpha, FFLAS::FFLAS_SIDE side, FFLAS::FFLAS_UPLO uplo, FFLAS::FFLAS_TRANSPOSE trans, FFLAS::FFLAS_DIAG diag, RandIter& Rand){
typedef typename Field::Element Element;
Element * A, *B, *B2, *C;
size_t k = (side==FFLAS::FflasLeft?m:n);
size_t lda,ldb,ldc;
lda=k+13;
ldb=n+14;
ldc=n+15;
A = FFLAS::fflas_new(F,k,lda);
B = FFLAS::fflas_new(F,m,ldb);
B2 = FFLAS::fflas_new(F,m,ldb);
C = FFLAS::fflas_new(F,m,ldc);
RandomTriangularMatrix (F, k, k, uplo, diag, true, A, lda, Rand);
RandomMatrix (F, m, n, B, ldb, Rand);
FFLAS::fassign (F, m, n, B, ldb, B2, ldb);
string ss=string((uplo == FFLAS::FflasLower)?"Lower_":"Upper_")+string((side == FFLAS::FflasLeft)?"Left_":"Right_")+string((trans == FFLAS::FflasTrans)?"Trans_":"NoTrans_")+string((diag == FFLAS::FflasUnit)?"Unit":"NonUnit");
cout<<std::left<<"Checking FTRMM_";
cout.fill('.');
cout.width(35);
cout<<ss;
FFLAS::Timer t; t.clear();
double time=0.0;
t.clear();
t.start();
FFLAS::ftrmm (F, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb);
t.stop();
time+=t.usertime();
if (side == FFLAS::FflasLeft)
FFLAS::fgemm(F, trans, FFLAS::FflasNoTrans, m, n, m, alpha, A, lda, B2, ldb, F.zero, C, ldc);
else
FFLAS::fgemm(F, FFLAS::FflasNoTrans, trans, m, n, n, alpha, B2, ldb, A, lda, F.zero, C, ldc);
bool ok = true;
if (FFLAS::fequal (F, m, n, B, ldb, C, ldc)){
//cout << "\033[1;32mPASSED\033[0m ("<<time<<")"<<endl;
cout << "PASSED ("<<time<<")"<<endl;
//cerr<<"PASSED ("<<time<<")"<<endl;
} else{
//cout << "\033[1;31mFAILED\033[0m ("<<time<<")"<<endl;
cout << "FAILED ("<<time<<")"<<endl;
ok=false;
//cerr<<"FAILED ("<<time<<")"<<endl;
}
FFLAS::fflas_delete(A);
FFLAS::fflas_delete(B);
FFLAS::fflas_delete(B2);
FFLAS::fflas_delete(C);
return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t n, uint64_t a, size_t iters, uint64_t seed){
bool ok = true ;
int nbit=(int)iters;
while (ok && nbit){
//typedef typename Field::Element Element ;
// choose Field
Field* F= chooseField<Field>(q,b);
typename Field::RandIter G(*F,0,seed);
if (F==nullptr)
return true;
typename Field::Element alpha;
F->init (alpha, (typename Field::Element)a);
cout<<"Checking with ";F->write(cout)<<endl;
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasLeft,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasNoTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasLower,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
ok = ok && check_ftrmm(*F,m,n,alpha,FFLAS::FflasRight,FFLAS::FflasUpper,FFLAS::FflasTrans,FFLAS::FflasNonUnit,G);
nbit--;
delete F;
}
return ok;
}
int main(int argc, char** argv)
{
cerr<<setprecision(10);
Givaro::Integer q=-1;
size_t b=0;
size_t m=128;
size_t n=128;
size_t a=1;
size_t iters=1;
bool loop=false;
uint64_t seed = time(NULL);
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b },
{ 'm', "-m M", "Set the row dimension of unknown matrix.", TYPE_INT , &m },
{ 'n', "-n N", "Set the column dimension of the unknown matrix.", TYPE_INT , &n },
{ 'a', "-a A", "Set the scaling of trmm", TYPE_INT , &a },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
bool ok = true;
do{
ok = ok && run_with_field<Modular<double> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<double> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<float> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<float> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<int32_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<int32_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<int64_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<ModularBalanced<int64_t> >(q,b,m,n,a,iters,seed);
ok = ok && run_with_field<Modular<Givaro::Integer> >(q,5,m/4+1,n/4+1,a,iters,seed);
ok = ok && run_with_field<Modular<Givaro::Integer> >(q,(b?b:512),m/4+1,n/4+1,a,iters,seed);
} while (loop && ok);
return !ok ;
}
<|endoftext|> |
<commit_before>//===- Core/Resolver.cpp - Resolves Atom References -----------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Core/Atom.h"
#include "lld/Core/File.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SymbolTable.h"
#include "lld/Core/TargetInfo.h"
#include "lld/Core/UndefinedAtom.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <vector>
namespace lld {
namespace {
/// This is used as a filter function to std::remove_if to dead strip atoms.
class NotLive {
public:
explicit NotLive(const llvm::DenseSet<const Atom*>& la) : _liveAtoms(la) { }
bool operator()(const Atom *atom) const {
// don't remove if live
if ( _liveAtoms.count(atom) )
return false;
// don't remove if marked never-dead-strip
if (const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(atom)) {
if ( defAtom->deadStrip() == DefinedAtom::deadStripNever )
return false;
}
// do remove this atom
return true;
}
private:
const llvm::DenseSet<const Atom*> _liveAtoms;
};
/// This is used as a filter function to std::remove_if to coalesced atoms.
class AtomCoalescedAway {
public:
explicit AtomCoalescedAway(SymbolTable &sym) : _symbolTable(sym) {}
bool operator()(const Atom *atom) const {
const Atom *rep = _symbolTable.replacement(atom);
return rep != atom;
}
private:
SymbolTable &_symbolTable;
};
} // namespace
// add all atoms from all initial .o files
void Resolver::buildInitialAtomList() {
DEBUG_WITH_TYPE("resolver", llvm::dbgs() << "Resolver initial atom list:\n");
// each input files contributes initial atoms
_atoms.reserve(1024);
_inputFiles.forEachInitialAtom(*this);
_completedInitialObjectFiles = true;
}
// called before the first atom in any file is added with doAtom()
void Resolver::doFile(const File &file) {
}
void Resolver::doUndefinedAtom(const class UndefinedAtom& atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " UndefinedAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", name="
<< atom.name()
<< "\n");
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
_symbolTable.add(atom);
}
// called on each atom when a file is added
void Resolver::doDefinedAtom(const DefinedAtom &atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " DefinedAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", file=#"
<< atom.file().ordinal()
<< ", atom=#"
<< atom.ordinal()
<< ", name="
<< atom.name()
<< "\n");
// Verify on zero-size atoms are pinned to start or end of section.
switch ( atom.sectionPosition() ) {
case DefinedAtom::sectionPositionStart:
case DefinedAtom::sectionPositionEnd:
assert(atom.size() == 0);
break;
case DefinedAtom::sectionPositionEarly:
case DefinedAtom::sectionPositionAny:
break;
}
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
_symbolTable.add(atom);
if (_targetInfo.deadStrip()) {
// add to set of dead-strip-roots, all symbols that
// the compiler marks as don't strip
if (atom.deadStrip() == DefinedAtom::deadStripNever)
_deadStripRoots.insert(&atom);
}
}
void Resolver::doSharedLibraryAtom(const SharedLibraryAtom& atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " SharedLibraryAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", name="
<< atom.name()
<< "\n");
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
_symbolTable.add(atom);
}
void Resolver::doAbsoluteAtom(const AbsoluteAtom& atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " AbsoluteAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", name="
<< atom.name()
<< "\n");
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
if (atom.scope() != Atom::scopeTranslationUnit) {
_symbolTable.add(atom);
}
}
// utility to add a vector of atoms
void Resolver::addAtoms(const std::vector<const DefinedAtom*>& newAtoms) {
for (std::vector<const DefinedAtom *>::const_iterator it = newAtoms.begin();
it != newAtoms.end(); ++it) {
this->doDefinedAtom(**it);
}
}
// ask symbol table if any definitionUndefined atoms still exist
// if so, keep searching libraries until no more atoms being added
void Resolver::resolveUndefines() {
const bool searchArchives =
_targetInfo.searchArchivesToOverrideTentativeDefinitions();
const bool searchSharedLibs =
_targetInfo.searchSharedLibrariesToOverrideTentativeDefinitions();
// keep looping until no more undefines were added in last loop
unsigned int undefineGenCount = 0xFFFFFFFF;
while (undefineGenCount != _symbolTable.size()) {
undefineGenCount = _symbolTable.size();
std::vector<const UndefinedAtom *> undefines;
_symbolTable.undefines(undefines);
for ( const Atom *undefAtom : undefines ) {
StringRef undefName = undefAtom->name();
// load for previous undefine may also have loaded this undefine
if (!_symbolTable.isDefined(undefName)) {
_inputFiles.searchLibraries(undefName,
true, // searchSharedLibs
true, // searchArchives
false, // dataSymbolOnly
*this);
}
}
// search libraries for overrides of common symbols
if (searchArchives || searchSharedLibs) {
std::vector<StringRef> tentDefNames;
_symbolTable.tentativeDefinitions(tentDefNames);
for ( StringRef tentDefName : tentDefNames ) {
// Load for previous tentative may also have loaded
// something that overrode this tentative, so always check.
const Atom *curAtom = _symbolTable.findByName(tentDefName);
assert(curAtom != nullptr);
if (const DefinedAtom* curDefAtom = dyn_cast<DefinedAtom>(curAtom)) {
if (curDefAtom->merge() == DefinedAtom::mergeAsTentative) {
// Still tentative definition, so look for override.
_inputFiles.searchLibraries(tentDefName,
searchSharedLibs,
searchArchives,
true, // dataSymbolOnly
*this);
}
}
}
}
}
}
// switch all references to undefined or coalesced away atoms
// to the new defined atom
void Resolver::updateReferences() {
for(const Atom *atom : _atoms) {
if (const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(atom)) {
for (const Reference *ref : *defAtom) {
const Atom* newTarget = _symbolTable.replacement(ref->target());
(const_cast<Reference*>(ref))->setTarget(newTarget);
}
}
}
}
// for dead code stripping, recursively mark atoms "live"
void Resolver::markLive(const Atom &atom) {
// if already marked live, then done (stop recursion)
if ( _liveAtoms.count(&atom) )
return;
// mark this atom is live
_liveAtoms.insert(&atom);
// mark all atoms it references as live
if ( const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(&atom)) {
for (const Reference *ref : *defAtom) {
const Atom *target = ref->target();
if ( target != nullptr )
this->markLive(*target);
}
}
}
// remove all atoms not actually used
void Resolver::deadStripOptimize() {
// only do this optimization with -dead_strip
if (!_targetInfo.deadStrip())
return;
// clear liveness on all atoms
_liveAtoms.clear();
// By default, shared libraries are built with all globals as dead strip roots
if (_targetInfo.globalsAreDeadStripRoots()) {
for ( const Atom *atom : _atoms ) {
const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom);
if (defAtom == nullptr)
continue;
if ( defAtom->scope() == DefinedAtom::scopeGlobal )
_deadStripRoots.insert(defAtom);
}
}
// Or, use list of names that are dead stip roots.
for (const StringRef &name : _targetInfo.deadStripRoots()) {
const Atom *symAtom = _symbolTable.findByName(name);
assert(symAtom->definition() != Atom::definitionUndefined);
_deadStripRoots.insert(symAtom);
}
// mark all roots as live, and recursively all atoms they reference
for ( const Atom *dsrAtom : _deadStripRoots) {
this->markLive(*dsrAtom);
}
// now remove all non-live atoms from _atoms
_atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(),
NotLive(_liveAtoms)), _atoms.end());
}
// error out if some undefines remain
bool Resolver::checkUndefines(bool final) {
// when using LTO, undefines are checked after bitcode is optimized
if (_haveLLVMObjs && !final)
return false;
// build vector of remaining undefined symbols
std::vector<const UndefinedAtom *> undefinedAtoms;
_symbolTable.undefines(undefinedAtoms);
if (_targetInfo.deadStrip()) {
// When dead code stripping, we don't care if dead atoms are undefined.
undefinedAtoms.erase(std::remove_if(
undefinedAtoms.begin(), undefinedAtoms.end(),
NotLive(_liveAtoms)), undefinedAtoms.end());
}
// error message about missing symbols
if (!undefinedAtoms.empty()) {
// FIXME: need diagnostics interface for writing error messages
bool foundUndefines = false;
for (const UndefinedAtom *undefAtom : undefinedAtoms) {
const File &f = undefAtom->file();
// Skip over a weak symbol.
if (undefAtom->canBeNull() != UndefinedAtom::canBeNullNever)
continue;
// If this is a library and undefined symbols are allowed on the
// target platform, skip over it.
if (isa<SharedLibraryFile>(f) && _targetInfo.allowShlibUndefines())
continue;
// Seems like this symbol is undefined. Warn that.
foundUndefines = true;
if (_targetInfo.printRemainingUndefines()) {
llvm::errs() << "Undefined Symbol: " << undefAtom->file().path()
<< " : " << undefAtom->name() << "\n";
}
}
if (foundUndefines) {
if (_targetInfo.printRemainingUndefines())
llvm::errs() << "symbol(s) not found\n";
return true;
}
}
return false;
}
// remove from _atoms all coaleseced away atoms
void Resolver::removeCoalescedAwayAtoms() {
_atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(),
AtomCoalescedAway(_symbolTable)), _atoms.end());
}
// check for interactions between symbols defined in this linkage unit
// and same symbol name in linked dynamic shared libraries
void Resolver::checkDylibSymbolCollisions() {
for ( const Atom *atom : _atoms ) {
const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(atom);
if (defAtom == nullptr)
continue;
if ( defAtom->merge() != DefinedAtom::mergeAsTentative )
continue;
assert(defAtom->scope() != DefinedAtom::scopeTranslationUnit);
// See if any shared library also has symbol which
// collides with the tentative definition.
// SymbolTable will warn if needed.
_inputFiles.searchLibraries(defAtom->name(), true, false, false, *this);
}
}
void Resolver::linkTimeOptimize() {
// FIX ME
}
bool Resolver::resolve() {
this->buildInitialAtomList();
this->resolveUndefines();
this->updateReferences();
this->deadStripOptimize();
if (this->checkUndefines(false)) {
if (!_targetInfo.allowRemainingUndefines())
return true;
}
this->removeCoalescedAwayAtoms();
this->checkDylibSymbolCollisions();
this->linkTimeOptimize();
this->_result.addAtoms(_atoms);
return false;
}
void Resolver::MergedFile::addAtom(const Atom& atom) {
if (const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(&atom)) {
_definedAtoms._atoms.push_back(defAtom);
} else if (const UndefinedAtom* undefAtom = dyn_cast<UndefinedAtom>(&atom)) {
_undefinedAtoms._atoms.push_back(undefAtom);
} else if (const SharedLibraryAtom* slAtom =
dyn_cast<SharedLibraryAtom>(&atom)) {
_sharedLibraryAtoms._atoms.push_back(slAtom);
} else if (const AbsoluteAtom* abAtom = dyn_cast<AbsoluteAtom>(&atom)) {
_absoluteAtoms._atoms.push_back(abAtom);
} else {
llvm_unreachable("atom has unknown definition kind");
}
}
MutableFile::DefinedAtomRange Resolver::MergedFile::definedAtoms() {
return range<std::vector<const DefinedAtom*>::iterator>(
_definedAtoms._atoms.begin(), _definedAtoms._atoms.end());
}
void Resolver::MergedFile::addAtoms(std::vector<const Atom*>& all) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs() << "Resolver final atom list:\n");
for ( const Atom *atom : all ) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< llvm::format(" 0x%09lX", atom)
<< ", name="
<< atom->name()
<< "\n");
this->addAtom(*atom);
}
}
} // namespace lld
<commit_msg>[lld] Use range based for loop instead of explicit iterators (no functionality change)<commit_after>//===- Core/Resolver.cpp - Resolves Atom References -----------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Core/Atom.h"
#include "lld/Core/File.h"
#include "lld/Core/InputFiles.h"
#include "lld/Core/LLVM.h"
#include "lld/Core/Resolver.h"
#include "lld/Core/SymbolTable.h"
#include "lld/Core/TargetInfo.h"
#include "lld/Core/UndefinedAtom.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <vector>
namespace lld {
namespace {
/// This is used as a filter function to std::remove_if to dead strip atoms.
class NotLive {
public:
explicit NotLive(const llvm::DenseSet<const Atom*>& la) : _liveAtoms(la) { }
bool operator()(const Atom *atom) const {
// don't remove if live
if ( _liveAtoms.count(atom) )
return false;
// don't remove if marked never-dead-strip
if (const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(atom)) {
if ( defAtom->deadStrip() == DefinedAtom::deadStripNever )
return false;
}
// do remove this atom
return true;
}
private:
const llvm::DenseSet<const Atom*> _liveAtoms;
};
/// This is used as a filter function to std::remove_if to coalesced atoms.
class AtomCoalescedAway {
public:
explicit AtomCoalescedAway(SymbolTable &sym) : _symbolTable(sym) {}
bool operator()(const Atom *atom) const {
const Atom *rep = _symbolTable.replacement(atom);
return rep != atom;
}
private:
SymbolTable &_symbolTable;
};
} // namespace
// add all atoms from all initial .o files
void Resolver::buildInitialAtomList() {
DEBUG_WITH_TYPE("resolver", llvm::dbgs() << "Resolver initial atom list:\n");
// each input files contributes initial atoms
_atoms.reserve(1024);
_inputFiles.forEachInitialAtom(*this);
_completedInitialObjectFiles = true;
}
// called before the first atom in any file is added with doAtom()
void Resolver::doFile(const File &file) {
}
void Resolver::doUndefinedAtom(const class UndefinedAtom& atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " UndefinedAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", name="
<< atom.name()
<< "\n");
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
_symbolTable.add(atom);
}
// called on each atom when a file is added
void Resolver::doDefinedAtom(const DefinedAtom &atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " DefinedAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", file=#"
<< atom.file().ordinal()
<< ", atom=#"
<< atom.ordinal()
<< ", name="
<< atom.name()
<< "\n");
// Verify on zero-size atoms are pinned to start or end of section.
switch ( atom.sectionPosition() ) {
case DefinedAtom::sectionPositionStart:
case DefinedAtom::sectionPositionEnd:
assert(atom.size() == 0);
break;
case DefinedAtom::sectionPositionEarly:
case DefinedAtom::sectionPositionAny:
break;
}
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
_symbolTable.add(atom);
if (_targetInfo.deadStrip()) {
// add to set of dead-strip-roots, all symbols that
// the compiler marks as don't strip
if (atom.deadStrip() == DefinedAtom::deadStripNever)
_deadStripRoots.insert(&atom);
}
}
void Resolver::doSharedLibraryAtom(const SharedLibraryAtom& atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " SharedLibraryAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", name="
<< atom.name()
<< "\n");
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
_symbolTable.add(atom);
}
void Resolver::doAbsoluteAtom(const AbsoluteAtom& atom) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< " AbsoluteAtom: "
<< llvm::format("0x%09lX", &atom)
<< ", name="
<< atom.name()
<< "\n");
// add to list of known atoms
_atoms.push_back(&atom);
// tell symbol table
if (atom.scope() != Atom::scopeTranslationUnit) {
_symbolTable.add(atom);
}
}
// utility to add a vector of atoms
void Resolver::addAtoms(const std::vector<const DefinedAtom*>& newAtoms) {
for (const DefinedAtom *newAtom : newAtoms) {
this->doDefinedAtom(*newAtom);
}
}
// ask symbol table if any definitionUndefined atoms still exist
// if so, keep searching libraries until no more atoms being added
void Resolver::resolveUndefines() {
const bool searchArchives =
_targetInfo.searchArchivesToOverrideTentativeDefinitions();
const bool searchSharedLibs =
_targetInfo.searchSharedLibrariesToOverrideTentativeDefinitions();
// keep looping until no more undefines were added in last loop
unsigned int undefineGenCount = 0xFFFFFFFF;
while (undefineGenCount != _symbolTable.size()) {
undefineGenCount = _symbolTable.size();
std::vector<const UndefinedAtom *> undefines;
_symbolTable.undefines(undefines);
for ( const Atom *undefAtom : undefines ) {
StringRef undefName = undefAtom->name();
// load for previous undefine may also have loaded this undefine
if (!_symbolTable.isDefined(undefName)) {
_inputFiles.searchLibraries(undefName,
true, // searchSharedLibs
true, // searchArchives
false, // dataSymbolOnly
*this);
}
}
// search libraries for overrides of common symbols
if (searchArchives || searchSharedLibs) {
std::vector<StringRef> tentDefNames;
_symbolTable.tentativeDefinitions(tentDefNames);
for ( StringRef tentDefName : tentDefNames ) {
// Load for previous tentative may also have loaded
// something that overrode this tentative, so always check.
const Atom *curAtom = _symbolTable.findByName(tentDefName);
assert(curAtom != nullptr);
if (const DefinedAtom* curDefAtom = dyn_cast<DefinedAtom>(curAtom)) {
if (curDefAtom->merge() == DefinedAtom::mergeAsTentative) {
// Still tentative definition, so look for override.
_inputFiles.searchLibraries(tentDefName,
searchSharedLibs,
searchArchives,
true, // dataSymbolOnly
*this);
}
}
}
}
}
}
// switch all references to undefined or coalesced away atoms
// to the new defined atom
void Resolver::updateReferences() {
for(const Atom *atom : _atoms) {
if (const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(atom)) {
for (const Reference *ref : *defAtom) {
const Atom* newTarget = _symbolTable.replacement(ref->target());
(const_cast<Reference*>(ref))->setTarget(newTarget);
}
}
}
}
// for dead code stripping, recursively mark atoms "live"
void Resolver::markLive(const Atom &atom) {
// if already marked live, then done (stop recursion)
if ( _liveAtoms.count(&atom) )
return;
// mark this atom is live
_liveAtoms.insert(&atom);
// mark all atoms it references as live
if ( const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(&atom)) {
for (const Reference *ref : *defAtom) {
const Atom *target = ref->target();
if ( target != nullptr )
this->markLive(*target);
}
}
}
// remove all atoms not actually used
void Resolver::deadStripOptimize() {
// only do this optimization with -dead_strip
if (!_targetInfo.deadStrip())
return;
// clear liveness on all atoms
_liveAtoms.clear();
// By default, shared libraries are built with all globals as dead strip roots
if (_targetInfo.globalsAreDeadStripRoots()) {
for ( const Atom *atom : _atoms ) {
const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(atom);
if (defAtom == nullptr)
continue;
if ( defAtom->scope() == DefinedAtom::scopeGlobal )
_deadStripRoots.insert(defAtom);
}
}
// Or, use list of names that are dead stip roots.
for (const StringRef &name : _targetInfo.deadStripRoots()) {
const Atom *symAtom = _symbolTable.findByName(name);
assert(symAtom->definition() != Atom::definitionUndefined);
_deadStripRoots.insert(symAtom);
}
// mark all roots as live, and recursively all atoms they reference
for ( const Atom *dsrAtom : _deadStripRoots) {
this->markLive(*dsrAtom);
}
// now remove all non-live atoms from _atoms
_atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(),
NotLive(_liveAtoms)), _atoms.end());
}
// error out if some undefines remain
bool Resolver::checkUndefines(bool final) {
// when using LTO, undefines are checked after bitcode is optimized
if (_haveLLVMObjs && !final)
return false;
// build vector of remaining undefined symbols
std::vector<const UndefinedAtom *> undefinedAtoms;
_symbolTable.undefines(undefinedAtoms);
if (_targetInfo.deadStrip()) {
// When dead code stripping, we don't care if dead atoms are undefined.
undefinedAtoms.erase(std::remove_if(
undefinedAtoms.begin(), undefinedAtoms.end(),
NotLive(_liveAtoms)), undefinedAtoms.end());
}
// error message about missing symbols
if (!undefinedAtoms.empty()) {
// FIXME: need diagnostics interface for writing error messages
bool foundUndefines = false;
for (const UndefinedAtom *undefAtom : undefinedAtoms) {
const File &f = undefAtom->file();
// Skip over a weak symbol.
if (undefAtom->canBeNull() != UndefinedAtom::canBeNullNever)
continue;
// If this is a library and undefined symbols are allowed on the
// target platform, skip over it.
if (isa<SharedLibraryFile>(f) && _targetInfo.allowShlibUndefines())
continue;
// Seems like this symbol is undefined. Warn that.
foundUndefines = true;
if (_targetInfo.printRemainingUndefines()) {
llvm::errs() << "Undefined Symbol: " << undefAtom->file().path()
<< " : " << undefAtom->name() << "\n";
}
}
if (foundUndefines) {
if (_targetInfo.printRemainingUndefines())
llvm::errs() << "symbol(s) not found\n";
return true;
}
}
return false;
}
// remove from _atoms all coaleseced away atoms
void Resolver::removeCoalescedAwayAtoms() {
_atoms.erase(std::remove_if(_atoms.begin(), _atoms.end(),
AtomCoalescedAway(_symbolTable)), _atoms.end());
}
// check for interactions between symbols defined in this linkage unit
// and same symbol name in linked dynamic shared libraries
void Resolver::checkDylibSymbolCollisions() {
for ( const Atom *atom : _atoms ) {
const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(atom);
if (defAtom == nullptr)
continue;
if ( defAtom->merge() != DefinedAtom::mergeAsTentative )
continue;
assert(defAtom->scope() != DefinedAtom::scopeTranslationUnit);
// See if any shared library also has symbol which
// collides with the tentative definition.
// SymbolTable will warn if needed.
_inputFiles.searchLibraries(defAtom->name(), true, false, false, *this);
}
}
void Resolver::linkTimeOptimize() {
// FIX ME
}
bool Resolver::resolve() {
this->buildInitialAtomList();
this->resolveUndefines();
this->updateReferences();
this->deadStripOptimize();
if (this->checkUndefines(false)) {
if (!_targetInfo.allowRemainingUndefines())
return true;
}
this->removeCoalescedAwayAtoms();
this->checkDylibSymbolCollisions();
this->linkTimeOptimize();
this->_result.addAtoms(_atoms);
return false;
}
void Resolver::MergedFile::addAtom(const Atom& atom) {
if (const DefinedAtom* defAtom = dyn_cast<DefinedAtom>(&atom)) {
_definedAtoms._atoms.push_back(defAtom);
} else if (const UndefinedAtom* undefAtom = dyn_cast<UndefinedAtom>(&atom)) {
_undefinedAtoms._atoms.push_back(undefAtom);
} else if (const SharedLibraryAtom* slAtom =
dyn_cast<SharedLibraryAtom>(&atom)) {
_sharedLibraryAtoms._atoms.push_back(slAtom);
} else if (const AbsoluteAtom* abAtom = dyn_cast<AbsoluteAtom>(&atom)) {
_absoluteAtoms._atoms.push_back(abAtom);
} else {
llvm_unreachable("atom has unknown definition kind");
}
}
MutableFile::DefinedAtomRange Resolver::MergedFile::definedAtoms() {
return range<std::vector<const DefinedAtom*>::iterator>(
_definedAtoms._atoms.begin(), _definedAtoms._atoms.end());
}
void Resolver::MergedFile::addAtoms(std::vector<const Atom*>& all) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs() << "Resolver final atom list:\n");
for ( const Atom *atom : all ) {
DEBUG_WITH_TYPE("resolver", llvm::dbgs()
<< llvm::format(" 0x%09lX", atom)
<< ", name="
<< atom->name()
<< "\n");
this->addAtom(*atom);
}
}
} // namespace lld
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int h;
string printSymbol(char s, int n) {
int i = 0;
string line = "";
for (; i < n; i++) {
line += s;
}
return line;
}
string printSymbol2(char s1, char s2, int n) {
string line = "";
cout << printSymbol(s1, n);
cout << s2;
cout << printSymbol(s1, h - (2 * n - 1));
cout << s2;
return line;
}
int main() {
int i = 1;
cin >> h;
for (; i <= h; i++) {
cout << printSymbol(' ', h - i);
cout << printSymbol('*', 2 * i - 1);
cout << "\n";
}
for (i = 1; i <= h; i++) {
if (i > 1 && i < h) {
cout << printSymbol2(' ', '*', h - i);
} else {
cout << printSymbol(' ', h - i);
cout << printSymbol('*', 2 * i - 1);
}
cout << "\n";
}
return 0;
}
<commit_msg>Exercise print triangle.<commit_after>#include <iostream>
using namespace std;
int h;
string printSymbol(char s, int n) {
int i = 0;
string line = "";
for (; i < n; i++) {
line += s;
}
return line;
}
string printSymbol2(int n, int i) {
string line = "";
cout << printSymbol(' ', n);
cout << '*';
cout << printSymbol(' ', i);
cout << '*';
return line;
}
void printFullTriangle(int h) {
int i = 1;
for (; i <= h; i++) {
cout << printSymbol(' ', h - i);
cout << printSymbol('*', 2 * i - 1);
cout << "\n";
}
}
void printEmptyCenterTriangle(int h, int i) {
for (i = 1; i <= h; i++) {
if (i > 1 && i < h) {
cout << printSymbol2(h - i, 2 * i - 3);
} else {
cout << printSymbol(' ', h - i);
cout << printSymbol('*', 2 * i - 1);
}
cout << "\n";
}
}
int main() {
int i = 1;
cin >> h;
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <cstdio>
#include <cctype>
#include <iostream>
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
tok_eof = -1,
// commands
tok_def = -2,
tok_extern = -3,
// primary
tok_identifier = -4,
tok_number = -5,
};
static std::string IdentifierStr;
static double NumVal;
// gettok - Return the next token from standard input.
static int gettok() {
static int LastChar = ' ';
// Skip any whitespace
while (std::isspace(LastChar)) {
LastChar = std::getchar();
}
if (std::isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
IdentifierStr = LastChar;
while (std::isalnum((LastChar = std::getchar()))) {
IdentifierStr += LastChar;
}
if (IdentifierStr == "def") {
return tok_def;
}
if (IdentifierStr == "extern") {
return tok_extern;
}
return tok_identifier;
}
if (std::isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
std::string NumStr;
do {
NumStr += LastChar;
LastChar = std::getchar();
} while (std::isdigit(LastChar) || LastChar == '.');
NumVal = std::strtod(NumStr.c_str(), 0);
return tok_number;
}
if (LastChar == '#') {
// Comment until end of line
do {
LastChar = std::getchar();
} while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF) {
return gettok();
}
}
// Check for end of file. Don't eat the EOF.
if (LastChar == EOF) {
return tok_eof;
}
// Otherwise, just return the character as its ascii value.
int ThisChar = LastChar;
LastChar = std::getchar();
return ThisChar;
}
int main(int, char**) {
while (true) {
auto tok = gettok();
std::cout << tok << std::endl;
if (tok == tok_eof) {
break;
}
}
return 0;
}
<commit_msg>Kaleidoscope tutorial, Chapter 2<commit_after>#include <string>
#include <cstdio>
#include <cctype>
#include <iostream>
#include <memory>
#include <vector>
#include <map>
#pragma GCC diagnostic ignored "-Wunused-private-field"
#pragma GCC diagnostic ignored "-Wunused-function"
////////////////////////////////////////////////////////////////////////////////
// Lexer
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
tok_eof = -1,
// commands
tok_def = -2,
tok_extern = -3,
// primary
tok_identifier = -4,
tok_number = -5,
};
static std::string IdentifierStr;
static double NumVal;
// gettok - Return the next token from standard input.
static int gettok() {
static int LastChar = ' ';
// Skip any whitespace
while (std::isspace(LastChar)) {
LastChar = std::getchar();
}
if (std::isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
IdentifierStr = LastChar;
while (std::isalnum((LastChar = std::getchar()))) {
IdentifierStr += LastChar;
}
if (IdentifierStr == "def") {
return tok_def;
}
if (IdentifierStr == "extern") {
return tok_extern;
}
return tok_identifier;
}
if (std::isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
std::string NumStr;
do {
NumStr += LastChar;
LastChar = std::getchar();
} while (std::isdigit(LastChar) || LastChar == '.');
NumVal = std::strtod(NumStr.c_str(), 0);
return tok_number;
}
if (LastChar == '#') {
// Comment until end of line
do {
LastChar = std::getchar();
} while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF) {
return gettok();
}
}
// Check for end of file. Don't eat the EOF.
if (LastChar == EOF) {
return tok_eof;
}
// Otherwise, just return the character as its ascii value.
int ThisChar = LastChar;
LastChar = std::getchar();
return ThisChar;
}
////////////////////////////////////////////////////////////////////////////////
// Parser
/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
virtual ~ExprAST() {}
};
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
explicit NumberExprAST(double Val) : Val(Val) {}
};
/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
std::string Name;
public:
explicit VariableExprAST(const std::string& Name) : Name(Name) {}
};
/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
char Op;
std::unique_ptr<ExprAST> LHS, RHS;
public:
BinaryExprAST(char op, std::unique_ptr<ExprAST> LHS,
std::unique_ptr<ExprAST> RHS)
: Op(op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
};
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<std::unique_ptr<ExprAST>> Args;
public:
CallExprAST(const std::string& Callee,
std::vector<std::unique_ptr<ExprAST>> Args)
: Callee(Callee), Args(std::move(Args)) {}
};
/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
std::string Name;
std::vector<std::string> Args;
public:
PrototypeAST(const std::string& name, std::vector<std::string> Args)
: Name(name), Args(std::move(Args)) {}
const std::string& getName() const { return Name; }
};
/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
std::unique_ptr<PrototypeAST> Proto;
std::unique_ptr<ExprAST> Body;
public:
FunctionAST(std::unique_ptr<PrototypeAST> Proto,
std::unique_ptr<ExprAST> Body)
: Proto(std::move(Proto)), Body(std::move(Body)) {}
};
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
/// token the parser is looking at. getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() {
return CurTok = gettok();
}
/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char* Str) {
fprintf(stderr, "LogError: %s\n", Str);
return nullptr;
}
std::unique_ptr<PrototypeAST> LogErrorP(const char* Str) {
LogError(Str);
return nullptr;
}
static std::unique_ptr<ExprAST> ParseExpression();
/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
auto Result = std::make_unique<NumberExprAST>(NumVal);
getNextToken(); // consume the number
return std::move(Result);
}
/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
getNextToken(); // eat (.
auto V = ParseExpression();
if (!V) {
return nullptr;
}
if (CurTok != ')') {
return LogError("Expected ')'");
}
getNextToken(); // eat ).
return V;
}
/// identifierexpr
/// ::= identifier
/// ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
getNextToken(); // eat identifier
if (CurTok != '(') { // simple variable ref
return std::make_unique<VariableExprAST>(IdName);
}
// Call
getNextToken(); // eat (
std::vector<std::unique_ptr<ExprAST>> Args;
if (CurTok != ')') {
while(1) {
if (auto Arg = ParseExpression()) {
Args.push_back(std::move(Arg));
} else return nullptr;
if (CurTok == ')') break;
if (CurTok != ',') {
return LogError("Expected ')' or ',' in argument list");
}
getNextToken();
}
}
// Eat the ')'.
getNextToken();
return std::make_unique<CallExprAST>(IdName, std::move(Args));
}
/// primary
/// ::= identifierexpr
/// ::= numberexpr
/// ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
switch (CurTok) {
default:
return LogError("unknown token when expecting an expression");
case tok_identifier:
return ParseIdentifierExpr();
case tok_number:
return ParseNumberExpr();
case '(':
return ParseParenExpr();
}
}
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
if (!isascii(CurTok)) {
return -1;
}
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
return TokPrec;
}
/// binoprhs
/// ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
std::unique_ptr<ExprAST> LHS) {
// If this is a binop, find its precedence
while (true) {
int TokPrec = GetTokPrecedence();
// If this is a binop that binds at least as tightly as the current binop,
// consume it, otherwise we are done.
if (TokPrec < ExprPrec) {
return LHS;
}
// Okay, we know this is a binop.
int BinOp = CurTok;
getNextToken(); // eat binop
// Parse the primary expression after the binary operator
auto RHS = ParsePrimary();
if (!RHS) {
return nullptr;
}
// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
if (!RHS) {
return nullptr;
}
}
// Merge LHS/RHS.
LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
}
}
/// expression
/// ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
auto LHS = ParsePrimary();
if (!LHS) {
return nullptr;
}
return ParseBinOpRHS(0, std::move(LHS));
}
/// prototype
/// ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype() {
if (CurTok != tok_identifier) {
return LogErrorP("Expected function name in prototype");
}
std::string FnName = IdentifierStr;
getNextToken();
if (CurTok != '(') {
return LogErrorP("Expected '(' in prototype");
}
// Read the list of argument names
std::vector<std::string> ArgNames;
while (getNextToken() == tok_identifier) {
ArgNames.push_back(IdentifierStr);
}
if (CurTok != ')') {
return LogErrorP("Expected ')' in prototype");
}
// success
getNextToken(); // eat ')'
return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}
/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
getNextToken();
auto Proto = ParsePrototype();
if (!Proto) return nullptr;
if (auto E = ParseExpression()) {
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}
return nullptr;
}
/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
getNextToken(); // eat extern.
return ParsePrototype();
}
/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
if (auto E = ParseExpression()) {
// Make an anonymous proto.
auto Proto = std::make_unique<PrototypeAST>("", std::vector<std::string>());
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
// Driver
void HandleDefinition() {
if (ParseDefinition()) {
fprintf(stderr, "Parsed a function definition\n");
} else {
// Skip token for error recovery
getNextToken();
}
}
void HandleExtern() {
if (ParseExtern()) {
fprintf(stderr, "Parsed an extern\n");
} else {
// Skip token for error recovery
getNextToken();
}
}
void HandleTopLevelExpression() {
if (ParseTopLevelExpr()) {
fprintf(stderr, "Parsed a top-level expr\n");
} else {
// Skip token for error recovery
getNextToken();
}
}
static void MainLoop() {
while (1) {
fprintf(stderr, "ready>");
switch (CurTok) {
case tok_eof:
return;
case ';': // ignore top-level semicolons.
getNextToken();
break;
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
int main(int, char**) {
// Install standard binary operators.
// 1 is lowest precedence.
BinopPrecedence['<'] = 10;
BinopPrecedence['+'] = 20;
BinopPrecedence['-'] = 30;
BinopPrecedence['*'] = 40; // highest
// Prime the first token.
fprintf(stderr, "ready>");
getNextToken();
MainLoop();
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <array>
#include <iostream>
#include <string>
#include <cppformat/format.h>
#include "blackhole/cpp17/optional.hpp"
#include "blackhole/cpp17/string_view.hpp"
using blackhole::cpp17::string_view;
constexpr
std::size_t
parse_argument(const string_view& string, std::size_t& pos) {
char c = string[pos];
if (c == '}') {
return 2;
} else {
throw std::out_of_range("only {} is supported for compile-time analysys for now, sorry");
}
}
namespace blackhole {
namespace detail {
namespace cppformat = fmt;
/// Returns the number of literals which will be produced by formatter internally.
constexpr
std::size_t
literal_count(const string_view& format) {
// Always has at least one literal.
std::size_t result = 1;
if (format.size() == 0) {
return result;
}
std::size_t id = 0;
bool last_literal_has_next_placeholder = false;
bool has_some_bytes = false;
while (id < format.size()) {
char curr = format[id];
if (curr == '{') {
++id;
if (id >= format.size()) {
throw std::out_of_range("unmatched '{' in format");
}
curr = format[id];
if (curr == '{') {
++id;
++result;
continue;
} else {
const auto size = ::parse_argument(format, id);
id += size - 1;
++result;
has_some_bytes = false;
last_literal_has_next_placeholder = true;
continue;
}
} else if (curr == '}') {
++id;
if (id >= format.size()) {
throw std::out_of_range("single '}' encountered in format string");
}
curr = format[id];
if (curr == '}') {
++id;
++result;
has_some_bytes = false;
continue;
} else {
throw std::out_of_range("single '}' encountered in format string");
}
}
++id;
has_some_bytes = true;
}
return result;
}
} // namespace detail
} // namespace blackhole
constexpr std::size_t count_placeholders(const string_view& string) {
std::size_t counter = 0;
std::size_t i = 0;
while (i != string.size()) {
char c = string[i];
if (c == '{') {
i++;
if (i == string.size()) {
throw std::out_of_range("unmatched '{' in format");
}
c = string[i];
if (c == '{') {
i++;
continue;
} else {
// save literal.
parse_argument(string, i);
counter++;
// parse_argument.
}
} else if (c == '}') {
// expect_closed_brace()
i++;
if (i == string.size()) {
throw std::out_of_range("single '}' encountered in format string");
}
c = string[i];
if (c == '}') {
i++;
continue;
} else {
throw std::out_of_range("single '}' encountered in format string");
}
}
i++;
}
return counter;
}
constexpr std::size_t count_literals(const string_view& string) {
std::size_t counter = 0;
int state = 0;
std::size_t i = 0;
while (i != string.size()) {
char c = string[i];
if (c == '{') {
i++;
if (i == string.size()) {
throw std::out_of_range("unmatched '{' in format");
}
c = string[i];
if (c == '{') {
i++;
continue;
} else {
// save literal.
parse_argument(string, i);
counter++;
state = 1;
// parse_argument.
}
} else if (c == '}') {
// expect_closed_brace()
i++;
if (i == string.size()) {
throw std::out_of_range("single '}' encountered in format string");
}
c = string[i];
if (c == '}') {
i++;
continue;
} else {
throw std::out_of_range("single '}' encountered in format string");
}
}
i++;
state = 0;
}
if (state == 0) {
counter++;
}
return counter;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
struct literal_t {
string_view data;
bool placeholder_next;
constexpr
literal_t(string_view data, bool placeholder_next):
data(data),
placeholder_next(placeholder_next)
{}
friend std::ostream&
operator<<(std::ostream& stream, const literal_t& value) {
stream << "literal_t(data='" << value.data << "', placeholder_next=" << value.placeholder_next << ")";
return stream;
}
};
constexpr
literal_t
next_literal(const string_view& string) {
size_t pos = 0;
while (pos < string.size()) {
if (string[pos] == '{') {
// Possible placeholder begin.
pos++;
if (pos == string.size()) {
// End of string - emit unclosed '{'.
throw std::out_of_range("unmatched '{' in format");
}
if (string[pos] == '{') {
// Matched '{{' - emit as single '{'.
pos++;
return {string.substr(0, pos - 1), false};
}
// This is a placeholder, emit full literal minis '{' character.
auto lit = string.substr(0, pos - 1);
pos += 1;
return {lit, true};
} else if (string[pos] == '}') {
pos++;
if (pos == string.size()) {
// End of string - emit unexpected '}'.
throw std::out_of_range("single '}' encountered in format string");
}
if (string[pos] == '}') {
// Matched '}}' - emit as single '}'.
pos++;
return {string.substr(0, pos - 1), false};
}
}
pos++;
}
return {string, false};
}
namespace blackhole {
namespace detail {
template<class T>
struct format_traits {
static inline
void
format(fmt::MemoryWriter& writer, const T& val) {
writer << val;
}
};
template<std::size_t N>
struct formatter {
const literal_t literal;
const formatter<N - 1> next;
public:
constexpr
formatter(const string_view& format) :
literal(::next_literal(format)),
// NOTE: 2 == placeholder.width.
next(format.substr(literal.placeholder_next ? literal.data.size() + 2 : literal.data.size() + 1))
{}
template<typename T, typename... Args>
constexpr
void
format(fmt::MemoryWriter& writer, const T& arg, const Args&... args) const {
writer << fmt::StringRef(literal.data.data(), literal.data.size());
if (literal.placeholder_next) {
format_traits<T>::format(writer, arg);
next.format(writer, args...);
} else {
next.format(writer, arg, args...);
}
}
template<class Stream>
Stream&
repr(Stream& stream) const {
stream << "formatter(" << literal << ", ";
next.repr(stream);
stream << ")";
return stream;
}
};
template<>
struct formatter<0>;
template<>
struct formatter<1> {
const literal_t literal;
public:
constexpr
formatter(const string_view& format) :
literal({format, false})
{}
// TODO: I can calcualte attributes count here to avoid unecessary Args... paramteter, cause
// it's always empty.
template<typename... Args>
constexpr
void
format(fmt::MemoryWriter& writer, const Args&...) const {
writer << fmt::StringRef(literal.data.data(), literal.data.size());
}
template<class Stream>
Stream&
repr(Stream& stream) const {
stream << "formatter(" << literal << ")";
return stream;
}
};
} // namespace detail
} // namespace blackhole
<commit_msg>refactor(sandbox): eliminate dead code<commit_after>#pragma once
#include <array>
#include <iostream>
#include <string>
#include <cppformat/format.h>
#include "blackhole/cpp17/optional.hpp"
#include "blackhole/cpp17/string_view.hpp"
using blackhole::cpp17::string_view;
constexpr
std::size_t
parse_argument(const string_view& string, std::size_t& pos) {
char c = string[pos];
if (c == '}') {
return 2;
} else {
throw std::out_of_range("only {} is supported for compile-time analysys for now, sorry");
}
}
namespace blackhole {
namespace detail {
namespace cppformat = fmt;
/// Returns the number of literals which will be produced by formatter internally.
constexpr
std::size_t
literal_count(const string_view& format) {
// Always has at least one literal.
std::size_t result = 1;
if (format.size() == 0) {
return result;
}
std::size_t id = 0;
bool last_literal_has_next_placeholder = false;
bool has_some_bytes = false;
while (id < format.size()) {
char curr = format[id];
if (curr == '{') {
++id;
if (id >= format.size()) {
throw std::out_of_range("unmatched '{' in format");
}
curr = format[id];
if (curr == '{') {
++id;
++result;
continue;
} else {
const auto size = ::parse_argument(format, id);
id += size - 1;
++result;
has_some_bytes = false;
last_literal_has_next_placeholder = true;
continue;
}
} else if (curr == '}') {
++id;
if (id >= format.size()) {
throw std::out_of_range("single '}' encountered in format string");
}
curr = format[id];
if (curr == '}') {
++id;
++result;
has_some_bytes = false;
continue;
} else {
throw std::out_of_range("single '}' encountered in format string");
}
}
++id;
has_some_bytes = true;
}
return result;
}
} // namespace detail
} // namespace blackhole
struct literal_t {
string_view data;
bool placeholder_next;
constexpr
literal_t(string_view data, bool placeholder_next):
data(data),
placeholder_next(placeholder_next)
{}
friend std::ostream&
operator<<(std::ostream& stream, const literal_t& value) {
stream << "literal_t(data='" << value.data << "', placeholder_next=" << value.placeholder_next << ")";
return stream;
}
};
constexpr
literal_t
next_literal(const string_view& string) {
size_t pos = 0;
while (pos < string.size()) {
if (string[pos] == '{') {
// Possible placeholder begin.
pos++;
if (pos == string.size()) {
// End of string - emit unclosed '{'.
throw std::out_of_range("unmatched '{' in format");
}
if (string[pos] == '{') {
// Matched '{{' - emit as single '{'.
pos++;
return {string.substr(0, pos - 1), false};
}
// This is a placeholder, emit full literal minis '{' character.
auto lit = string.substr(0, pos - 1);
pos += 1;
return {lit, true};
} else if (string[pos] == '}') {
pos++;
if (pos == string.size()) {
// End of string - emit unexpected '}'.
throw std::out_of_range("single '}' encountered in format string");
}
if (string[pos] == '}') {
// Matched '}}' - emit as single '}'.
pos++;
return {string.substr(0, pos - 1), false};
}
}
pos++;
}
return {string, false};
}
namespace blackhole {
namespace detail {
template<class T>
struct format_traits {
static inline
void
format(fmt::MemoryWriter& writer, const T& val) {
writer << val;
}
};
// TODO: Store placeholder number information too.
template<std::size_t N>
struct formatter {
const literal_t literal;
const formatter<N - 1> next;
public:
constexpr
formatter(const string_view& format) :
literal(::next_literal(format)),
// NOTE: 2 == placeholder.width.
next(format.substr(literal.placeholder_next ? literal.data.size() + 2 : literal.data.size() + 1))
{}
template<typename T, typename... Args>
constexpr
void
format(fmt::MemoryWriter& writer, const T& arg, const Args&... args) const {
writer << fmt::StringRef(literal.data.data(), literal.data.size());
if (literal.placeholder_next) {
format_traits<T>::format(writer, arg);
next.format(writer, args...);
} else {
next.format(writer, arg, args...);
}
}
template<class Stream>
Stream&
repr(Stream& stream) const {
stream << "formatter(" << literal << ", ";
next.repr(stream);
stream << ")";
return stream;
}
};
template<>
struct formatter<0>;
template<>
struct formatter<1> {
const literal_t literal;
public:
constexpr
formatter(const string_view& format) :
literal({format, false})
{}
// TODO: I can calcualte attributes count here to avoid unecessary Args... paramteter, cause
// it's always empty.
template<typename... Args>
constexpr
void
format(fmt::MemoryWriter& writer, const Args&...) const {
writer << fmt::StringRef(literal.data.data(), literal.data.size());
}
template<class Stream>
Stream&
repr(Stream& stream) const {
stream << "formatter(" << literal << ")";
return stream;
}
};
} // namespace detail
} // namespace blackhole
<|endoftext|> |
<commit_before>/**
* This file defines utilities to provide diagnostics to the user from the
* result of the analysis.
*/
#ifndef D2_CORE_DIAGNOSTIC_HPP
#define D2_CORE_DIAGNOSTIC_HPP
#include <d2/detail/decl.hpp>
#include <d2/lock_id.hpp>
#include <d2/thread_id.hpp>
#include <boost/assert.hpp>
#include <boost/move/utility.hpp>
#include <boost/operators.hpp>
#include <iosfwd>
#include <vector>
namespace d2 {
namespace diagnostic_detail {
//! Class representing the state of a single deadlocked thread.
struct deadlocked_thread : boost::partially_ordered<deadlocked_thread> {
/**
* Create a `deadlocked_thread` with the thread identifier `tid`,
* holding a sequence of `locks` and waiting for the `waiting_for` lock.
*/
template <typename Container>
deadlocked_thread(ThreadId tid, BOOST_FWD_REF(Container) locks,
LockId waiting_for)
: tid(tid), holding(boost::forward<Container>(locks)),
waiting_for(waiting_for)
{
BOOST_ASSERT_MSG(holding.size() >= 1,
"a thread can't be deadlocked if it is not holding at least one "
"lock while waiting for another one");
}
/**
* Create a `deadlocked_thread` with the thread identifier `tid`,
* holding a sequence of `locks` in the range delimited by [first, last)
* and waiting for the `waiting_for` lock.
*/
template <typename Iterator>
deadlocked_thread(ThreadId tid, BOOST_FWD_REF(Iterator) first,
BOOST_FWD_REF(Iterator) last, LockId waiting_for)
: tid(tid), holding(boost::forward<Iterator>(first),
boost::forward<Iterator>(last)),
waiting_for(waiting_for)
{
BOOST_ASSERT_MSG(holding.size() >= 1,
"a thread can't be deadlocked if it is not holding at least one "
"lock while waiting for another one");
}
//! Thread identifier of the deadlocked thread.
ThreadId tid;
//! Type of the sequence of locks held by the thread.
typedef std::vector<LockId> lock_sequence;
/**
* Collection of locks held by that thread at the moment of the deadlock.
* The locks are ordered in their order of acquisition.
*/
lock_sequence holding;
//! Identifier of the lock the thread is waiting after.
LockId waiting_for;
/**
* Return whether two `deadlocked_thread`s represent the same thread
* holding the same sequence of locks in the same order and waiting for
* the same lock.
*/
friend bool
operator==(deadlocked_thread const& a, deadlocked_thread const& b) {
return a.tid == b.tid &&
a.waiting_for == b.waiting_for &&
a.holding == b.holding;
}
/**
* Return whether `a`'s thread identifier is smaller than `b`'s.
*
* If both have the same thread identifier, the lock they are waiting
* for is compared. If these are the same, their sequences of held locks
* are compared lexicographically.
*
* @note While it is not generally useful to compare `deadlocked_thread`s
* together, it can be useful to store them in containers.
*/
friend bool
operator<(deadlocked_thread const& a, deadlocked_thread const& b) {
if (a.tid < b.tid)
return true;
else if (a.tid == b.tid)
return a.waiting_for < b.waiting_for ||
(a.waiting_for == b.waiting_for && a.holding < b.holding);
else
return false;
}
//! Print a human readable representation of a `deadlocked_thread`.
D2_DECL friend
std::ostream& operator<<(std::ostream&, deadlocked_thread const&);
};
/**
* Type representing a state which, if reached, would create a
* deadlock in the program.
*
* A thread identifier is guaranteed to appear at most once in the sequence
* of threads. Also, it is guaranteed that at least two threads are present
* in the sequence, otherwise a deadlock is impossible.
*/
class potential_deadlock : boost::less_than_comparable<potential_deadlock> {
void invariants() const {
BOOST_ASSERT_MSG(threads.size() >= 2,
"a deadlock can't happen with fewer than 2 threads");
BOOST_ASSERT_MSG(!has_duplicate_threads(),
"it makes no sense for the same thread to appear more than "
"once in the sequence of deadlocked threads");
}
/**
* Return whether the sequence of threads contains more than one thread
* with the same identifier.
*/
D2_DECL bool has_duplicate_threads() const;
public:
/**
* Create a `potential_deadlock` from a sequence of `deadlocked_thread`s
* delimited by [first, last).
*
* @pre A thread identifier appears at most once in the sequence.
* @pre There are at least two threads in the sequence, otherwise a
* deadlock is impossible.
*/
template <typename Iterator>
potential_deadlock(BOOST_FWD_REF(Iterator) first,
BOOST_FWD_REF(Iterator) last)
: threads(boost::forward<Iterator>(first),
boost::forward<Iterator>(last))
{
invariants();
}
/**
* Create a `potential_deadlock` from the `deadlocked_thread`s contained
* in `threads`.
*
* @pre A thread identifier appears at most once in the sequence.
* @pre There are at least two threads in the sequence, otherwise a
* deadlock is impossible.
*/
template <typename Container>
explicit potential_deadlock(BOOST_FWD_REF(Container) threads)
: threads(boost::forward<Container>(threads))
{
invariants();
}
/**
* Return the lexicographical comparison of the sequences of threads of
* two `potential_deadlock`s.
*
* @note This is mostly (if not only) useful to store
* `potential_deadlock`s in ordered containers.
*/
friend bool
operator<(potential_deadlock const& a, potential_deadlock const& b) {
return a.threads < b.threads;
}
/**
* Return whether a deadlock is equivalent to another, i.e. if it consists
* of the same sequence of threads in a possibly different order.
*/
D2_DECL bool is_equivalent_to(potential_deadlock const& other) const;
//! Type of the container holding the sequence of `deadlocked_thread`s.
typedef std::vector<deadlocked_thread> thread_sequence;
//! The actual sequence of threads involved in the deadlock.
thread_sequence threads;
//! Print a human readable representation of a `potential_deadlock`.
D2_DECL friend
std::ostream& operator<<(std::ostream&, potential_deadlock const&);
};
/**
* Write an explanation of the potential deadlock state in plain text to
* an output stream.
*
* Example output:
* <begin output>
* thread 1 acquired A, X, B
* while
* thread 2 acquired B, X, A
* which creates a deadlock if
* thread 1 acquires A and waits for B
* thread 2 acquires B and waits for A
* <end output>
*/
D2_DECL extern std::ostream&
plain_text_explanation(std::ostream&, potential_deadlock const&);
} // end namespace diagnostic_detail
namespace core {
using diagnostic_detail::deadlocked_thread;
using diagnostic_detail::plain_text_explanation;
using diagnostic_detail::potential_deadlock;
}
} // end namespace d2
#endif // !D2_CORE_DIAGNOSTIC_HPP
<commit_msg>Reformulate comment in diagnostic.hpp.<commit_after>/**
* This file defines utilities to provide diagnostics to the user from the
* result of the analysis.
*/
#ifndef D2_CORE_DIAGNOSTIC_HPP
#define D2_CORE_DIAGNOSTIC_HPP
#include <d2/detail/decl.hpp>
#include <d2/lock_id.hpp>
#include <d2/thread_id.hpp>
#include <boost/assert.hpp>
#include <boost/move/utility.hpp>
#include <boost/operators.hpp>
#include <iosfwd>
#include <vector>
namespace d2 {
namespace diagnostic_detail {
//! Class representing the state of a single deadlocked thread.
struct deadlocked_thread : boost::partially_ordered<deadlocked_thread> {
/**
* Create a `deadlocked_thread` with the thread identifier `tid`,
* holding a sequence of `locks` and waiting for the `waiting_for` lock.
*/
template <typename Container>
deadlocked_thread(ThreadId tid, BOOST_FWD_REF(Container) locks,
LockId waiting_for)
: tid(tid), holding(boost::forward<Container>(locks)),
waiting_for(waiting_for)
{
BOOST_ASSERT_MSG(holding.size() >= 1,
"a thread can't be deadlocked if it is not holding at least one "
"lock while waiting for another one");
}
/**
* Create a `deadlocked_thread` with the thread identifier `tid`,
* holding a sequence of `locks` in the range delimited by [first, last)
* and waiting for the `waiting_for` lock.
*/
template <typename Iterator>
deadlocked_thread(ThreadId tid, BOOST_FWD_REF(Iterator) first,
BOOST_FWD_REF(Iterator) last, LockId waiting_for)
: tid(tid), holding(boost::forward<Iterator>(first),
boost::forward<Iterator>(last)),
waiting_for(waiting_for)
{
BOOST_ASSERT_MSG(holding.size() >= 1,
"a thread can't be deadlocked if it is not holding at least one "
"lock while waiting for another one");
}
//! Thread identifier of the deadlocked thread.
ThreadId tid;
//! Type of the sequence of locks held by the thread.
typedef std::vector<LockId> lock_sequence;
/**
* Collection of locks held by that thread at the moment of the deadlock.
* The locks are sorted in their order of acquisition.
*/
lock_sequence holding;
//! Identifier of the lock the thread is waiting after.
LockId waiting_for;
/**
* Return whether two `deadlocked_thread`s represent the same thread
* holding the same sequence of locks in the same order and waiting for
* the same lock.
*/
friend bool
operator==(deadlocked_thread const& a, deadlocked_thread const& b) {
return a.tid == b.tid &&
a.waiting_for == b.waiting_for &&
a.holding == b.holding;
}
/**
* Return whether `a`'s thread identifier is smaller than `b`'s.
*
* If both have the same thread identifier, the lock they are waiting
* for is compared. If these are the same, their sequences of held locks
* are compared lexicographically.
*
* @note While it is not generally useful to compare `deadlocked_thread`s
* together, it can be useful to store them in containers.
*/
friend bool
operator<(deadlocked_thread const& a, deadlocked_thread const& b) {
if (a.tid < b.tid)
return true;
else if (a.tid == b.tid)
return a.waiting_for < b.waiting_for ||
(a.waiting_for == b.waiting_for && a.holding < b.holding);
else
return false;
}
//! Print a human readable representation of a `deadlocked_thread`.
D2_DECL friend
std::ostream& operator<<(std::ostream&, deadlocked_thread const&);
};
/**
* Type representing a state which, if reached, would create a
* deadlock in the program.
*
* A thread identifier is guaranteed to appear at most once in the sequence
* of threads. Also, it is guaranteed that at least two threads are present
* in the sequence, otherwise a deadlock is impossible.
*/
class potential_deadlock : boost::less_than_comparable<potential_deadlock> {
void invariants() const {
BOOST_ASSERT_MSG(threads.size() >= 2,
"a deadlock can't happen with fewer than 2 threads");
BOOST_ASSERT_MSG(!has_duplicate_threads(),
"it makes no sense for the same thread to appear more than "
"once in the sequence of deadlocked threads");
}
/**
* Return whether the sequence of threads contains more than one thread
* with the same identifier.
*/
D2_DECL bool has_duplicate_threads() const;
public:
/**
* Create a `potential_deadlock` from a sequence of `deadlocked_thread`s
* delimited by [first, last).
*
* @pre A thread identifier appears at most once in the sequence.
* @pre There are at least two threads in the sequence, otherwise a
* deadlock is impossible.
*/
template <typename Iterator>
potential_deadlock(BOOST_FWD_REF(Iterator) first,
BOOST_FWD_REF(Iterator) last)
: threads(boost::forward<Iterator>(first),
boost::forward<Iterator>(last))
{
invariants();
}
/**
* Create a `potential_deadlock` from the `deadlocked_thread`s contained
* in `threads`.
*
* @pre A thread identifier appears at most once in the sequence.
* @pre There are at least two threads in the sequence, otherwise a
* deadlock is impossible.
*/
template <typename Container>
explicit potential_deadlock(BOOST_FWD_REF(Container) threads)
: threads(boost::forward<Container>(threads))
{
invariants();
}
/**
* Return the lexicographical comparison of the sequences of threads of
* two `potential_deadlock`s.
*
* @note This is mostly (if not only) useful to store
* `potential_deadlock`s in ordered containers.
*/
friend bool
operator<(potential_deadlock const& a, potential_deadlock const& b) {
return a.threads < b.threads;
}
/**
* Return whether a deadlock is equivalent to another, i.e. if it consists
* of the same sequence of threads in a possibly different order.
*/
D2_DECL bool is_equivalent_to(potential_deadlock const& other) const;
//! Type of the container holding the sequence of `deadlocked_thread`s.
typedef std::vector<deadlocked_thread> thread_sequence;
//! The actual sequence of threads involved in the deadlock.
thread_sequence threads;
//! Print a human readable representation of a `potential_deadlock`.
D2_DECL friend
std::ostream& operator<<(std::ostream&, potential_deadlock const&);
};
/**
* Write an explanation of the potential deadlock state in plain text to
* an output stream.
*
* Example output:
* <begin output>
* thread 1 acquired A, X, B
* while
* thread 2 acquired B, X, A
* which creates a deadlock if
* thread 1 acquires A and waits for B
* thread 2 acquires B and waits for A
* <end output>
*/
D2_DECL extern std::ostream&
plain_text_explanation(std::ostream&, potential_deadlock const&);
} // end namespace diagnostic_detail
namespace core {
using diagnostic_detail::deadlocked_thread;
using diagnostic_detail::plain_text_explanation;
using diagnostic_detail::potential_deadlock;
}
} // end namespace d2
#endif // !D2_CORE_DIAGNOSTIC_HPP
<|endoftext|> |
<commit_before>#ifndef COMPASS_RT_X86_IMPL_H_
#define COMPASS_RT_X86_IMPL_H_
#include "detail/ct/detect_os.hpp"
#include "detail/ct/detect_compiler.hpp"
#include "detail/ct/detect_arch.hpp"
#include "detail/rt/x86_cpuid.hpp"
#include "detail/tags.hpp"
#include "detail/bit_view.hpp"
#include "detail/definitions.hpp"
#include <iostream>
#include <string>
namespace compass {
namespace runtime {
namespace detail {
static bool works(ct::x86_tag) {
auto regs = rt::cpuid(0);
if(regs.size())
return true;
else
return false;
}
static std::string vendor(ct::x86_tag) {
std::array<std::uint32_t,4> regs = rt::cpuid_to_int(0);
std::string vendor_name = "";
if(!regs.empty()){
vendor_name.resize(3*4);
std::copy(reinterpret_cast<char*>(®s[ct::ebx]),reinterpret_cast<char*>(®s[ct::ebx])+4,
vendor_name.begin());
std::copy(reinterpret_cast<char*>(®s[ct::edx]),reinterpret_cast<char*>(®s[ct::edx])+4,
vendor_name.begin()+4);
std::copy(reinterpret_cast<char*>(®s[ct::ecx]),reinterpret_cast<char*>(®s[ct::ecx])+4,
vendor_name.begin()+8);
}
return vendor_name;
}
static std::string brand(ct::x86_tag) {
std::string value = "";
auto regs = rt::cpuid_to_int(0x80000000);
if(regs[ct::eax] >= 0x80000004){
value.resize(48);
char* value_begin = &value[0];
for(std::uint32_t i = 2; i<5;++i){
auto ret = rt::cpuid_to_int(0x80000000 + i);
for(std::uint32_t r = 0; r<4;++r){
std::uint32_t* tgt = reinterpret_cast<std::uint32_t*>(value_begin + (i-2)*16u + r*4u);
*tgt = ret[r];
}
}
}
return value;
}
static std::string device_name(ct::x86_tag) {
std::string brand_str = compass::runtime::detail::brand(ct::x86_tag());
std::string vendor = compass::runtime::detail::vendor(ct::x86_tag());
std::size_t find_pos = 0;
if((find_pos = vendor.find("Genuine"))!=std::string::npos){
vendor.erase(find_pos,7);
}
std::string value = "";
if(brand_str.find(vendor) != std::string::npos){
//based on the Intel chip test strings that are known
auto second_bracket_itr = brand_str.rfind(")");
auto last_at_itr = brand_str.rfind("@");
value = brand_str.substr(second_bracket_itr,last_at_itr-second_bracket_itr);
if((find_pos = value.find(" CPU"))!=std::string::npos){
value.erase(find_pos,4);
}
}
return value;
}
static bool has(feature::sse , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::edx].test(25);
return value;
}
static bool has(feature::sse2 , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::edx].test(26);
return value;
}
static bool has(feature::sse3 , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::ecx].test(9) | regs[ct::ecx].test(0) | regs[ct::ecx].test(3);
return value;
}
static bool has(feature::sse4 , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::ecx].test(19) | regs[ct::ecx].test(20);
return value;
}
static bool has(feature::avx , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::ecx].test(28);
return value;
}
static bool has(feature::avx2 , ct::x86_tag){
auto regs = rt::cpuid_to_int(7,7,0,0);
bool value = compass::utility::bit_view<std::uint32_t>(regs[ct::ebx]).test(5);
return value;
}
};
};
};
#endif /* COMPASS_RT_X86_IMPL_H_ */
<commit_msg>adapted avx2 finder<commit_after>#ifndef COMPASS_RT_X86_IMPL_H_
#define COMPASS_RT_X86_IMPL_H_
#include "detail/ct/detect_os.hpp"
#include "detail/ct/detect_compiler.hpp"
#include "detail/ct/detect_arch.hpp"
#include "detail/rt/x86_cpuid.hpp"
#include "detail/tags.hpp"
#include "detail/bit_view.hpp"
#include "detail/definitions.hpp"
#include <iostream>
#include <string>
namespace compass {
namespace runtime {
namespace detail {
static bool works(ct::x86_tag) {
auto regs = rt::cpuid(0);
if(regs.size())
return true;
else
return false;
}
static std::string vendor(ct::x86_tag) {
std::array<std::uint32_t,4> regs = rt::cpuid_to_int(0);
std::string vendor_name = "";
if(!regs.empty()){
vendor_name.resize(3*4);
std::copy(reinterpret_cast<char*>(®s[ct::ebx]),reinterpret_cast<char*>(®s[ct::ebx])+4,
vendor_name.begin());
std::copy(reinterpret_cast<char*>(®s[ct::edx]),reinterpret_cast<char*>(®s[ct::edx])+4,
vendor_name.begin()+4);
std::copy(reinterpret_cast<char*>(®s[ct::ecx]),reinterpret_cast<char*>(®s[ct::ecx])+4,
vendor_name.begin()+8);
}
return vendor_name;
}
static std::string brand(ct::x86_tag) {
std::string value = "";
auto regs = rt::cpuid_to_int(0x80000000);
if(regs[ct::eax] >= 0x80000004){
value.resize(48);
char* value_begin = &value[0];
for(std::uint32_t i = 2; i<5;++i){
auto ret = rt::cpuid_to_int(0x80000000 + i);
for(std::uint32_t r = 0; r<4;++r){
std::uint32_t* tgt = reinterpret_cast<std::uint32_t*>(value_begin + (i-2)*16u + r*4u);
*tgt = ret[r];
}
}
}
return value;
}
static std::string device_name(ct::x86_tag) {
std::string brand_str = compass::runtime::detail::brand(ct::x86_tag());
std::string vendor = compass::runtime::detail::vendor(ct::x86_tag());
std::size_t find_pos = 0;
if((find_pos = vendor.find("Genuine"))!=std::string::npos){
vendor.erase(find_pos,7);
}
std::string value = "";
if(brand_str.find(vendor) != std::string::npos){
//based on the Intel chip test strings that are known
auto second_bracket_itr = brand_str.rfind(")");
auto last_at_itr = brand_str.rfind("@");
value = brand_str.substr(second_bracket_itr,last_at_itr-second_bracket_itr);
if((find_pos = value.find(" CPU"))!=std::string::npos){
value.erase(find_pos,4);
}
}
return value;
}
static bool has(feature::sse , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::edx].test(25);
return value;
}
static bool has(feature::sse2 , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::edx].test(26);
return value;
}
static bool has(feature::sse3 , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::ecx].test(9) | regs[ct::ecx].test(0) | regs[ct::ecx].test(3);
return value;
}
static bool has(feature::sse4 , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::ecx].test(19) | regs[ct::ecx].test(20);
return value;
}
static bool has(feature::avx , ct::x86_tag){
std::array<std::bitset<32>,4> regs = rt::cpuid(1);
if(regs.empty()){
std::cerr << "unsupported cpuid level detected\n";
}
bool value = regs[ct::ecx].test(28);
return value;
}
static bool has(feature::avx2 , ct::x86_tag){
auto regs = rt::cpuid_to_int(7,0,0,0);
bool value = compass::utility::bit_view<std::uint32_t>(regs[ct::ebx]).test(5);
return value;
}
};
};
};
#endif /* COMPASS_RT_X86_IMPL_H_ */
<|endoftext|> |
<commit_before>#include <algorithm>
#include "xUnit++/xUnit++.h"
#include "FileDataspace.hpp"
template<typename DS>
bool containsDS(DS ds, const K3::Value& val)
{
return ds.template fold<bool>(
[val](bool fnd, K3::Value cur) {
if (fnd || val == cur)
return true;
else
return fnd;
}, false);
}
template<typename DS>
unsigned sizeDS(DS ds)
{
return ds.template fold<unsigned>(
[](unsigned count, K3::Value) {
return count + 1;
}, 0);
}
class ElementNotFoundException : public std::runtime_error
{
public:
ElementNotFoundException(const K3::Value& val)
: std::runtime_error("Could not find element " + val)
{}
};
class ExtraElementsException : public std::runtime_error
{
public:
ExtraElementsException(unsigned i)
: std::runtime_error("Dataspace had " + toString(i) + " extra elements")
{ }
};
template<typename DS>
std::shared_ptr<DS> findAndRemoveElement(std::shared_ptr<DS> ds, const K3::Value& val)
{
if (!ds)
return std::shared_ptr<DS>(nullptr);
else {
if (containsDS(*ds, val)) {
ds->delete_first(val);
return ds;
}
else
throw ElementNotFoundException(val);
}
}
template<typename DS>
bool compareDataspaceToList(DS dataspace, std::vector<K3::Value> l)
{
std::shared_ptr<DS> ds_ptr = std::make_shared<DS>(dataspace);
std::shared_ptr<DS> result = std::accumulate(begin(l), end(l), ds_ptr,
[](std::shared_ptr<DS> ds, K3::Value cur_val) {
return findAndRemoveElement(ds, cur_val);
});
if (result) {
auto s = sizeDS(*result);
if (s == 0)
return true;
else
throw ExtraElementsException(s);
}
else
return false;
}
template<typename DS>
bool emptyPeek(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
std::shared_ptr<K3::Value> result = d.peek();
return result == nullptr;
}
template<typename DS>
bool testEmptyFold(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
unsigned counter = d.template fold<unsigned>(
[](unsigned accum, K3::Value) {
return accum + 1;
}, 0);
return counter == 0;
}
const std::vector<K3::Value> test_lst({"1", "2", "3", "4", "4", "100"});
template<typename DS>
bool testPeek(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
std::shared_ptr<K3::Value> peekResult = test_ds.peek();
if (!peekResult)
throw std::runtime_error("Peek returned nothing!");
else
return containsDS(test_ds, *peekResult);
}
template<typename DS>
bool testInsert(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get());
for( K3::Value val : test_lst )
test_ds.insert_basic(val);
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("3");
test_ds.delete_first("4");
std::vector<K3::Value> deleted_lst({"1", "2", "4", "100"});
return compareDataspaceToList(test_ds, deleted_lst);
}
template<typename DS>
bool testMissingDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("5");
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testUpdate(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("1", "4");
std::vector<K3::Value> updated_answer({"4", "2", "3", "4", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMultiple(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("4", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "5", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMissing(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("40", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "4", "4", "100", "5"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testFold(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
unsigned test_sum = test_ds.template fold<unsigned>(
[](unsigned sum, K3::Value val) {
sum += fromString<unsigned>(val);
return sum;
}, 0);
return test_sum == 114;
}
template<typename DS>
bool testMap(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS mapped_ds = test_ds.map(
[](K3::Value val) {
return toString(fromString<int>(val) + 5);
});
std::vector<K3::Value> mapped_answer({"6", "7", "8", "9", "9", "105"});
return compareDataspaceToList(mapped_ds, mapped_answer);
}
template<typename DS>
bool testFilter(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS filtered = test_ds.filter([](K3::Value val) {
return fromString<int>(val) > 50;
});
std::vector<K3::Value> filtered_answer({"100"});
return compareDataspaceToList(filtered, filtered_answer);
}
template<typename DS>
bool testCombine(std::shared_ptr<K3::Engine> engine)
{
DS left_ds(engine.get(), begin(test_lst), end(test_lst));
DS right_ds(engine.get(), begin(test_lst), end(test_lst));
DS combined = left_ds.combine(right_ds);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
bool testCombineSelf(std::shared_ptr<K3::Engine> engine)
{
DS self(engine.get(), begin(test_lst), end(test_lst));
DS combined = self.combine(self);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
std::shared_ptr<std::tuple<DS, DS>> split_findAndRemoveElement(std::shared_ptr<std::tuple<DS, DS>> maybeTuple, K3::Value cur_val)
{
typedef std::shared_ptr<std::tuple<DS, DS>> MaybePair;
if (!maybeTuple) {
return nullptr;
}
else {
DS& left = std::get<0>(*maybeTuple);
DS& right = std::get<1>(*maybeTuple);
if (containsDS(left, cur_val)) {
left.delete_first(cur_val);
// TODO copying everywhere!
// this copies the DS into the tuple, then the tuple is copied into the new target of the shared_ptr
return std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
}
else if (containsDS(right, cur_val)) {
right.delete_first(cur_val);
// TODO see above
return std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
}
else {
throw ElementNotFoundException(cur_val);
return MaybePair(nullptr);
}
}
}
template<typename DS>
bool testSplit(std::shared_ptr<K3::Engine> engine)
{
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
DS first_ds(engine.get(), begin(long_lst), end(long_lst));
std::tuple<DS, DS> split_pair = first_ds.split();
DS& left = std::get<0>(split_pair);
DS& right = std::get<1>(split_pair);
unsigned leftLen = sizeDS(left);
unsigned rightLen = sizeDS(right);
// TODO should the >= be just > ?
if (leftLen >= long_lst.size() || rightLen >= long_lst.size() || leftLen + rightLen > long_lst.size())
return false;
else {
std::shared_ptr<std::tuple<DS, DS>> remainders = std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
for (K3::Value val : long_lst)
remainders = split_findAndRemoveElement(remainders, val);
if (!remainders) {
return false;
}
else {
const DS& l = std::get<0>(*remainders);
const DS& r = std::get<1>(*remainders);
return (sizeDS(l) == 0 && sizeDS(r) == 0);
}
}
}
// TODO This just makes sure that nothing crashes, but should probably check for correctness also
// This test is commented out because it segfaults clang 3.4. It's bug #18473.
// There's a temporary fix in r200954 that may be included in 3.4.1, but that's not released yet.
//template<typename DS>
//bool insertInsideMap(std::shared_ptr<K3::Engine> engine)
//{
// DS outer_ds(engine.get(), begin(test_lst), end(test_lst));
// DS result_ds = outer_ds.map([&outer_ds, &v, &v4](K3::Value cur_val) {
// outer_ds.insert_basic("256");
// return "4";
// });
// return true;
//}
// Engine setup
std::shared_ptr<K3::Engine> buildEngine()
{
// Configure engine components
bool simulation = true;
K3::SystemEnvironment s_env = K3::defaultEnvironment();
auto i_cdec = std::shared_ptr<K3::InternalCodec>(new K3::DefaultInternalCodec());
// Construct an engine
K3::Engine * engine = new K3::Engine(simulation, s_env, i_cdec);
return std::shared_ptr<K3::Engine>(engine);
}
void callTest(std::function<bool(std::shared_ptr<K3::Engine>)> testFunc)
{
auto engine = buildEngine();
bool success = false;
try {
success = testFunc(engine);
xUnitpp::Assert.Equal(success, true);
}
catch( const std::exception& e)
{
xUnitpp::Assert.Fail() << e.what();
}
}
#define MAKE_TEST(name, function, ds) \
FACT(name) { callTest(function<ds>); }
SUITE("List Dataspace") {
MAKE_TEST( "EmptyPeek", emptyPeek, ListDataspace)
MAKE_TEST( "Fold on Empty List Test", testEmptyFold, ListDataspace)
MAKE_TEST( "Peek Test", testPeek, ListDataspace)
MAKE_TEST( "Insert Test", testInsert, ListDataspace)
MAKE_TEST( "Delete Test", testDelete, ListDataspace)
MAKE_TEST( "Delete of missing element Test", testMissingDelete, ListDataspace)
MAKE_TEST( "Update Test", testUpdate, ListDataspace)
MAKE_TEST( "Update Multiple Test", testUpdateMultiple, ListDataspace)
MAKE_TEST( "Update missing element Test", testUpdateMissing, ListDataspace)
MAKE_TEST( "Fold Test", testFold, ListDataspace)
MAKE_TEST( "Map Test", testMap, ListDataspace)
MAKE_TEST( "Filter Test", testFilter, ListDataspace)
MAKE_TEST( "Combine Test", testCombine, ListDataspace)
MAKE_TEST( "Combine with Self Test", testCombineSelf, ListDataspace)
MAKE_TEST( "Split Test", testSplit, ListDataspace)
MAKE_TEST( "Insert inside map", insertInsideMap, ListDataspace)
}
//SUITE("File Dataspace") {
// MAKE_TEST( "EmptyPeek", emptyPeek, FileDataspace)
// MAKE_TEST( "Fold on Empty List Test", testEmptyFold, FileDataspace)
// MAKE_TEST( "Peek Test", testPeek, FileDataspace)
// /*MAKE_TEST( "Insert Test", testInsert, FileDataspace)
// MAKE_TEST( "Delete Test", testDelete, FileDataspace)
// MAKE_TEST( "Delete of missing element Test", testMissingDelete, FileDataspace)
// MAKE_TEST( "Update Test", testUpdate, FileDataspace)
// MAKE_TEST( "Update Multiple Test", testUpdateMultiple, FileDataspace)
// MAKE_TEST( "Update missing element Test", testUpdateMissing, FileDataspace)
// MAKE_TEST( "Fold Test", testFold, FileDataspace)
// MAKE_TEST( "Map Test", testMap, FileDataspace)
// MAKE_TEST( "Filter Test", testFilter, FileDataspace)
// MAKE_TEST( "Combine Test", testCombine, FileDataspace)
// MAKE_TEST( "Combine with Self Test", testCombineSelf, FileDataspace)
// MAKE_TEST( "Split Test", testSplit, FileDataspace)
// MAKE_TEST( "Insert inside map", insertInsideMap, FileDataspace)*/
//}
//MAKE_TEST_GROUP("List Dataspace", ListDataspace)
//MAKE_TEST_GROUP("File Dataspace", FileDataspace)
<commit_msg>Rewrite FileDataspaceTest to be standalone for debugging<commit_after>#include <algorithm>
//#include "xUnit++/xUnit++.h"
#include "FileDataspace.hpp"
template<typename DS>
bool containsDS(DS ds, const K3::Value& val)
{
return ds.template fold<bool>(
[val](bool fnd, K3::Value cur) {
if (fnd || val == cur)
return true;
else
return fnd;
}, false);
}
template<typename DS>
unsigned sizeDS(DS ds)
{
return ds.template fold<unsigned>(
[](unsigned count, K3::Value) {
return count + 1;
}, 0);
}
class ElementNotFoundException : public std::runtime_error
{
public:
ElementNotFoundException(const K3::Value& val)
: std::runtime_error("Could not find element " + val)
{}
};
class ExtraElementsException : public std::runtime_error
{
public:
ExtraElementsException(unsigned i)
: std::runtime_error("Dataspace had " + toString(i) + " extra elements")
{ }
};
template<typename DS>
std::shared_ptr<DS> findAndRemoveElement(std::shared_ptr<DS> ds, const K3::Value& val)
{
if (!ds)
return std::shared_ptr<DS>(nullptr);
else {
if (containsDS(*ds, val)) {
ds->delete_first(val);
return ds;
}
else
throw ElementNotFoundException(val);
}
}
template<typename DS>
bool compareDataspaceToList(DS dataspace, std::vector<K3::Value> l)
{
std::shared_ptr<DS> ds_ptr = std::make_shared<DS>(dataspace);
std::shared_ptr<DS> result = std::accumulate(begin(l), end(l), ds_ptr,
[](std::shared_ptr<DS> ds, K3::Value cur_val) {
return findAndRemoveElement(ds, cur_val);
});
if (result) {
auto s = sizeDS(*result);
if (s == 0)
return true;
else
throw ExtraElementsException(s);
}
else
return false;
}
template<typename DS>
bool emptyPeek(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
std::shared_ptr<K3::Value> result = d.peek();
return result == nullptr;
}
template<typename DS>
bool testEmptyFold(std::shared_ptr<K3::Engine> engine)
{
DS d(engine.get());
unsigned counter = d.template fold<unsigned>(
[](unsigned accum, K3::Value) {
return accum + 1;
}, 0);
return counter == 0;
}
const std::vector<K3::Value> test_lst({"1", "2", "3", "4", "4", "100"});
template<typename DS>
bool testPeek(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
std::shared_ptr<K3::Value> peekResult = test_ds.peek();
if (!peekResult)
throw std::runtime_error("Peek returned nothing!");
else
return containsDS(test_ds, *peekResult);
}
template<typename DS>
bool testInsert(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get());
for( K3::Value val : test_lst )
test_ds.insert_basic(val);
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("3");
test_ds.delete_first("4");
std::vector<K3::Value> deleted_lst({"1", "2", "4", "100"});
return compareDataspaceToList(test_ds, deleted_lst);
}
template<typename DS>
bool testMissingDelete(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.delete_first("5");
return compareDataspaceToList(test_ds, test_lst);
}
template<typename DS>
bool testUpdate(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("1", "4");
std::vector<K3::Value> updated_answer({"4", "2", "3", "4", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMultiple(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("4", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "5", "4", "100"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testUpdateMissing(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
test_ds.update_first("40", "5");
std::vector<K3::Value> updated_answer({"1", "2", "3", "4", "4", "100", "5"});
return compareDataspaceToList(test_ds, updated_answer);
}
template<typename DS>
bool testFold(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
unsigned test_sum = test_ds.template fold<unsigned>(
[](unsigned sum, K3::Value val) {
sum += fromString<unsigned>(val);
return sum;
}, 0);
return test_sum == 114;
}
template<typename DS>
bool testMap(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS mapped_ds = test_ds.map(
[](K3::Value val) {
return toString(fromString<int>(val) + 5);
});
std::vector<K3::Value> mapped_answer({"6", "7", "8", "9", "9", "105"});
return compareDataspaceToList(mapped_ds, mapped_answer);
}
template<typename DS>
bool testFilter(std::shared_ptr<K3::Engine> engine)
{
DS test_ds(engine.get(), begin(test_lst), end(test_lst));
DS filtered = test_ds.filter([](K3::Value val) {
return fromString<int>(val) > 50;
});
std::vector<K3::Value> filtered_answer({"100"});
return compareDataspaceToList(filtered, filtered_answer);
}
template<typename DS>
bool testCombine(std::shared_ptr<K3::Engine> engine)
{
DS left_ds(engine.get(), begin(test_lst), end(test_lst));
DS right_ds(engine.get(), begin(test_lst), end(test_lst));
DS combined = left_ds.combine(right_ds);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
bool testCombineSelf(std::shared_ptr<K3::Engine> engine)
{
DS self(engine.get(), begin(test_lst), end(test_lst));
DS combined = self.combine(self);
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
return compareDataspaceToList(combined, long_lst);
}
template<typename DS>
std::shared_ptr<std::tuple<DS, DS>> split_findAndRemoveElement(std::shared_ptr<std::tuple<DS, DS>> maybeTuple, K3::Value cur_val)
{
typedef std::shared_ptr<std::tuple<DS, DS>> MaybePair;
if (!maybeTuple) {
return nullptr;
}
else {
DS& left = std::get<0>(*maybeTuple);
DS& right = std::get<1>(*maybeTuple);
if (containsDS(left, cur_val)) {
left.delete_first(cur_val);
// TODO copying everywhere!
// this copies the DS into the tuple, then the tuple is copied into the new target of the shared_ptr
return std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
}
else if (containsDS(right, cur_val)) {
right.delete_first(cur_val);
// TODO see above
return std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
}
else {
throw ElementNotFoundException(cur_val);
return MaybePair(nullptr);
}
}
}
template<typename DS>
bool testSplit(std::shared_ptr<K3::Engine> engine)
{
std::vector<K3::Value> long_lst(test_lst);
long_lst.insert(end(long_lst), begin(test_lst), end(test_lst));
DS first_ds(engine.get(), begin(long_lst), end(long_lst));
std::tuple<DS, DS> split_pair = first_ds.split();
DS& left = std::get<0>(split_pair);
DS& right = std::get<1>(split_pair);
unsigned leftLen = sizeDS(left);
unsigned rightLen = sizeDS(right);
// TODO should the >= be just > ?
if (leftLen >= long_lst.size() || rightLen >= long_lst.size() || leftLen + rightLen > long_lst.size())
return false;
else {
std::shared_ptr<std::tuple<DS, DS>> remainders = std::make_shared<std::tuple<DS, DS>>(std::make_tuple(left, right));
for (K3::Value val : long_lst)
remainders = split_findAndRemoveElement(remainders, val);
if (!remainders) {
return false;
}
else {
const DS& l = std::get<0>(*remainders);
const DS& r = std::get<1>(*remainders);
return (sizeDS(l) == 0 && sizeDS(r) == 0);
}
}
}
// TODO This just makes sure that nothing crashes, but should probably check for correctness also
// This test is commented out because it segfaults clang 3.4. It's bug #18473.
// There's a temporary fix in r200954 that may be included in 3.4.1, but that's not released yet.
//template<typename DS>
//bool insertInsideMap(std::shared_ptr<K3::Engine> engine)
//{
// DS outer_ds(engine.get(), begin(test_lst), end(test_lst));
// DS result_ds = outer_ds.map([&outer_ds, &v, &v4](K3::Value cur_val) {
// outer_ds.insert_basic("256");
// return "4";
// });
// return true;
//}
// Engine setup
std::shared_ptr<K3::Engine> buildEngine()
{
// Configure engine components
bool simulation = true;
K3::SystemEnvironment s_env = K3::defaultEnvironment();
auto i_cdec = std::shared_ptr<K3::InternalCodec>(new K3::DefaultInternalCodec());
// Construct an engine
K3::Engine * engine = new K3::Engine(simulation, s_env, i_cdec);
return std::shared_ptr<K3::Engine>(engine);
}
void callTest(std::function<bool(std::shared_ptr<K3::Engine>)> testFunc)
{
auto engine = buildEngine();
bool success = false;
try {
success = testFunc(engine);
assert(success == true);
//xUnitpp::Assert.Equal(success, true);
}
catch( std::exception& e)
{
std::cerr << e.what();
assert(false);
//xUnitpp::Assert.Fail() << e.what();
}
}
//#define MAKE_TEST(name, function, ds) \
// FACT(name) { callTest(function<ds>); }
#define MAKE_TEST(name, function, ds) \
callTest(function<ds>);
//SUITE("List Dataspace") {
// MAKE_TEST( "EmptyPeek", emptyPeek, ListDataspace)
// MAKE_TEST( "Fold on Empty List Test", testEmptyFold, ListDataspace)
// MAKE_TEST( "Peek Test", testPeek, ListDataspace)
// MAKE_TEST( "Insert Test", testInsert, ListDataspace)
// MAKE_TEST( "Delete Test", testDelete, ListDataspace)
// MAKE_TEST( "Delete of missing element Test", testMissingDelete, ListDataspace)
// MAKE_TEST( "Update Test", testUpdate, ListDataspace)
// MAKE_TEST( "Update Multiple Test", testUpdateMultiple, ListDataspace)
// MAKE_TEST( "Update missing element Test", testUpdateMissing, ListDataspace)
// MAKE_TEST( "Fold Test", testFold, ListDataspace)
// MAKE_TEST( "Map Test", testMap, ListDataspace)
// MAKE_TEST( "Filter Test", testFilter, ListDataspace)
// MAKE_TEST( "Combine Test", testCombine, ListDataspace)
// MAKE_TEST( "Combine with Self Test", testCombineSelf, ListDataspace)
// MAKE_TEST( "Split Test", testSplit, ListDataspace)
// MAKE_TEST( "Insert inside map", insertInsideMap, ListDataspace)
//}
//SUITE("File Dataspace") {
int main()
{
MAKE_TEST( "EmptyPeek", emptyPeek, FileDataspace)
MAKE_TEST( "Fold on Empty List Test", testEmptyFold, FileDataspace)
MAKE_TEST( "Peek Test", testPeek, FileDataspace)
MAKE_TEST( "Insert Test", testInsert, FileDataspace)
MAKE_TEST( "Delete Test", testDelete, FileDataspace)
MAKE_TEST( "Delete of missing element Test", testMissingDelete, FileDataspace)
MAKE_TEST( "Update Test", testUpdate, FileDataspace)
MAKE_TEST( "Update Multiple Test", testUpdateMultiple, FileDataspace)
MAKE_TEST( "Update missing element Test", testUpdateMissing, FileDataspace)
MAKE_TEST( "Fold Test", testFold, FileDataspace)
MAKE_TEST( "Map Test", testMap, FileDataspace)
MAKE_TEST( "Filter Test", testFilter, FileDataspace)
MAKE_TEST( "Combine Test", testCombine, FileDataspace)
MAKE_TEST( "Combine with Self Test", testCombineSelf, FileDataspace)
MAKE_TEST( "Split Test", testSplit, FileDataspace)
//MAKE_TEST( "Insert inside map", insertInsideMap, FileDataspace)
}
//MAKE_TEST_GROUP("List Dataspace", ListDataspace)
//MAKE_TEST_GROUP("File Dataspace", FileDataspace)
<|endoftext|> |
<commit_before>#include "qhexbuffer.h"
#include <QBuffer>
QHexBuffer::QHexBuffer(QObject *parent) : QObject(parent) { }
uchar QHexBuffer::at(int idx) { return this->read(idx, 1).front(); }
bool QHexBuffer::isEmpty() const { return this->length() <= 0; }
void QHexBuffer::replace(int offset, const QByteArray &data)
{
this->remove(offset, data.length());
this->insert(offset, data);
}
void QHexBuffer::read(char *data, int size)
{
QBuffer* buffer = new QBuffer(this);
buffer->setData(data, size);
if(!buffer->isOpen())
buffer->open(QBuffer::ReadWrite);
this->read(buffer);
}
void QHexBuffer::read(const QByteArray &ba)
{
QBuffer* buffer = new QBuffer(this);
if(!buffer->isOpen())
buffer->open(QBuffer::ReadWrite);
buffer->setData(ba);
this->read(buffer);
}
<commit_msg>QHexBuffer: Qt 5.9 compatibility<commit_after>#include "qhexbuffer.h"
#include <QBuffer>
QHexBuffer::QHexBuffer(QObject *parent) : QObject(parent) { }
uchar QHexBuffer::at(int idx) { return this->read(idx, 1)[0]; }
bool QHexBuffer::isEmpty() const { return this->length() <= 0; }
void QHexBuffer::replace(int offset, const QByteArray &data)
{
this->remove(offset, data.length());
this->insert(offset, data);
}
void QHexBuffer::read(char *data, int size)
{
QBuffer* buffer = new QBuffer(this);
buffer->setData(data, size);
if(!buffer->isOpen())
buffer->open(QBuffer::ReadWrite);
this->read(buffer);
}
void QHexBuffer::read(const QByteArray &ba)
{
QBuffer* buffer = new QBuffer(this);
if(!buffer->isOpen())
buffer->open(QBuffer::ReadWrite);
buffer->setData(ba);
this->read(buffer);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 - 2021, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BatchStatus.hpp"
#include "gtest/gtest.h"
#include <functional>
#include <unistd.h>
#include <sys/wait.h>
using geopm::BatchStatus;
using geopm::BatchStatusImp;
class BatchStatusTest : public ::testing::Test
{
protected:
void SetUp(void);
void TearDown(void);
int fork_other(std::function<void(void)> other_func);
std::string m_server_prefix;
std::string m_server_key;
};
int BatchStatusTest::fork_other(std::function<void(void)> other_func)
{
int result = fork();
if (result == 0) {
other_func();
exit(0);
}
return result;
}
void BatchStatusTest::SetUp(void)
{
m_server_prefix = "batch-status";
m_server_key = "test-key";
}
void BatchStatusTest::TearDown(void)
{
std::string path = m_server_prefix + "-in-" + m_server_key;
(void)unlink(path.c_str());
path = m_server_prefix + "-out-" + m_server_key;
(void)unlink(path.c_str());
}
TEST_F(BatchStatusTest, client_send_one)
{
int client_pid = getpid();
std::function<void(void)> test_func = [this, client_pid]()
{
std::shared_ptr<BatchStatus> server_status =
std::make_shared<BatchStatusImp>(client_pid,
this->m_server_key,
true,
this->m_server_prefix);
server_status->receive_message('a');
};
int server_pid = fork_other(test_func);
sleep(1);
std::shared_ptr<BatchStatus> client_status =
std::make_shared<BatchStatusImp>(0, m_server_key, false, m_server_prefix);
client_status->send_message('a');
waitpid(server_pid, nullptr, 0);
}
<commit_msg>Adding tests for BatchStatusSignal and BatchStatusFIFO<commit_after>/*
* Copyright (c) 2015 - 2021, Intel Corporation
*
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "BatchStatus.hpp"
#include "gtest/gtest.h"
#include <functional>
#include <unistd.h>
#include <sys/wait.h>
using geopm::BatchStatus;
using geopm::BatchStatusFIFO;
class BatchStatusTest : public ::testing::Test
{
protected:
void SetUp(void);
void TearDown(void);
int fork_other(std::function<void(void)> other_func);
std::string m_server_prefix;
std::string m_server_key;
};
int BatchStatusTest::fork_other(std::function<void(void)> other_func)
{
int result = fork();
if (result == 0) {
other_func();
exit(0);
}
return result;
}
void BatchStatusTest::SetUp(void)
{
m_server_prefix = "batch-status";
m_server_key = "test-key";
}
void BatchStatusTest::TearDown(void)
{
std::string path = m_server_prefix + "-in-" + m_server_key;
(void)unlink(path.c_str());
path = m_server_prefix + "-out-" + m_server_key;
(void)unlink(path.c_str());
}
TEST_F(BatchStatusTest, client_send_to_server_fifo)
{
int client_pid = getpid();
std::function<void(void)> test_func = [this, client_pid]()
{
auto server_status = BatchStatus::make_unique_server(
client_pid, this->m_server_key
);
server_status->receive_message(BatchStatus::M_MESSAGE_READ);
};
int server_pid = fork_other(test_func);
sleep(1); // context switch
auto client_status = BatchStatus::make_unique_client(m_server_key);
client_status->send_message(BatchStatus::M_MESSAGE_READ);
waitpid(server_pid, nullptr, 0); // reap child process
}
TEST_F(BatchStatusTest, server_send_to_client_fifo)
{
int client_pid = getpid();
std::function<void(void)> test_func = [this, client_pid]()
{
auto server_status = BatchStatus::make_unique_server(
client_pid, this->m_server_key
);
server_status->send_message(BatchStatus::M_MESSAGE_READ);
};
int server_pid = fork_other(test_func);
sleep(1); // context switch
auto client_status = BatchStatus::make_unique_client(m_server_key);
client_status->receive_message(BatchStatus::M_MESSAGE_READ);
waitpid(server_pid, nullptr, 0); // reap child process
}
TEST_F(BatchStatusTest, both_send_at_once_fifo)
{
int client_pid = getpid();
std::function<void(void)> test_func = [this, client_pid]()
{
auto server_status = BatchStatus::make_unique_server(
client_pid, this->m_server_key
);
server_status->send_message(BatchStatus::M_MESSAGE_WRITE);
server_status->receive_message(BatchStatus::M_MESSAGE_READ);
};
int server_pid = fork_other(test_func);
sleep(1); // context switch
auto client_status = BatchStatus::make_unique_client(m_server_key);
client_status->receive_message(BatchStatus::M_MESSAGE_WRITE);
client_status->send_message(BatchStatus::M_MESSAGE_READ);
waitpid(server_pid, nullptr, 0); // reap child process
}
TEST_F(BatchStatusTest, client_send_to_server_signal)
{
int client_pid = getpid();
std::function<void(void)> test_func = [this, client_pid]()
{
auto server_status = BatchStatus::make_unique_signal(client_pid);
server_status->receive_message(BatchStatus::M_MESSAGE_READ);
};
int server_pid = fork_other(test_func);
sleep(1); // context switch
auto client_status = BatchStatus::make_unique_signal(server_pid);
client_status->send_message(BatchStatus::M_MESSAGE_READ);
waitpid(server_pid, nullptr, 0); // reap child process
}
TEST_F(BatchStatusTest, server_send_to_client_signal)
{
int client_pid = getpid();
std::function<void(void)> test_func = [this, client_pid]()
{
auto server_status = BatchStatus::make_unique_signal(client_pid);
server_status->send_message(BatchStatus::M_MESSAGE_READ);
};
int server_pid = fork_other(test_func);
sleep(1); // context switch
auto client_status = BatchStatus::make_unique_signal(server_pid);
client_status->receive_message(BatchStatus::M_MESSAGE_READ);
waitpid(server_pid, nullptr, 0); // reap child process
}
TEST_F(BatchStatusTest, both_send_at_once_signal)
{
int client_pid = getpid();
std::function<void(void)> test_func = [this, client_pid]()
{
auto server_status = BatchStatus::make_unique_signal(client_pid);
server_status->send_message(BatchStatus::M_MESSAGE_WRITE);
server_status->receive_message(BatchStatus::M_MESSAGE_READ);
};
int server_pid = fork_other(test_func);
sleep(1); // context switch
auto client_status = BatchStatus::make_unique_signal(server_pid);
client_status->receive_message(BatchStatus::M_MESSAGE_WRITE);
client_status->send_message(BatchStatus::M_MESSAGE_READ);
waitpid(server_pid, nullptr, 0); // reap child process
}
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/util/tensor_format.h"
namespace tensorflow {
typedef FunctionDefHelper FDH;
Status SoftmaxGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
"SoftmaxGrad",
// Arg defs
{"x: T", "grad_softmax: T"},
// Ret val defs
{"grad_x: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
// Based on _SoftmaxGrad in nn_grad.py.
{
{{"softmax"}, "Softmax", {"x"}, {{"T", "$T"}}},
{{"n0"}, "Mul", {"grad_softmax", "softmax"}, {{"T", "$T"}}},
FDH::Const<int32>("indices", {1}),
{{"n1"}, "Sum", {"n0", "indices"}, {{"T", "$T"}}},
FDH::Const<int32>("newshape", {-1, 1}),
{{"n2"}, "Reshape", {"n1", "newshape"}, {{"T", "$T"}}},
{{"n3"}, "Sub", {"grad_softmax", "n2"}, {{"T", "$T"}}},
{{"grad_x"}, "Mul", {"n3", "softmax"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Softmax", SoftmaxGrad);
Status ReluGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"x: T", "dy: T"},
// Ret val defs
{"dx: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
{{"dx"}, "ReluGrad", {"dy", "x"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Relu", ReluGrad);
Status Relu6Grad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"x: T", "dy: T"},
// Ret val defs
{"dx: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
{{"dx"}, "Relu6Grad", {"dy", "x"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Relu6", Relu6Grad);
Status CrossEntropyGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"features: T", "labels: T", "dcost_dloss: T", "donotcare: T"},
// Ret val defs
{"dcost_dfeatures: T", "dcost_dlabels: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
// _, dloss_dfeatures = CrossEntropy(features, labels)
{{"donotcare_loss", "dloss_dfeatures"}, "CrossEntropy",
{"features", "labels"}, {{"T", "$T"}}},
// dcost_dloss is of shape [batch_size].
// dcost_dloss_mat is of shape [batch_size, 1].
FDH::Const("neg1", -1),
{{"dcost_dloss_mat"}, "ExpandDims", {"dcost_dloss", "neg1"},
{{"T", "$T"}}},
// chain rule: dcost/dfeatures = dcost/dloss * dloss/dfeatures
{{"dcost_dfeatures"}, "Mul", {"dcost_dloss_mat", "dloss_dfeatures"},
{{"T", "$T"}}},
{{"dcost_dlabels"}, "ZerosLike", {"labels"}, {{"T", "$T"}}},
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("CrossEntropy", CrossEntropyGrad);
Status Conv2DGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "filter: T", "grad: T"},
// Ret val defs
{"input_grad: T", "filter_grad: T"},
// Attr defs
{"T: {float, double}",
"strides: list(int)",
"use_cudnn_on_gpu: bool = true",
GetPaddingAttrString(),
GetConvnetDataFormatAttrString()},
// Nodes
{
{{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}},
{{"input_grad"}, "Conv2DBackpropInput", {"i_shape", "filter", "grad"},
/*Attrs=*/{{"T", "$T"},
{"strides", "$strides"},
{"padding", "$padding"},
{"data_format", "$data_format"},
{"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}},
{{"f_shape"}, "Shape", {"filter"}, {{"T", "$T"}}},
{{"filter_grad"}, "Conv2DBackpropFilter", {"input", "f_shape", "grad"},
/*Attrs=*/{{"T", "$T"},
{"strides", "$strides"},
{"padding", "$padding"},
{"data_format", "$data_format"},
{"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}},
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Conv2D", Conv2DGrad);
Status MaxPoolGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
// Invoke MaxPool again to recompute the outputs (removed by CSE?).
{{"maxpool"}, "MaxPool", {"input"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}},
{{"output"}, "MaxPoolGrad", {"input", "maxpool", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("MaxPool", MaxPoolGrad);
Status AvgPoolGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
{{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}},
{{"output"}, "AvgPoolGrad", {"i_shape", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("AvgPool", AvgPoolGrad);
Status MaxPoolGradGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
// Invoke MaxPool again to recompute the outputs (removed by CSE?).
{{"maxpool"}, "MaxPool", {"input"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}},
{{"output"}, "MaxPoolGradGrad", {"input", "maxpool", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("MaxPoolGrad", MaxPoolGradGrad);
Status BiasAddGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "bias: T", "grad: T"},
// Ret val defs
{"grad: T", "bias_grad: T"},
// Attr defs
{{"T: {float, double}"},
GetConvnetDataFormatAttrString()},
// Nodes
{
{{"bias_grad"}, "BiasAddGrad", {"grad"},
/*Attrs=*/{{"T", "$T"},
{"data_format", "$data_format"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("BiasAdd", BiasAddGrad);
} // end namespace tensorflow
<commit_msg>Add symbolic gradient for LogSoftmax. The symbolic gradient for Softmax is also simplified.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/util/tensor_format.h"
namespace tensorflow {
typedef FunctionDefHelper FDH;
Status SoftmaxGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
"SoftmaxGrad",
// Arg defs
{"x: T", "grad_softmax: T"},
// Ret val defs
{"grad_x: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
// Based on _SoftmaxGrad in nn_grad.py.
{
{{"softmax"}, "Softmax", {"x"}, {{"T", "$T"}}},
{{"n0"}, "Mul", {"grad_softmax", "softmax"}, {{"T", "$T"}}},
FDH::Const<int32>("indices", {-1}),
{{"n1"}, "Sum", {"n0", "indices"}, {{"keep_dims", true}, {"T", "$T"}}},
{{"n2"}, "Sub", {"grad_softmax", "n1"}, {{"T", "$T"}}},
{{"grad_x"}, "Mul", {"n2", "softmax"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Softmax", SoftmaxGrad);
Status LogSoftmaxGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
"LogSoftmaxGrad",
// Arg defs
{"x: T", "grad_logsoftmax: T"},
// Ret val defs
{"grad_x: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
// Based on _LogSoftmaxGrad in nn_grad.py.
{
{{"softmax"}, "Softmax", {"x"}, {{"T", "$T"}}},
FDH::Const<int32>("indices", {-1}),
{{"n0"}, "Sum", {"grad_logsoftmax", "indices"},
{{"keep_dims", true}, {"T", "$T"}}},
{{"n1"}, "Mul", {"n0", "softmax"}, {{"T", "$T"}}},
{{"grad_x"}, "Sub", {"grad_logsoftmax", "n1"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("LogSoftmax", LogSoftmaxGrad);
Status ReluGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"x: T", "dy: T"},
// Ret val defs
{"dx: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
{{"dx"}, "ReluGrad", {"dy", "x"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Relu", ReluGrad);
Status Relu6Grad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"x: T", "dy: T"},
// Ret val defs
{"dx: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
{{"dx"}, "Relu6Grad", {"dy", "x"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Relu6", Relu6Grad);
Status CrossEntropyGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"features: T", "labels: T", "dcost_dloss: T", "donotcare: T"},
// Ret val defs
{"dcost_dfeatures: T", "dcost_dlabels: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
// _, dloss_dfeatures = CrossEntropy(features, labels)
{{"donotcare_loss", "dloss_dfeatures"}, "CrossEntropy",
{"features", "labels"}, {{"T", "$T"}}},
// dcost_dloss is of shape [batch_size].
// dcost_dloss_mat is of shape [batch_size, 1].
FDH::Const("neg1", -1),
{{"dcost_dloss_mat"}, "ExpandDims", {"dcost_dloss", "neg1"},
{{"T", "$T"}}},
// chain rule: dcost/dfeatures = dcost/dloss * dloss/dfeatures
{{"dcost_dfeatures"}, "Mul", {"dcost_dloss_mat", "dloss_dfeatures"},
{{"T", "$T"}}},
{{"dcost_dlabels"}, "ZerosLike", {"labels"}, {{"T", "$T"}}},
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("CrossEntropy", CrossEntropyGrad);
Status Conv2DGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "filter: T", "grad: T"},
// Ret val defs
{"input_grad: T", "filter_grad: T"},
// Attr defs
{"T: {float, double}",
"strides: list(int)",
"use_cudnn_on_gpu: bool = true",
GetPaddingAttrString(),
GetConvnetDataFormatAttrString()},
// Nodes
{
{{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}},
{{"input_grad"}, "Conv2DBackpropInput", {"i_shape", "filter", "grad"},
/*Attrs=*/{{"T", "$T"},
{"strides", "$strides"},
{"padding", "$padding"},
{"data_format", "$data_format"},
{"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}},
{{"f_shape"}, "Shape", {"filter"}, {{"T", "$T"}}},
{{"filter_grad"}, "Conv2DBackpropFilter", {"input", "f_shape", "grad"},
/*Attrs=*/{{"T", "$T"},
{"strides", "$strides"},
{"padding", "$padding"},
{"data_format", "$data_format"},
{"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}},
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Conv2D", Conv2DGrad);
Status MaxPoolGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
// Invoke MaxPool again to recompute the outputs (removed by CSE?).
{{"maxpool"}, "MaxPool", {"input"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}},
{{"output"}, "MaxPoolGrad", {"input", "maxpool", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("MaxPool", MaxPoolGrad);
Status AvgPoolGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
{{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}},
{{"output"}, "AvgPoolGrad", {"i_shape", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("AvgPool", AvgPoolGrad);
Status MaxPoolGradGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
// Invoke MaxPool again to recompute the outputs (removed by CSE?).
{{"maxpool"}, "MaxPool", {"input"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}},
{{"output"}, "MaxPoolGradGrad", {"input", "maxpool", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("MaxPoolGrad", MaxPoolGradGrad);
Status BiasAddGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "bias: T", "grad: T"},
// Ret val defs
{"grad: T", "bias_grad: T"},
// Attr defs
{{"T: {float, double}"},
GetConvnetDataFormatAttrString()},
// Nodes
{
{{"bias_grad"}, "BiasAddGrad", {"grad"},
/*Attrs=*/{{"T", "$T"},
{"data_format", "$data_format"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("BiasAdd", BiasAddGrad);
} // end namespace tensorflow
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2014, Jan Koester [email protected]
* 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 <organization> 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 <COPYRIGHT HOLDER> 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 <http.h>
#include <httpd.h>
#include <exception.h>
#include <os/os.h>
#include <utils.h>
#include "htmlpp/exception.h"
#include "htmlpp/html.h"
#include "header_png.h"
#include "favicon_ico.h"
#ifndef Windows
#include <sys/utsname.h>
#endif // !Windows
class HtmlTable{
public:
HtmlTable(const char *id=NULL){
_firstRow=nullptr;
_lastRow=nullptr;
_Id=id;
}
~HtmlTable(){
delete _firstRow;
}
class Row {
public:
Row &operator<<(const char *value){
_Data+=value;
return *this;
};
Row &operator<<(int value){
char buf[255];
libhttppp::itoa(value,buf);
return *this << buf;
};
private:
libhtmlpp::HtmlString _Data;
int _Size;
Row(){
_Size=0;
_nextRow=nullptr;
};
~Row(){
delete _nextRow;
};
Row *_nextRow;
friend class HtmlTable;
};
Row &createRow(){
if(_firstRow!=nullptr){
_lastRow->_nextRow=new Row;
_lastRow=_lastRow->_nextRow;
}else{
_firstRow=new Row;
_lastRow=_firstRow;
}
return *_lastRow;
}
const char *getTable(){
_Buffer.clear();
if(_Id!=NULL)
_Buffer << "<table id=\"" << _Id << "\">";
else
_Buffer << "<table>";
for(Row *curow=_firstRow; curow; curow=curow->_nextRow){
_Buffer << "<tr>";
_Buffer += curow->_Data;
_Buffer << "</tr>";
}
_Buffer << "</table>";
return _Buffer.c_str();
}
private:
libhtmlpp::HtmlString _Buffer;
const char *_Id;
Row *_firstRow;
Row *_lastRow;
};
class HtmlContent{
void generateHeader(){
}
};
class IndexPage{
public:
IndexPage(){
_Index << "<!DOCTYPE html><body style=\"color:rgb(239, 240, 241); background:rgb(79, 83, 88);\">"
<< "<div id=\"mainbar\" style=\"border-radius: 38px; background:rgb(35, 38, 41); width:1280px; margin:0px auto;\">"
<< "<div id=\"headerimage\"><img src=\"images/header.png\"/></div>"
<< "<div id=\"sysinfo\" style=\"padding:40px 20px;\"><span>System Info:</span><br/>";
KernelInfo();
CPUInfo();
SysInfo();
// FsInfo();
_Index << "</div></div></body></html>";
}
void KernelInfo(){
#ifndef Windows
struct utsname usysinfo;
uname(&usysinfo);
HtmlTable htmltable;
htmltable.createRow() << "<td>Operating system</td><td>" << usysinfo.sysname <<"</td>";
htmltable.createRow() << "<td>Release Version</td><td>" << usysinfo.release <<"</td>";
htmltable.createRow() << "<td>Hardware</td><td>" << usysinfo.machine <<"</td>";
_Index << "<h2>KernelInfo:</h2>" << htmltable.getTable();
#endif
}
void CPUInfo(){
libhttppp::CpuInfo cpuinfo;
_Index << "<h2>CPUInfo:</h2>";
HtmlTable cputable;
cputable.createRow() << "<td>Cores</td><td>" << cpuinfo.getCores()<<"</td>";
cputable.createRow() << "<td>Running on Thread</td><td>"<< cpuinfo.getActualThread()<<"</td>";
cputable.createRow() << "<td>Threads</td><td>" << cpuinfo.getThreads()<<"</td>";
_Index << cputable.getTable();
}
void SysInfo(){
libhttppp::SysInfo sysinfo;
_Index << "<h2>SysInfo:</h2>";
HtmlTable cputable;
cputable.createRow() << "<td>Total Ram</td><td>" << sysinfo.getTotalRam()<<"</td>";
cputable.createRow() << "<td>Free Ram</td><td>" << sysinfo.getFreeRam()<<"</td>";
cputable.createRow() << "<td>Buffered Ram</td><td>" <<sysinfo.getBufferRam()<<"</td>";
_Index << cputable.getTable();
}
void FsInfo(){
libhttppp::FsInfo fsinfo;
_Index << "<h2>FsInfo:</h2>";
HtmlTable fstable;
for(libhttppp::MountPoint *curm=fsinfo.getFirstDevice(); curm; curm=curm->nextMountPoint()){
fstable.createRow() << "<td>Device</td><td>" << curm->getDevice() <<"</td>";
}
_Index << fstable.getTable();
}
const char *getIndexPage(){
return _Index.c_str();
}
size_t getIndexPageSize(){
return _Index.size();
}
private:
libhtmlpp::HtmlString _Index;
};
class Controller : public libhttppp::Event {
public:
Controller(libhttppp::ServerSocket* serversocket) : Event(serversocket){
};
void IndexController(libhttppp::Connection *curcon){
try{
libhttppp::HttpRequest curreq;
curreq.parse(curcon);
const char *cururl=curreq.getRequestURL();
libhttppp::HttpResponse curres;
curres.setState(HTTP200);
curres.setVersion(HTTPVERSION(1.1));
if(strncmp(cururl,"/", libhttppp::getlen(cururl))==0){
curres.setContentType("text/html");
IndexPage idx;
curres.send(curcon,idx.getIndexPage(),idx.getIndexPageSize());
}else if(strncmp(cururl,"/images/header.png", libhttppp::getlen(cururl))==0){
curres.setContentType("image/png");
curres.setContentLength(header_png_size);
curres.send(curcon,(const char*)header_png,header_png_size);
}else if(strncmp(cururl,"/favicon.ico ",libhttppp::getlen(cururl))==0){
curres.setContentType("image/ico");
curres.setContentLength(favicon_ico_size);
curres.send(curcon,(const char*)favicon_ico,favicon_ico_size);
}else{
curres.setState(HTTP404);
curres.send(curcon,NULL,0);
}
}catch(libhttppp::HTTPException &e){
throw e;
}
}
void RequestEvent(libhttppp::Connection *curcon){
try{
IndexController(curcon);
}catch(libhttppp::HTTPException &e){
libhttppp::Console con;
con << e.what() << con.endl;
throw e;
}
}
private:
};
class HttpConD : public libhttppp::HttpD {
public:
HttpConD(int argc, char** argv) : HttpD(argc,argv){
Controller controller(getServerSocket());
controller.runEventloop();
};
};
int main(int argc, char** argv){
try{
HttpConD(argc,argv);
return 0;
}catch(libhttppp::HTTPException &e){
libhttppp::Console con;
con << e.what() << con.endl;
if(e.getErrorType()==libhttppp::HTTPException::Note
|| libhttppp::HTTPException::Warning)
return 0;
else
return -1;
};
}
<commit_msg>use http v2 in httpsysinfo<commit_after>/*******************************************************************************
* Copyright (c) 2014, Jan Koester [email protected]
* 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 <organization> 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 <COPYRIGHT HOLDER> 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 <http.h>
#include <httpd.h>
#include <exception.h>
#include <os/os.h>
#include <utils.h>
#include "htmlpp/exception.h"
#include "htmlpp/html.h"
#include "header_png.h"
#include "favicon_ico.h"
#ifndef Windows
#include <sys/utsname.h>
#endif // !Windows
class HtmlTable{
public:
HtmlTable(const char *id=NULL){
_firstRow=nullptr;
_lastRow=nullptr;
_Id=id;
}
~HtmlTable(){
delete _firstRow;
}
class Row {
public:
Row &operator<<(const char *value){
_Data+=value;
return *this;
};
Row &operator<<(int value){
char buf[255];
libhttppp::itoa(value,buf);
return *this << buf;
};
private:
libhtmlpp::HtmlString _Data;
int _Size;
Row(){
_Size=0;
_nextRow=nullptr;
};
~Row(){
delete _nextRow;
};
Row *_nextRow;
friend class HtmlTable;
};
Row &createRow(){
if(_firstRow!=nullptr){
_lastRow->_nextRow=new Row;
_lastRow=_lastRow->_nextRow;
}else{
_firstRow=new Row;
_lastRow=_firstRow;
}
return *_lastRow;
}
const char *getTable(){
_Buffer.clear();
if(_Id!=NULL)
_Buffer << "<table id=\"" << _Id << "\">";
else
_Buffer << "<table>";
for(Row *curow=_firstRow; curow; curow=curow->_nextRow){
_Buffer << "<tr>";
_Buffer += curow->_Data;
_Buffer << "</tr>";
}
_Buffer << "</table>";
return _Buffer.c_str();
}
private:
libhtmlpp::HtmlString _Buffer;
const char *_Id;
Row *_firstRow;
Row *_lastRow;
};
class HtmlContent{
void generateHeader(){
}
};
class IndexPage{
public:
IndexPage(){
_Index << "<!DOCTYPE html><body style=\"color:rgb(239, 240, 241); background:rgb(79, 83, 88);\">"
<< "<div id=\"mainbar\" style=\"border-radius: 38px; background:rgb(35, 38, 41); width:1280px; margin:0px auto;\">"
<< "<div id=\"headerimage\"><img src=\"images/header.png\"/></div>"
<< "<div id=\"sysinfo\" style=\"padding:40px 20px;\"><span>System Info:</span><br/>";
KernelInfo();
CPUInfo();
SysInfo();
// FsInfo();
_Index << "</div></div></body></html>";
}
void KernelInfo(){
#ifndef Windows
struct utsname usysinfo;
uname(&usysinfo);
HtmlTable htmltable;
htmltable.createRow() << "<td>Operating system</td><td>" << usysinfo.sysname <<"</td>";
htmltable.createRow() << "<td>Release Version</td><td>" << usysinfo.release <<"</td>";
htmltable.createRow() << "<td>Hardware</td><td>" << usysinfo.machine <<"</td>";
_Index << "<h2>KernelInfo:</h2>" << htmltable.getTable();
#endif
}
void CPUInfo(){
libhttppp::CpuInfo cpuinfo;
_Index << "<h2>CPUInfo:</h2>";
HtmlTable cputable;
cputable.createRow() << "<td>Cores</td><td>" << cpuinfo.getCores()<<"</td>";
cputable.createRow() << "<td>Running on Thread</td><td>"<< cpuinfo.getActualThread()<<"</td>";
cputable.createRow() << "<td>Threads</td><td>" << cpuinfo.getThreads()<<"</td>";
_Index << cputable.getTable();
}
void SysInfo(){
libhttppp::SysInfo sysinfo;
_Index << "<h2>SysInfo:</h2>";
HtmlTable cputable;
cputable.createRow() << "<td>Total Ram</td><td>" << sysinfo.getTotalRam()<<"</td>";
cputable.createRow() << "<td>Free Ram</td><td>" << sysinfo.getFreeRam()<<"</td>";
cputable.createRow() << "<td>Buffered Ram</td><td>" <<sysinfo.getBufferRam()<<"</td>";
_Index << cputable.getTable();
}
void FsInfo(){
libhttppp::FsInfo fsinfo;
_Index << "<h2>FsInfo:</h2>";
HtmlTable fstable;
for(libhttppp::MountPoint *curm=fsinfo.getFirstDevice(); curm; curm=curm->nextMountPoint()){
fstable.createRow() << "<td>Device</td><td>" << curm->getDevice() <<"</td>";
}
_Index << fstable.getTable();
}
const char *getIndexPage(){
return _Index.c_str();
}
size_t getIndexPageSize(){
return _Index.size();
}
private:
libhtmlpp::HtmlString _Index;
};
class Controller : public libhttppp::Event {
public:
Controller(libhttppp::ServerSocket* serversocket) : Event(serversocket){
};
void IndexController(libhttppp::Connection *curcon){
try{
libhttppp::HttpRequest curreq;
curreq.parse(curcon);
const char *cururl=curreq.getRequestURL();
libhttppp::HttpResponse curres;
curres.setState(HTTP200);
curres.setVersion(HTTPVERSION(2.0));
if(strncmp(cururl,"/", libhttppp::getlen(cururl))==0){
curres.setContentType("text/html");
IndexPage idx;
curres.send(curcon,idx.getIndexPage(),idx.getIndexPageSize());
}else if(strncmp(cururl,"/images/header.png", libhttppp::getlen(cururl))==0){
curres.setContentType("image/png");
curres.setContentLength(header_png_size);
curres.send(curcon,(const char*)header_png,header_png_size);
}else if(strncmp(cururl,"/favicon.ico ",libhttppp::getlen(cururl))==0){
curres.setContentType("image/ico");
curres.setContentLength(favicon_ico_size);
curres.send(curcon,(const char*)favicon_ico,favicon_ico_size);
}else{
curres.setState(HTTP404);
curres.send(curcon,NULL,0);
}
}catch(libhttppp::HTTPException &e){
throw e;
}
}
void RequestEvent(libhttppp::Connection *curcon){
try{
IndexController(curcon);
}catch(libhttppp::HTTPException &e){
libhttppp::Console con;
con << e.what() << con.endl;
throw e;
}
}
private:
};
class HttpConD : public libhttppp::HttpD {
public:
HttpConD(int argc, char** argv) : HttpD(argc,argv){
Controller controller(getServerSocket());
controller.runEventloop();
};
};
int main(int argc, char** argv){
try{
HttpConD(argc,argv);
return 0;
}catch(libhttppp::HTTPException &e){
libhttppp::Console con;
con << e.what() << con.endl;
if(e.getErrorType()==libhttppp::HTTPException::Note
|| libhttppp::HTTPException::Warning)
return 0;
else
return -1;
};
}
<|endoftext|> |
<commit_before>struct bonk { };
void test(bonk X) {
X = X;
}
// RUN: c-index-test -test-annotate-tokens=%s:1:1:5:5 %s
// CHECK: Keyword: "struct" [1:1 - 1:7] StructDecl=bonk:1:8 (Definition)
// CHECK: Identifier: "bonk" [1:8 - 1:12] StructDecl=bonk:1:8 (Definition)
// CHECK: Punctuation: "{" [1:13 - 1:14] StructDecl=bonk:1:8 (Definition)
// CHECK: Punctuation: "}" [1:15 - 1:16] StructDecl=bonk:1:8 (Definition)
// CHECK: Punctuation: ";" [1:16 - 1:17]
// CHECK: Keyword: "void" [2:1 - 2:5] FunctionDecl=test:2:6 (Definition)
// CHECK: Identifier: "test" [2:6 - 2:10] FunctionDecl=test:2:6 (Definition)
// CHECK: Punctuation: "(" [2:10 - 2:11] FunctionDecl=test:2:6 (Definition)
// CHECK: Identifier: "bonk" [2:11 - 2:15] TypeRef=struct bonk:1:8
// CHECK: Identifier: "X" [2:16 - 2:17] ParmDecl=X:2:16 (Definition)
// CHECK: Punctuation: ")" [2:17 - 2:18] FunctionDecl=test:2:6 (Definition)
// CHECK: Punctuation: "{" [2:19 - 2:20] UnexposedStmt=
// CHECK: Identifier: "X" [3:5 - 3:6] DeclRefExpr=X:2:16
// CHECK: Punctuation: "=" [3:7 - 3:8] DeclRefExpr=operator=:1:8
// CHECK: Identifier: "X" [3:9 - 3:10] DeclRefExpr=X:2:16
// CHECK: Punctuation: ";" [3:10 - 3:11] UnexposedStmt=
// CHECK: Punctuation: "}" [4:1 - 4:2] UnexposedStmt=
<commit_msg>Fix test that didn't really test anything.<commit_after>struct bonk { };
void test(bonk X) {
X = X;
}
// RUN: c-index-test -test-annotate-tokens=%s:1:1:5:5 %s | FileCheck %s
// CHECK: Keyword: "struct" [1:1 - 1:7] StructDecl=bonk:1:8 (Definition)
// CHECK: Identifier: "bonk" [1:8 - 1:12] StructDecl=bonk:1:8 (Definition)
// CHECK: Punctuation: "{" [1:13 - 1:14] StructDecl=bonk:1:8 (Definition)
// CHECK: Punctuation: "}" [1:15 - 1:16] StructDecl=bonk:1:8 (Definition)
// CHECK: Punctuation: ";" [1:16 - 1:17]
// CHECK: Keyword: "void" [2:1 - 2:5] FunctionDecl=test:2:6 (Definition)
// CHECK: Identifier: "test" [2:6 - 2:10] FunctionDecl=test:2:6 (Definition)
// CHECK: Punctuation: "(" [2:10 - 2:11] FunctionDecl=test:2:6 (Definition)
// CHECK: Identifier: "bonk" [2:11 - 2:15] TypeRef=struct bonk:1:8
// CHECK: Identifier: "X" [2:16 - 2:17] ParmDecl=X:2:16 (Definition)
// CHECK: Punctuation: ")" [2:17 - 2:18] FunctionDecl=test:2:6 (Definition)
// CHECK: Punctuation: "{" [2:19 - 2:20] UnexposedStmt=
// CHECK: Identifier: "X" [3:5 - 3:6] DeclRefExpr=X:2:16
// CHECK: Punctuation: "=" [3:7 - 3:8] CallExpr=operator=:1:8
// CHECK: Identifier: "X" [3:9 - 3:10] DeclRefExpr=X:2:16
// CHECK: Punctuation: ";" [3:10 - 3:11] UnexposedStmt=
// CHECK: Punctuation: "}" [4:1 - 4:2] UnexposedStmt=
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (C) 2004 Reinhold Kainhofer <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "incidencechanger.h"
#include "koprefs.h"
#include "kogroupware.h"
#include "mailscheduler.h"
#include <kcal/freebusy.h>
#include <kcal/dndfactory.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <klocale.h>
bool IncidenceChanger::beginChange( Incidence *incidence )
{
if ( !incidence ) {
return false;
}
kDebug() << "for incidence \"" << incidence->summary() << "\"";
return mCalendar->beginChange( incidence );
}
bool IncidenceChanger::sendGroupwareMessage( Incidence *incidence,
KCal::iTIPMethod method, bool deleting )
{
if ( KOPrefs::instance()->thatIsMe( incidence->organizer().email() ) &&
incidence->attendeeCount() > 0 &&
!KOPrefs::instance()->mUseGroupwareCommunication ) {
emit schedule( method, incidence );
return true;
} else if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
// FIXME: Find a widget to use as parent, instead of 0
return KOGroupware::instance()->sendICalMessage( 0, method, incidence, deleting );
}
return true;
}
void IncidenceChanger::cancelAttendees( Incidence *incidence )
{
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( KMessageBox::questionYesNo(
0,
i18n( "Some attendees were removed from the incidence. "
"Shall cancel messages be sent to these attendees?" ),
i18n( "Attendees Removed" ), KGuiItem( i18n( "Send Messages" ) ),
KGuiItem( i18n( "Do Not Send" ) ) ) == KMessageBox::Yes ) {
// don't use KOGroupware::sendICalMessage here, because that asks just
// a very general question "Other people are involved, send message to
// them?", which isn't helpful at all in this situation. Afterwards, it
// would only call the MailScheduler::performTransaction, so do this
// manually.
// FIXME: Groupware schedulling should be factored out to it's own class
// anyway
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( incidence, iTIPCancel );
}
}
}
bool IncidenceChanger::endChange( Incidence *incidence )
{
// FIXME: if that's a groupware incidence, and I'm not the organizer,
// send out a mail to the organizer with a counterproposal instead
// of actually changing the incidence. Then no locking is needed.
// FIXME: if that's a groupware incidence, and the incidence was
// never locked, we can't unlock it with endChange().
if ( !incidence ) {
return false;
}
kDebug() << "\"" << incidence->summary() << "\"";
return mCalendar->endChange( incidence );
}
bool IncidenceChanger::deleteIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel, true );
if( doDelete ) {
// @TODO: let Calendar::deleteIncidence do the locking...
Incidence* tmp = incidence->clone();
emit incidenceToBeDeleted( incidence );
doDelete = mCalendar->deleteIncidence( tmp );
if ( !KOPrefs::instance()->thatIsMe( tmp->organizer().email() ) ) {
const QStringList myEmails = KOPrefs::instance()->allEmails();
bool notifyOrganizer = false;
for ( QStringList::ConstIterator it = myEmails.begin(); it != myEmails.end(); ++it ) {
QString email = *it;
Attendee *me = tmp->attendeeByMail(email);
if ( me ) {
if ( me->status() == KCal::Attendee::Accepted || me->status() == KCal::Attendee::Delegated )
notifyOrganizer = true;
Attendee *newMe = new Attendee( *me );
newMe->setStatus( KCal::Attendee::Declined );
tmp->clearAttendees();
tmp->addAttendee( newMe );
break;
}
}
if ( notifyOrganizer ) {
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( tmp, KCal::iTIPReply );
}
}
emit incidenceDeleted( incidence );
}
return doDelete;
}
bool IncidenceChanger::cutIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel );
if( doDelete ) {
// @TODO: the factory needs to do the locking!
DndFactory factory( mCalendar );
emit incidenceToBeDeleted( incidence );
factory.cutIncidence( incidence );
emit incidenceDeleted( incidence );
}
return doDelete;
}
class IncidenceChanger::ComparisonVisitor : public IncidenceBase::Visitor
{
public:
ComparisonVisitor() {}
bool act( IncidenceBase *incidence, IncidenceBase *inc2 )
{
mIncidence2 = inc2;
if ( incidence ) {
return incidence->accept( *this );
} else {
return inc2 == 0;
}
}
protected:
bool visit( Event *event )
{
Event *ev2 = dynamic_cast<Event*>(mIncidence2);
if ( event && ev2 ) {
return *event == *ev2;
} else {
// either both 0, or return false;
return ev2 == event;
}
}
bool visit( Todo *todo )
{
Todo *to2 = dynamic_cast<Todo*>( mIncidence2 );
if ( todo && to2 ) {
return *todo == *to2;
} else {
// either both 0, or return false;
return todo == to2;
}
}
bool visit( Journal *journal )
{
Journal *j2 = dynamic_cast<Journal*>( mIncidence2 );
if ( journal && j2 ) {
return *journal == *j2;
} else {
// either both 0, or return false;
return journal == j2;
}
}
bool visit( FreeBusy *fb )
{
FreeBusy *fb2 = dynamic_cast<FreeBusy*>( mIncidence2 );
if ( fb && fb2 ) {
return *fb == *fb2;
} else {
// either both 0, or return false;
return fb2 == fb;
}
}
protected:
IncidenceBase *mIncidence2;
};
class IncidenceChanger::AssignmentVisitor : public IncidenceBase::Visitor
{
public:
AssignmentVisitor() {}
bool act( IncidenceBase *incidence, IncidenceBase *inc2 )
{
mIncidence2 = inc2;
if ( incidence ) {
return incidence->accept( *this );
} else {
return false;
}
}
protected:
bool visit( Event *event )
{
Event *ev2 = dynamic_cast<Event*>( mIncidence2 );
if ( event && ev2 ) {
*event = *ev2;
return true;
} else {
return false;
}
}
bool visit( Todo *todo )
{
Todo *to2 = dynamic_cast<Todo*>( mIncidence2 );
if ( todo && to2 ) {
*todo = *to2;
return true;
} else {
return false;
}
}
bool visit( Journal *journal )
{
Journal *j2 = dynamic_cast<Journal*>(mIncidence2);
if ( journal && j2 ) {
*journal = *j2;
return true;
} else {
return false;
}
}
bool visit( FreeBusy *fb )
{
FreeBusy *fb2 = dynamic_cast<FreeBusy*>( mIncidence2 );
if ( fb && fb2 ) {
*fb = *fb2;
return true;
} else {
return false;
}
}
protected:
IncidenceBase *mIncidence2;
};
bool IncidenceChanger::incidencesEqual( Incidence *inc1, Incidence *inc2 )
{
ComparisonVisitor v;
return ( v.act( inc1, inc2 ) );
}
bool IncidenceChanger::assignIncidence( Incidence *inc1, Incidence *inc2 )
{
AssignmentVisitor v;
return v.act( inc1, inc2 );
}
bool IncidenceChanger::myAttendeeStatusChanged( Incidence *oldInc, Incidence *newInc )
{
Attendee *oldMe = oldInc->attendeeByMails( KOPrefs::instance()->allEmails() );
Attendee *newMe = newInc->attendeeByMails( KOPrefs::instance()->allEmails() );
if ( oldMe && newMe && ( oldMe->status() != newMe->status() ) ) {
return true;
}
return false;
}
bool IncidenceChanger::changeIncidence( Incidence *oldinc, Incidence *newinc,
int action )
{
kDebug() << "for incidence \"" << newinc->summary()
<< "\" ( old one was \"" << oldinc->summary() << "\")";
if ( incidencesEqual( newinc, oldinc ) ) {
// Don't do anything
kDebug() << "Incidence not changed";
} else {
kDebug() << "Changing incidence";
bool statusChanged = myAttendeeStatusChanged( oldinc, newinc );
int revision = newinc->revision();
newinc->setRevision( revision + 1 );
// FIXME: Use a generic method for this! Ideally, have an interface class
// for group cheduling. Each implementation could then just do what
// it wants with the event. If no groupware is used,use the null
// pattern...
bool revert = KOPrefs::instance()->mUseGroupwareCommunication;
if ( revert &&
KOGroupware::instance()->sendICalMessage( 0,
KCal::iTIPRequest,
newinc, false, statusChanged ) ) {
// Accept the event changes
if ( action < 0 ) {
emit incidenceChanged( oldinc, newinc );
} else {
emit incidenceChanged( oldinc, newinc, action );
}
revert = false;
}
if ( revert ) {
assignIncidence( newinc, oldinc );
return false;
}
}
return true;
}
bool IncidenceChanger::addIncidence( Incidence *incidence, QWidget *parent )
{
kDebug() << "\"" << incidence->summary() << "\"";
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( !KOGroupware::instance()->sendICalMessage( parent,
KCal::iTIPRequest,
incidence ) ) {
kError() << "sendIcalMessage failed.";
}
}
// FIXME: This is a nasty hack, since we need to set a parent for the
// resource selection dialog. However, we don't have any UI methods
// in the calendar, only in the CalendarResources::DestinationPolicy
// So we need to type-cast it and extract it from the CalendarResources
CalendarResources *stdcal = dynamic_cast<CalendarResources*>(mCalendar);
QWidget *tmpparent = 0;
if ( stdcal ) {
tmpparent = stdcal->dialogParentWidget();
stdcal->setDialogParentWidget( parent );
}
bool success = mCalendar->addIncidence( incidence );
if ( stdcal ) {
// Reset the parent widget, otherwise we'll end up with pointers to deleted
// widgets sooner or later
stdcal->setDialogParentWidget( tmpparent );
}
if ( !success ) {
kDebug() << "failed";
KMessageBox::sorry( parent,
i18n( "Unable to save %1 \"%2\".",
i18n( incidence->type() ),
incidence->summary() ) );
return false;
}
emit incidenceAdded( incidence );
return true;
}
#include "incidencechanger.moc"
<commit_msg>Delete the real incidence item, not its clone.<commit_after>/*
This file is part of KOrganizer.
Copyright (C) 2004 Reinhold Kainhofer <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "incidencechanger.h"
#include "koprefs.h"
#include "kogroupware.h"
#include "mailscheduler.h"
#include <kcal/freebusy.h>
#include <kcal/dndfactory.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <klocale.h>
bool IncidenceChanger::beginChange( Incidence *incidence )
{
if ( !incidence ) {
return false;
}
kDebug() << "for incidence \"" << incidence->summary() << "\"";
return mCalendar->beginChange( incidence );
}
bool IncidenceChanger::sendGroupwareMessage( Incidence *incidence,
KCal::iTIPMethod method, bool deleting )
{
if ( KOPrefs::instance()->thatIsMe( incidence->organizer().email() ) &&
incidence->attendeeCount() > 0 &&
!KOPrefs::instance()->mUseGroupwareCommunication ) {
emit schedule( method, incidence );
return true;
} else if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
// FIXME: Find a widget to use as parent, instead of 0
return KOGroupware::instance()->sendICalMessage( 0, method, incidence, deleting );
}
return true;
}
void IncidenceChanger::cancelAttendees( Incidence *incidence )
{
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( KMessageBox::questionYesNo(
0,
i18n( "Some attendees were removed from the incidence. "
"Shall cancel messages be sent to these attendees?" ),
i18n( "Attendees Removed" ), KGuiItem( i18n( "Send Messages" ) ),
KGuiItem( i18n( "Do Not Send" ) ) ) == KMessageBox::Yes ) {
// don't use KOGroupware::sendICalMessage here, because that asks just
// a very general question "Other people are involved, send message to
// them?", which isn't helpful at all in this situation. Afterwards, it
// would only call the MailScheduler::performTransaction, so do this
// manually.
// FIXME: Groupware schedulling should be factored out to it's own class
// anyway
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( incidence, iTIPCancel );
}
}
}
bool IncidenceChanger::endChange( Incidence *incidence )
{
// FIXME: if that's a groupware incidence, and I'm not the organizer,
// send out a mail to the organizer with a counterproposal instead
// of actually changing the incidence. Then no locking is needed.
// FIXME: if that's a groupware incidence, and the incidence was
// never locked, we can't unlock it with endChange().
if ( !incidence ) {
return false;
}
kDebug() << "\"" << incidence->summary() << "\"";
return mCalendar->endChange( incidence );
}
bool IncidenceChanger::deleteIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel, true );
if( doDelete ) {
// @TODO: let Calendar::deleteIncidence do the locking...
Incidence* tmp = incidence->clone();
emit incidenceToBeDeleted( incidence );
doDelete = mCalendar->deleteIncidence( incidence );
if ( !KOPrefs::instance()->thatIsMe( tmp->organizer().email() ) ) {
const QStringList myEmails = KOPrefs::instance()->allEmails();
bool notifyOrganizer = false;
for ( QStringList::ConstIterator it = myEmails.begin(); it != myEmails.end(); ++it ) {
QString email = *it;
Attendee *me = tmp->attendeeByMail(email);
if ( me ) {
if ( me->status() == KCal::Attendee::Accepted || me->status() == KCal::Attendee::Delegated )
notifyOrganizer = true;
Attendee *newMe = new Attendee( *me );
newMe->setStatus( KCal::Attendee::Declined );
tmp->clearAttendees();
tmp->addAttendee( newMe );
break;
}
}
if ( notifyOrganizer ) {
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( tmp, KCal::iTIPReply );
}
}
emit incidenceDeleted( incidence );
}
return doDelete;
}
bool IncidenceChanger::cutIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel );
if( doDelete ) {
// @TODO: the factory needs to do the locking!
DndFactory factory( mCalendar );
emit incidenceToBeDeleted( incidence );
factory.cutIncidence( incidence );
emit incidenceDeleted( incidence );
}
return doDelete;
}
class IncidenceChanger::ComparisonVisitor : public IncidenceBase::Visitor
{
public:
ComparisonVisitor() {}
bool act( IncidenceBase *incidence, IncidenceBase *inc2 )
{
mIncidence2 = inc2;
if ( incidence ) {
return incidence->accept( *this );
} else {
return inc2 == 0;
}
}
protected:
bool visit( Event *event )
{
Event *ev2 = dynamic_cast<Event*>(mIncidence2);
if ( event && ev2 ) {
return *event == *ev2;
} else {
// either both 0, or return false;
return ev2 == event;
}
}
bool visit( Todo *todo )
{
Todo *to2 = dynamic_cast<Todo*>( mIncidence2 );
if ( todo && to2 ) {
return *todo == *to2;
} else {
// either both 0, or return false;
return todo == to2;
}
}
bool visit( Journal *journal )
{
Journal *j2 = dynamic_cast<Journal*>( mIncidence2 );
if ( journal && j2 ) {
return *journal == *j2;
} else {
// either both 0, or return false;
return journal == j2;
}
}
bool visit( FreeBusy *fb )
{
FreeBusy *fb2 = dynamic_cast<FreeBusy*>( mIncidence2 );
if ( fb && fb2 ) {
return *fb == *fb2;
} else {
// either both 0, or return false;
return fb2 == fb;
}
}
protected:
IncidenceBase *mIncidence2;
};
class IncidenceChanger::AssignmentVisitor : public IncidenceBase::Visitor
{
public:
AssignmentVisitor() {}
bool act( IncidenceBase *incidence, IncidenceBase *inc2 )
{
mIncidence2 = inc2;
if ( incidence ) {
return incidence->accept( *this );
} else {
return false;
}
}
protected:
bool visit( Event *event )
{
Event *ev2 = dynamic_cast<Event*>( mIncidence2 );
if ( event && ev2 ) {
*event = *ev2;
return true;
} else {
return false;
}
}
bool visit( Todo *todo )
{
Todo *to2 = dynamic_cast<Todo*>( mIncidence2 );
if ( todo && to2 ) {
*todo = *to2;
return true;
} else {
return false;
}
}
bool visit( Journal *journal )
{
Journal *j2 = dynamic_cast<Journal*>(mIncidence2);
if ( journal && j2 ) {
*journal = *j2;
return true;
} else {
return false;
}
}
bool visit( FreeBusy *fb )
{
FreeBusy *fb2 = dynamic_cast<FreeBusy*>( mIncidence2 );
if ( fb && fb2 ) {
*fb = *fb2;
return true;
} else {
return false;
}
}
protected:
IncidenceBase *mIncidence2;
};
bool IncidenceChanger::incidencesEqual( Incidence *inc1, Incidence *inc2 )
{
ComparisonVisitor v;
return ( v.act( inc1, inc2 ) );
}
bool IncidenceChanger::assignIncidence( Incidence *inc1, Incidence *inc2 )
{
AssignmentVisitor v;
return v.act( inc1, inc2 );
}
bool IncidenceChanger::myAttendeeStatusChanged( Incidence *oldInc, Incidence *newInc )
{
Attendee *oldMe = oldInc->attendeeByMails( KOPrefs::instance()->allEmails() );
Attendee *newMe = newInc->attendeeByMails( KOPrefs::instance()->allEmails() );
if ( oldMe && newMe && ( oldMe->status() != newMe->status() ) ) {
return true;
}
return false;
}
bool IncidenceChanger::changeIncidence( Incidence *oldinc, Incidence *newinc,
int action )
{
kDebug() << "for incidence \"" << newinc->summary()
<< "\" ( old one was \"" << oldinc->summary() << "\")";
if ( incidencesEqual( newinc, oldinc ) ) {
// Don't do anything
kDebug() << "Incidence not changed";
} else {
kDebug() << "Changing incidence";
bool statusChanged = myAttendeeStatusChanged( oldinc, newinc );
int revision = newinc->revision();
newinc->setRevision( revision + 1 );
// FIXME: Use a generic method for this! Ideally, have an interface class
// for group cheduling. Each implementation could then just do what
// it wants with the event. If no groupware is used,use the null
// pattern...
bool revert = KOPrefs::instance()->mUseGroupwareCommunication;
if ( revert &&
KOGroupware::instance()->sendICalMessage( 0,
KCal::iTIPRequest,
newinc, false, statusChanged ) ) {
// Accept the event changes
if ( action < 0 ) {
emit incidenceChanged( oldinc, newinc );
} else {
emit incidenceChanged( oldinc, newinc, action );
}
revert = false;
}
if ( revert ) {
assignIncidence( newinc, oldinc );
return false;
}
}
return true;
}
bool IncidenceChanger::addIncidence( Incidence *incidence, QWidget *parent )
{
kDebug() << "\"" << incidence->summary() << "\"";
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( !KOGroupware::instance()->sendICalMessage( parent,
KCal::iTIPRequest,
incidence ) ) {
kError() << "sendIcalMessage failed.";
}
}
// FIXME: This is a nasty hack, since we need to set a parent for the
// resource selection dialog. However, we don't have any UI methods
// in the calendar, only in the CalendarResources::DestinationPolicy
// So we need to type-cast it and extract it from the CalendarResources
CalendarResources *stdcal = dynamic_cast<CalendarResources*>(mCalendar);
QWidget *tmpparent = 0;
if ( stdcal ) {
tmpparent = stdcal->dialogParentWidget();
stdcal->setDialogParentWidget( parent );
}
bool success = mCalendar->addIncidence( incidence );
if ( stdcal ) {
// Reset the parent widget, otherwise we'll end up with pointers to deleted
// widgets sooner or later
stdcal->setDialogParentWidget( tmpparent );
}
if ( !success ) {
kDebug() << "failed";
KMessageBox::sorry( parent,
i18n( "Unable to save %1 \"%2\".",
i18n( incidence->type() ),
incidence->summary() ) );
return false;
}
emit incidenceAdded( incidence );
return true;
}
#include "incidencechanger.moc"
<|endoftext|> |
<commit_before>/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include <boost/algorithm/string.hpp>
#include <boost/bimap.hpp>
#include <boost/container/flat_map.hpp>
#include <cstdio>
#include <cstring>
#include <exception>
#include <filesystem>
#include <ipmid/api.hpp>
#include <ipmid/types.hpp>
#include <map>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus/match.hpp>
#include <string>
#include <vector>
#pragma once
static constexpr bool debug = false;
struct CmpStrVersion
{
bool operator()(std::string a, std::string b) const
{
return strverscmp(a.c_str(), b.c_str()) < 0;
}
};
using SensorSubTree = boost::container::flat_map<
std::string,
boost::container::flat_map<std::string, std::vector<std::string>>,
CmpStrVersion>;
using SensorNumMap = boost::bimap<int, std::string>;
static constexpr uint16_t maxSensorsPerLUN = 255;
static constexpr uint16_t maxIPMISensors = (maxSensorsPerLUN * 3);
static constexpr uint16_t lun1Sensor0 = 0x100;
static constexpr uint16_t lun3Sensor0 = 0x300;
static constexpr uint16_t invalidSensorNumber = 0xFFFF;
static constexpr uint8_t reservedSensorNumber = 0xFF;
namespace details
{
// Enable/disable the logging of stats instrumentation
static constexpr bool enableInstrumentation = false;
class IPMIStatsEntry
{
private:
int numReadings = 0;
int numMissings = 0;
int numStreakRead = 0;
int numStreakMiss = 0;
double minValue = 0.0;
double maxValue = 0.0;
std::string sensorName;
public:
const std::string& getName(void) const
{
return sensorName;
}
void updateName(std::string_view name)
{
sensorName = name;
}
// Returns true if this is the first successful reading
// This is so the caller can log the coefficients used
bool updateReading(double reading, int raw)
{
if constexpr (!enableInstrumentation)
{
return false;
}
bool first = ((numReadings == 0) && (numMissings == 0));
// Sensors can use "nan" to indicate unavailable reading
if (!(std::isfinite(reading)))
{
// Only show this if beginning a new streak
if (numStreakMiss == 0)
{
std::cerr << "IPMI sensor " << sensorName
<< ": Missing reading, byte=" << raw
<< ", Reading counts good=" << numReadings
<< " miss=" << numMissings
<< ", Prior good streak=" << numStreakRead << "\n";
}
numStreakRead = 0;
++numMissings;
++numStreakMiss;
return first;
}
// Only show this if beginning a new streak and not the first time
if ((numStreakRead == 0) && (numReadings != 0))
{
std::cerr << "IPMI sensor " << sensorName
<< ": Recovered reading, value=" << reading
<< " byte=" << raw
<< ", Reading counts good=" << numReadings
<< " miss=" << numMissings
<< ", Prior miss streak=" << numStreakMiss << "\n";
}
// Initialize min/max if the first successful reading
if (numReadings == 0)
{
std::cerr << "IPMI sensor " << sensorName
<< ": First reading, value=" << reading << " byte=" << raw
<< "\n";
minValue = reading;
maxValue = reading;
}
numStreakMiss = 0;
++numReadings;
++numStreakRead;
// Only provide subsequent output if new min/max established
if (reading < minValue)
{
std::cerr << "IPMI sensor " << sensorName
<< ": Lowest reading, value=" << reading
<< " byte=" << raw << "\n";
minValue = reading;
}
if (reading > maxValue)
{
std::cerr << "IPMI sensor " << sensorName
<< ": Highest reading, value=" << reading
<< " byte=" << raw << "\n";
maxValue = reading;
}
return first;
}
};
class IPMIStatsTable
{
private:
std::vector<IPMIStatsEntry> entries;
private:
void padEntries(size_t index)
{
char hexbuf[16];
// Pad vector until entries[index] becomes a valid index
while (entries.size() <= index)
{
// As name not known yet, use human-readable hex as name
IPMIStatsEntry newEntry;
sprintf(hexbuf, "0x%02zX", entries.size());
newEntry.updateName(hexbuf);
entries.push_back(std::move(newEntry));
}
}
public:
void wipeTable(void)
{
entries.clear();
}
const std::string& getName(size_t index)
{
padEntries(index);
return entries[index].getName();
}
void updateName(size_t index, std::string_view name)
{
padEntries(index);
entries[index].updateName(name);
}
bool updateReading(size_t index, double reading, int raw)
{
padEntries(index);
return entries[index].updateReading(reading, raw);
}
};
class IPMIWriteEntry
{
private:
bool writePermission = false;
public:
bool getWritePermission(void) const
{
return writePermission;
}
void setWritePermission(bool permission)
{
writePermission = permission;
}
};
class IPMIWriteTable
{
private:
std::vector<IPMIWriteEntry> entries;
private:
void padEntries(size_t index)
{
// Pad vector until entries[index] becomes a valid index
if (entries.size() <= index)
{
entries.resize(index + 1);
}
}
public:
void wipeTable(void)
{
entries.clear();
}
bool getWritePermission(size_t index)
{
padEntries(index);
return entries[index].getWritePermission();
}
void setWritePermission(size_t index, bool permission)
{
padEntries(index);
entries[index].setWritePermission(permission);
}
};
// Store information for threshold sensors and they are not used by VR
// sensors. These objects are global singletons, used from a variety of places.
inline IPMIStatsTable sdrStatsTable;
inline IPMIWriteTable sdrWriteTable;
/**
* Search ObjectMapper for sensors and update them to subtree.
*
* The function will search for sensors under either
* /xyz/openbmc_project/sensors or /xyz/openbmc_project/extsensors. It will
* optionally search VR typed sensors under /xyz/openbmc_project/vr
*
* @return the updated amount of times any of "sensors" or "extsensors" sensor
* paths updated successfully, previous amount if all failed. The "vr"
* sensor path is optional, and does not participate in the return value.
*/
uint16_t getSensorSubtree(std::shared_ptr<SensorSubTree>& subtree);
bool getSensorNumMap(std::shared_ptr<SensorNumMap>& sensorNumMap);
} // namespace details
bool getSensorSubtree(SensorSubTree& subtree);
#ifdef FEATURE_HYBRID_SENSORS
ipmi::sensor::IdInfoMap::const_iterator
findStaticSensor(const std::string& path);
#endif
struct CmpStr
{
bool operator()(const char* a, const char* b) const
{
return std::strcmp(a, b) < 0;
}
};
static constexpr size_t sensorTypeCodes = 0;
static constexpr size_t sensorEventTypeCodes = 1;
enum class SensorTypeCodes : uint8_t
{
reserved = 0x00,
temperature = 0x01,
voltage = 0x02,
current = 0x03,
fan = 0x04,
processor = 0x07,
power_unit = 0x09,
other = 0x0b,
memory = 0x0c,
buttons = 0x14,
watchdog2 = 0x23,
};
enum class SensorEventTypeCodes : uint8_t
{
unspecified = 0x00,
threshold = 0x01,
sensorSpecified = 0x6f
};
const static boost::container::flat_map<
const char*, std::pair<SensorTypeCodes, SensorEventTypeCodes>, CmpStr>
sensorTypes{
{{"temperature", std::make_pair(SensorTypeCodes::temperature,
SensorEventTypeCodes::threshold)},
{"voltage", std::make_pair(SensorTypeCodes::voltage,
SensorEventTypeCodes::threshold)},
{"current", std::make_pair(SensorTypeCodes::current,
SensorEventTypeCodes::threshold)},
{"fan_tach", std::make_pair(SensorTypeCodes::fan,
SensorEventTypeCodes::threshold)},
{"fan_pwm", std::make_pair(SensorTypeCodes::fan,
SensorEventTypeCodes::threshold)},
{"processor", std::make_pair(SensorTypeCodes::processor,
SensorEventTypeCodes::sensorSpecified)},
{"power", std::make_pair(SensorTypeCodes::other,
SensorEventTypeCodes::threshold)},
{"memory", std::make_pair(SensorTypeCodes::memory,
SensorEventTypeCodes::sensorSpecified)},
{"state", std::make_pair(SensorTypeCodes::power_unit,
SensorEventTypeCodes::sensorSpecified)},
{"buttons", std::make_pair(SensorTypeCodes::buttons,
SensorEventTypeCodes::sensorSpecified)},
{"watchdog", std::make_pair(SensorTypeCodes::watchdog2,
SensorEventTypeCodes::sensorSpecified)}}};
std::string getSensorTypeStringFromPath(const std::string& path);
uint8_t getSensorTypeFromPath(const std::string& path);
uint16_t getSensorNumberFromPath(const std::string& path);
uint8_t getSensorEventTypeFromPath(const std::string& path);
std::string getPathFromSensorNumber(uint16_t sensorNum);
namespace ipmi
{
std::map<std::string, std::vector<std::string>>
getObjectInterfaces(const char* path);
std::map<std::string, Value> getEntityManagerProperties(const char* path,
const char* interface);
const std::string* getSensorConfigurationInterface(
const std::map<std::string, std::vector<std::string>>&
sensorInterfacesResponse);
void updateIpmiFromAssociation(const std::string& path,
const DbusInterfaceMap& sensorMap,
uint8_t& entityId, uint8_t& entityInstance);
} // namespace ipmi
<commit_msg>dbus-sdr: Add physical security sensor type<commit_after>/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include <boost/algorithm/string.hpp>
#include <boost/bimap.hpp>
#include <boost/container/flat_map.hpp>
#include <cstdio>
#include <cstring>
#include <exception>
#include <filesystem>
#include <ipmid/api.hpp>
#include <ipmid/types.hpp>
#include <map>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus/match.hpp>
#include <string>
#include <vector>
#pragma once
static constexpr bool debug = false;
struct CmpStrVersion
{
bool operator()(std::string a, std::string b) const
{
return strverscmp(a.c_str(), b.c_str()) < 0;
}
};
using SensorSubTree = boost::container::flat_map<
std::string,
boost::container::flat_map<std::string, std::vector<std::string>>,
CmpStrVersion>;
using SensorNumMap = boost::bimap<int, std::string>;
static constexpr uint16_t maxSensorsPerLUN = 255;
static constexpr uint16_t maxIPMISensors = (maxSensorsPerLUN * 3);
static constexpr uint16_t lun1Sensor0 = 0x100;
static constexpr uint16_t lun3Sensor0 = 0x300;
static constexpr uint16_t invalidSensorNumber = 0xFFFF;
static constexpr uint8_t reservedSensorNumber = 0xFF;
namespace details
{
// Enable/disable the logging of stats instrumentation
static constexpr bool enableInstrumentation = false;
class IPMIStatsEntry
{
private:
int numReadings = 0;
int numMissings = 0;
int numStreakRead = 0;
int numStreakMiss = 0;
double minValue = 0.0;
double maxValue = 0.0;
std::string sensorName;
public:
const std::string& getName(void) const
{
return sensorName;
}
void updateName(std::string_view name)
{
sensorName = name;
}
// Returns true if this is the first successful reading
// This is so the caller can log the coefficients used
bool updateReading(double reading, int raw)
{
if constexpr (!enableInstrumentation)
{
return false;
}
bool first = ((numReadings == 0) && (numMissings == 0));
// Sensors can use "nan" to indicate unavailable reading
if (!(std::isfinite(reading)))
{
// Only show this if beginning a new streak
if (numStreakMiss == 0)
{
std::cerr << "IPMI sensor " << sensorName
<< ": Missing reading, byte=" << raw
<< ", Reading counts good=" << numReadings
<< " miss=" << numMissings
<< ", Prior good streak=" << numStreakRead << "\n";
}
numStreakRead = 0;
++numMissings;
++numStreakMiss;
return first;
}
// Only show this if beginning a new streak and not the first time
if ((numStreakRead == 0) && (numReadings != 0))
{
std::cerr << "IPMI sensor " << sensorName
<< ": Recovered reading, value=" << reading
<< " byte=" << raw
<< ", Reading counts good=" << numReadings
<< " miss=" << numMissings
<< ", Prior miss streak=" << numStreakMiss << "\n";
}
// Initialize min/max if the first successful reading
if (numReadings == 0)
{
std::cerr << "IPMI sensor " << sensorName
<< ": First reading, value=" << reading << " byte=" << raw
<< "\n";
minValue = reading;
maxValue = reading;
}
numStreakMiss = 0;
++numReadings;
++numStreakRead;
// Only provide subsequent output if new min/max established
if (reading < minValue)
{
std::cerr << "IPMI sensor " << sensorName
<< ": Lowest reading, value=" << reading
<< " byte=" << raw << "\n";
minValue = reading;
}
if (reading > maxValue)
{
std::cerr << "IPMI sensor " << sensorName
<< ": Highest reading, value=" << reading
<< " byte=" << raw << "\n";
maxValue = reading;
}
return first;
}
};
class IPMIStatsTable
{
private:
std::vector<IPMIStatsEntry> entries;
private:
void padEntries(size_t index)
{
char hexbuf[16];
// Pad vector until entries[index] becomes a valid index
while (entries.size() <= index)
{
// As name not known yet, use human-readable hex as name
IPMIStatsEntry newEntry;
sprintf(hexbuf, "0x%02zX", entries.size());
newEntry.updateName(hexbuf);
entries.push_back(std::move(newEntry));
}
}
public:
void wipeTable(void)
{
entries.clear();
}
const std::string& getName(size_t index)
{
padEntries(index);
return entries[index].getName();
}
void updateName(size_t index, std::string_view name)
{
padEntries(index);
entries[index].updateName(name);
}
bool updateReading(size_t index, double reading, int raw)
{
padEntries(index);
return entries[index].updateReading(reading, raw);
}
};
class IPMIWriteEntry
{
private:
bool writePermission = false;
public:
bool getWritePermission(void) const
{
return writePermission;
}
void setWritePermission(bool permission)
{
writePermission = permission;
}
};
class IPMIWriteTable
{
private:
std::vector<IPMIWriteEntry> entries;
private:
void padEntries(size_t index)
{
// Pad vector until entries[index] becomes a valid index
if (entries.size() <= index)
{
entries.resize(index + 1);
}
}
public:
void wipeTable(void)
{
entries.clear();
}
bool getWritePermission(size_t index)
{
padEntries(index);
return entries[index].getWritePermission();
}
void setWritePermission(size_t index, bool permission)
{
padEntries(index);
entries[index].setWritePermission(permission);
}
};
// Store information for threshold sensors and they are not used by VR
// sensors. These objects are global singletons, used from a variety of places.
inline IPMIStatsTable sdrStatsTable;
inline IPMIWriteTable sdrWriteTable;
/**
* Search ObjectMapper for sensors and update them to subtree.
*
* The function will search for sensors under either
* /xyz/openbmc_project/sensors or /xyz/openbmc_project/extsensors. It will
* optionally search VR typed sensors under /xyz/openbmc_project/vr
*
* @return the updated amount of times any of "sensors" or "extsensors" sensor
* paths updated successfully, previous amount if all failed. The "vr"
* sensor path is optional, and does not participate in the return value.
*/
uint16_t getSensorSubtree(std::shared_ptr<SensorSubTree>& subtree);
bool getSensorNumMap(std::shared_ptr<SensorNumMap>& sensorNumMap);
} // namespace details
bool getSensorSubtree(SensorSubTree& subtree);
#ifdef FEATURE_HYBRID_SENSORS
ipmi::sensor::IdInfoMap::const_iterator
findStaticSensor(const std::string& path);
#endif
struct CmpStr
{
bool operator()(const char* a, const char* b) const
{
return std::strcmp(a, b) < 0;
}
};
static constexpr size_t sensorTypeCodes = 0;
static constexpr size_t sensorEventTypeCodes = 1;
enum class SensorTypeCodes : uint8_t
{
reserved = 0x00,
temperature = 0x01,
voltage = 0x02,
current = 0x03,
fan = 0x04,
physical_security = 0x5,
processor = 0x07,
power_unit = 0x09,
other = 0x0b,
memory = 0x0c,
buttons = 0x14,
watchdog2 = 0x23,
};
enum class SensorEventTypeCodes : uint8_t
{
unspecified = 0x00,
threshold = 0x01,
sensorSpecified = 0x6f
};
const static boost::container::flat_map<
const char*, std::pair<SensorTypeCodes, SensorEventTypeCodes>, CmpStr>
sensorTypes{
{{"temperature", std::make_pair(SensorTypeCodes::temperature,
SensorEventTypeCodes::threshold)},
{"voltage", std::make_pair(SensorTypeCodes::voltage,
SensorEventTypeCodes::threshold)},
{"current", std::make_pair(SensorTypeCodes::current,
SensorEventTypeCodes::threshold)},
{"fan_tach", std::make_pair(SensorTypeCodes::fan,
SensorEventTypeCodes::threshold)},
{"fan_pwm", std::make_pair(SensorTypeCodes::fan,
SensorEventTypeCodes::threshold)},
{"intrusion", std::make_pair(SensorTypeCodes::physical_security,
SensorEventTypeCodes::sensorSpecified)},
{"processor", std::make_pair(SensorTypeCodes::processor,
SensorEventTypeCodes::sensorSpecified)},
{"power", std::make_pair(SensorTypeCodes::other,
SensorEventTypeCodes::threshold)},
{"memory", std::make_pair(SensorTypeCodes::memory,
SensorEventTypeCodes::sensorSpecified)},
{"state", std::make_pair(SensorTypeCodes::power_unit,
SensorEventTypeCodes::sensorSpecified)},
{"buttons", std::make_pair(SensorTypeCodes::buttons,
SensorEventTypeCodes::sensorSpecified)},
{"watchdog", std::make_pair(SensorTypeCodes::watchdog2,
SensorEventTypeCodes::sensorSpecified)}}};
std::string getSensorTypeStringFromPath(const std::string& path);
uint8_t getSensorTypeFromPath(const std::string& path);
uint16_t getSensorNumberFromPath(const std::string& path);
uint8_t getSensorEventTypeFromPath(const std::string& path);
std::string getPathFromSensorNumber(uint16_t sensorNum);
namespace ipmi
{
std::map<std::string, std::vector<std::string>>
getObjectInterfaces(const char* path);
std::map<std::string, Value> getEntityManagerProperties(const char* path,
const char* interface);
const std::string* getSensorConfigurationInterface(
const std::map<std::string, std::vector<std::string>>&
sensorInterfacesResponse);
void updateIpmiFromAssociation(const std::string& path,
const DbusInterfaceMap& sensorMap,
uint8_t& entityId, uint8_t& entityInstance);
} // namespace ipmi
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2017 Arlen Keshabyan ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <iostream>
#include "planar_movements_recognizer.hpp"
#include "platform.hpp"
#include "platform_utilities.hpp"
#include "strings.hpp"
#include "utilities.hpp"
#include "cmdline_options.hpp"
#include "process.hpp"
#include "signal_slot.hpp"
#include <sstream>
#include <iostream>
int main(int argc, char **argv)
{
using namespace nstd::str;
using namespace nstd::platform;
using namespace nstd::platform::utilities;
using namespace nstd::utilities;
using namespace nstd::process;
using namespace std::string_literals;
using namespace std::string_view_literals;
scoped_console_utf8 set_console_utf8;
const std::u8string_view str { u8"Консоль поддерживает UTF-8..." };
std::cout << std::string(std::begin(str), std::end(str)) << std::endl;
Process proc("echo \"Redirected output\"", "", [](auto a, auto b){ std::cout << std::endl << ">> " << std::string(a, b) << std::endl; }, [](auto a, auto b){});
(void)proc.get_exit_status();
nstd::po::parser p;
std::string shell_cmd;
auto help_callback { [&p]{ std::cout << p << std::endl; } };
p["execute"].abbreviation('E').type(nstd::po::string).description("Executes the provided shell command (not actually)").bind(shell_cmd);
p["help"].abbreviation('?').callback(help_callback).description("Prints the help screen");
auto pres { p(argc, argv) };
auto &&exe = p["execute"];
if (argc == 1 || !pres) help_callback();
if (exe.was_set() && !is_empty_or_ws(shell_cmd)) { std::cout << "command to execute: " << shell_cmd << std::endl; return 0; }
const std::string app_name { "pmr_example" };
__at_scope_exit_c(&app_name) { const std::u8string_view str { u8"Всё ещё UTF8..." }; std::cout << std::string(std::begin(str), std::end(str)) << " [" << app_name << "]" << std::endl; };
std::vector<at_scope_exit::at_scope_exit<at_scope_exit::always>> exit_chain;
exit_chain.emplace_back([&app_name] { std::cout << std::endl << "#1. exitting " << app_name << "..." << std::endl; });
exit_chain.emplace_back([] { std::cout << "#2. stopped" << std::endl; });
constexpr const bool if_windows { current_os_family == os_family::Windows };
auto cmd { compose_string(if_windows ? "where" : "which", " gcc 2>&1") };
auto res { shell_execute(cmd) };
std::cout << "shell execution result: \"" << trim(res) << "\"" << std::endl << std::endl;
cmd = "wmic diskdrive get DeviceID,FirmwareRevision,Model,SerialNumber";
res = shell_execute(cmd);
std::cout << "shell execution result: \"" << std::endl << trim(res) << std::endl << "\"" << std::endl << std::endl;
std::cout << "-----------------------" << std::endl;
if constexpr (if_windows)
{
std::istringstream iss { res };
std::string line;
while (std::getline(iss, line, '\n'))
{
if (is_empty_or_ws(line)) continue;
std::cout << "line: " << line << std::endl;
auto result { nstd::str::split_regex(line, "\\s{2,}"s) };
for (const auto &l : result) std::cout << "\t[" << l << "]" << std::endl;
}
}
std::cout << "Is Little Endian: " << boolalpha[is_little_endian] << std::endl;
std::cout << "Is 64 bit: " << boolalpha[is_64bit] << std::endl;
std::cout << " OS: " << get_current_os_type_name() << std::endl;
std::cout << "Platform: " << get_current_os_family_name() << std::endl;
std::cout << "Compiler: " << get_current_compiler_name() << std::endl << std::endl;
exit_chain.emplace_back([]{ std::cout << "#3. ..." << std::endl; });
try
{
__at_scope_exit_c() { std::cout << "Test for always is passed..." << std::endl; };
__at_scope_failed_c() { std::cout << "Test for failure is passed..." << std::endl; };
__at_scope_succeeded_c() { std::cout << "Test for failure isn't passed..." << std::endl; };
std::cout << "Making a failure..." << std::endl;
throw std::runtime_error("");
}
catch(const std::runtime_error &)
{
}
{
__at_scope_exit_c() { std::cout << "Test for always is passed..." << std::endl; };
__at_scope_failed_c() { std::cout << "Test for success isn't passed..." << std::endl; };
__at_scope_succeeded_c() { std::cout << "Test for success is passed..." << std::endl; };
std::cout << "Making a success..." << std::endl;
}
std::cout << std::endl;
using namespace std::string_literals;
using namespace nstd::pmr;
enum command : uint8_t
{
unknown = 0,
open_file = 100, close_file,
go_back, go_forward,
reload
};
using event = planar_movements_event_provider::event;
planar_movements_event_provider pmep;
command_recognizer<event, command> cr;
remove_noise_filter rnf;
nstd::signal_slot::connection_bag cons;
nstd::signal_slot::signal_set<command> command_signals;
cons = command_signals[command::unknown].connect([](){ std::cout << "Unknown" << std::endl; });
cons = command_signals[command::open_file].connect([](){ std::cout << "Open file" << std::endl; });
cons = command_signals[command::close_file].connect([](){ std::cout << "Close file" << std::endl; });
cons = command_signals[command::go_back].connect([](){ std::cout << "Go back" << std::endl; });
cons = command_signals[command::go_forward].connect([](){ std::cout << "Go forward" << std::endl; });
cons = command_signals[command::reload].connect([](){ std::cout << "Reload" << std::endl; });
auto emit_signal = [&command_signals, &cr, &rnf](auto &&coords) { command_signals[cr(rnf(std::move(coords)))].emit(); };
cr. add_command(command::open_file, { event::up }).
add_command(command::close_file, { event::down }).
add_command(command::go_back, { event::left }).
add_command(command::go_forward, { event::right }).
add_command(command::reload, { event::down, event::up })
;
{
std::vector<event> coords { pmep(100., 100.), pmep(150., 105.), pmep(200., 103.), pmep(250., 102.), pmep(300., 95.) }; // moving right
emit_signal(std::move(coords));
}
{
event_filter<event> ef(true);
ef.set(event::right, event::left);
// moving right, but mapping the right event to the left one using event_filter
std::vector<event> coords { ef(pmep(100., 100.)), ef(pmep(150., 105.)), ef(pmep(200., 103.)), ef(pmep(250., 102.)), ef(pmep(300., 95.)) }; // moving right
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; // moving up
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.) }; // moving down
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.),
pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; // moving down & up
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(300., 95.), pmep(1300., 11.), pmep(30., 5150.), pmep(0., 25.), pmep(0., 129.) }; // Noise / Unknown
emit_signal(std::move(coords));
}
return 0;
}
<commit_msg>small refinement<commit_after>/*
MIT License
Copyright (c) 2017 Arlen Keshabyan ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <iostream>
#include "planar_movements_recognizer.hpp"
#include "platform.hpp"
#include "platform_utilities.hpp"
#include "strings.hpp"
#include "utilities.hpp"
#include "cmdline_options.hpp"
#include "process.hpp"
#include "signal_slot.hpp"
#include <sstream>
#include <iostream>
int main(int argc, char **argv)
{
using namespace nstd::str;
using namespace nstd::platform;
using namespace nstd::platform::utilities;
using namespace nstd::utilities;
using namespace nstd::process;
using namespace std::string_literals;
using namespace std::string_view_literals;
scoped_console_utf8 set_console_utf8;
const std::u8string_view str { u8"Консоль поддерживает UTF-8..." };
std::cout << std::string(std::begin(str), std::end(str)) << std::endl;
Process proc("echo \"Redirected output\"", "", [](auto a, auto b){ std::cout << std::endl << ">> " << std::string(a, b) << std::endl; }, [](auto a, auto b){});
(void)proc.get_exit_status();
nstd::po::parser p;
std::string shell_cmd;
auto help_callback { [&p]{ std::cout << p << std::endl; } };
p["execute"].abbreviation('E').type(nstd::po::string).description("Executes the provided shell command (not actually)").bind(shell_cmd);
p["help"].abbreviation('?').callback(help_callback).description("Prints the help screen");
auto pres { p(argc, argv) };
auto &&exe = p["execute"];
if (argc == 1 || !pres) help_callback();
if (exe.was_set() && !is_empty_or_ws(shell_cmd)) { std::cout << "command to execute: " << shell_cmd << std::endl; return 0; }
const std::string app_name { "pmr_example" };
__at_scope_exit_c(&app_name) { const std::u8string_view str { u8"Всё ещё UTF8..." }; std::cout << std::string(std::begin(str), std::end(str)) << " [" << app_name << "]" << std::endl; };
std::vector<at_scope_exit::at_scope_exit<at_scope_exit::always>> exit_chain;
exit_chain.emplace_back([&app_name] { std::cout << std::endl << "#1. exitting " << app_name << "..." << std::endl; });
exit_chain.emplace_back([] { std::cout << "#2. stopped" << std::endl; });
constexpr const bool if_windows { current_os_family == os_family::Windows };
auto cmd { compose_string(if_windows ? "where" : "which", " gcc 2>&1") };
auto res { shell_execute(cmd) };
std::cout << "shell execution result: \"" << trim(res) << "\"" << std::endl << std::endl;
if constexpr (if_windows)
{
cmd = "wmic diskdrive get DeviceID,FirmwareRevision,Model,SerialNumber";
res = shell_execute(cmd);
std::cout << "shell execution result: \"" << std::endl << trim(res) << std::endl << "\"" << std::endl << std::endl;
std::cout << "-----------------------" << std::endl;
std::istringstream iss { res };
std::string line;
while (std::getline(iss, line, '\n'))
{
if (is_empty_or_ws(line)) continue;
std::cout << "line: " << line << std::endl;
auto result { nstd::str::split_regex(line, "\\s{2,}"s) };
for (const auto &l : result) std::cout << "\t[" << l << "]" << std::endl;
}
}
std::cout << "Is Little Endian: " << boolalpha[is_little_endian] << std::endl;
std::cout << "Is 64 bit: " << boolalpha[is_64bit] << std::endl;
std::cout << " OS: " << get_current_os_type_name() << std::endl;
std::cout << "Platform: " << get_current_os_family_name() << std::endl;
std::cout << "Compiler: " << get_current_compiler_name() << std::endl << std::endl;
exit_chain.emplace_back([]{ std::cout << "#3. ..." << std::endl; });
try
{
__at_scope_exit_c() { std::cout << "Test for always is passed..." << std::endl; };
__at_scope_failed_c() { std::cout << "Test for failure is passed..." << std::endl; };
__at_scope_succeeded_c() { std::cout << "Test for failure isn't passed..." << std::endl; };
std::cout << "Making a failure..." << std::endl;
throw std::runtime_error("");
}
catch(const std::runtime_error &)
{
}
{
__at_scope_exit_c() { std::cout << "Test for always is passed..." << std::endl; };
__at_scope_failed_c() { std::cout << "Test for success isn't passed..." << std::endl; };
__at_scope_succeeded_c() { std::cout << "Test for success is passed..." << std::endl; };
std::cout << "Making a success..." << std::endl;
}
std::cout << std::endl;
using namespace std::string_literals;
using namespace nstd::pmr;
enum command : uint8_t
{
unknown = 0,
open_file = 100, close_file,
go_back, go_forward,
reload
};
using event = planar_movements_event_provider::event;
planar_movements_event_provider pmep;
command_recognizer<event, command> cr;
remove_noise_filter rnf;
nstd::signal_slot::connection_bag cons;
nstd::signal_slot::signal_set<command> command_signals;
cons = command_signals[command::unknown].connect([](){ std::cout << "Unknown" << std::endl; });
cons = command_signals[command::open_file].connect([](){ std::cout << "Open file" << std::endl; });
cons = command_signals[command::close_file].connect([](){ std::cout << "Close file" << std::endl; });
cons = command_signals[command::go_back].connect([](){ std::cout << "Go back" << std::endl; });
cons = command_signals[command::go_forward].connect([](){ std::cout << "Go forward" << std::endl; });
cons = command_signals[command::reload].connect([](){ std::cout << "Reload" << std::endl; });
auto emit_signal = [&command_signals, &cr, &rnf](auto &&coords) { command_signals[cr(rnf(std::move(coords)))].emit(); };
cr. add_command(command::open_file, { event::up }).
add_command(command::close_file, { event::down }).
add_command(command::go_back, { event::left }).
add_command(command::go_forward, { event::right }).
add_command(command::reload, { event::down, event::up })
;
{
std::vector<event> coords { pmep(100., 100.), pmep(150., 105.), pmep(200., 103.), pmep(250., 102.), pmep(300., 95.) }; // moving right
emit_signal(std::move(coords));
}
{
event_filter<event> ef(true);
ef.set(event::right, event::left);
// moving right, but mapping the right event to the left one using event_filter
std::vector<event> coords { ef(pmep(100., 100.)), ef(pmep(150., 105.)), ef(pmep(200., 103.)), ef(pmep(250., 102.)), ef(pmep(300., 95.)) }; // moving right
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; // moving up
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.) }; // moving down
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(300., 95.), pmep(300., 120.), pmep(300., 150.), pmep(310., 202.), pmep(295., 239.),
pmep(295., 239.), pmep(310., 202.), pmep(300., 150.), pmep(300., 120.), pmep(300., 95.) }; // moving down & up
emit_signal(std::move(coords));
}
{
std::vector<event> coords { pmep(300., 95.), pmep(1300., 11.), pmep(30., 5150.), pmep(0., 25.), pmep(0., 129.) }; // Noise / Unknown
emit_signal(std::move(coords));
}
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (C) 2004 Reinhold Kainhofer <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "incidencechanger.h"
#include "kogroupware.h"
#include "koprefs.h"
#include "mailscheduler.h"
#include <KCal/AssignmentVisitor>
#include <KCal/CalendarResources>
#include <KCal/DndFactory>
#include <KCal/FreeBusy>
#include <KCal/Incidence>
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
bool IncidenceChanger::beginChange( Incidence *incidence )
{
if ( !incidence ) {
return false;
}
kDebug() << "for incidence \"" << incidence->summary() << "\"";
return mCalendar->beginChange( incidence );
}
bool IncidenceChanger::sendGroupwareMessage( KCal::Incidence *incidence,
KCal::iTIPMethod method, bool deleting )
{
if ( KOPrefs::instance()->thatIsMe( incidence->organizer().email() ) &&
incidence->attendeeCount() > 0 &&
!KOPrefs::instance()->mUseGroupwareCommunication ) {
emit schedule( method, incidence );
return true;
} else if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
// FIXME: Find a widget to use as parent, instead of 0
return KOGroupware::instance()->sendICalMessage( 0, method, incidence, deleting );
}
return true;
}
void IncidenceChanger::cancelAttendees( Incidence *incidence )
{
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( KMessageBox::questionYesNo(
0,
i18n( "Some attendees were removed from the incidence. "
"Shall cancel messages be sent to these attendees?" ),
i18n( "Attendees Removed" ), KGuiItem( i18n( "Send Messages" ) ),
KGuiItem( i18n( "Do Not Send" ) ) ) == KMessageBox::Yes ) {
// don't use KOGroupware::sendICalMessage here, because that asks just
// a very general question "Other people are involved, send message to
// them?", which isn't helpful at all in this situation. Afterwards, it
// would only call the MailScheduler::performTransaction, so do this
// manually.
// FIXME: Groupware schedulling should be factored out to it's own class
// anyway
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( incidence, iTIPCancel );
}
}
}
bool IncidenceChanger::endChange( Incidence *incidence )
{
// FIXME: if that's a groupware incidence, and I'm not the organizer,
// send out a mail to the organizer with a counterproposal instead
// of actually changing the incidence. Then no locking is needed.
// FIXME: if that's a groupware incidence, and the incidence was
// never locked, we can't unlock it with endChange().
if ( !incidence ) {
return false;
}
kDebug() << "\"" << incidence->summary() << "\"";
return mCalendar->endChange( incidence );
}
bool IncidenceChanger::deleteIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel, true );
if( doDelete ) {
// @TODO: let Calendar::deleteIncidence do the locking...
Incidence *tmp = incidence->clone();
emit incidenceToBeDeleted( incidence );
doDelete = mCalendar->deleteIncidence( incidence );
if ( !KOPrefs::instance()->thatIsMe( tmp->organizer().email() ) ) {
const QStringList myEmails = KOPrefs::instance()->allEmails();
bool notifyOrganizer = false;
for ( QStringList::ConstIterator it = myEmails.begin(); it != myEmails.end(); ++it ) {
QString email = *it;
Attendee *me = tmp->attendeeByMail(email);
if ( me ) {
if ( me->status() == KCal::Attendee::Accepted ||
me->status() == KCal::Attendee::Delegated ) {
notifyOrganizer = true;
}
Attendee *newMe = new Attendee( *me );
newMe->setStatus( KCal::Attendee::Declined );
tmp->clearAttendees();
tmp->addAttendee( newMe );
break;
}
}
if ( notifyOrganizer ) {
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( tmp, KCal::iTIPReply );
}
}
emit incidenceDeleted( incidence );
}
return doDelete;
}
bool IncidenceChanger::cutIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel );
if( doDelete ) {
// @TODO: the factory needs to do the locking!
DndFactory factory( mCalendar );
emit incidenceToBeDeleted( incidence );
factory.cutIncidence( incidence );
emit incidenceDeleted( incidence );
}
return doDelete;
}
class IncidenceChanger::ComparisonVisitor : public IncidenceBase::Visitor
{
public:
ComparisonVisitor() {}
bool act( IncidenceBase *incidence, IncidenceBase *inc2 )
{
mIncidence2 = inc2;
if ( incidence ) {
return incidence->accept( *this );
} else {
return inc2 == 0;
}
}
protected:
bool visit( Event *event )
{
Event *ev2 = dynamic_cast<Event*>(mIncidence2);
if ( event && ev2 ) {
return *event == *ev2;
} else {
// either both 0, or return false;
return ev2 == event;
}
}
bool visit( Todo *todo )
{
Todo *to2 = dynamic_cast<Todo*>( mIncidence2 );
if ( todo && to2 ) {
return *todo == *to2;
} else {
// either both 0, or return false;
return todo == to2;
}
}
bool visit( Journal *journal )
{
Journal *j2 = dynamic_cast<Journal*>( mIncidence2 );
if ( journal && j2 ) {
return *journal == *j2;
} else {
// either both 0, or return false;
return journal == j2;
}
}
bool visit( FreeBusy *fb )
{
FreeBusy *fb2 = dynamic_cast<FreeBusy*>( mIncidence2 );
if ( fb && fb2 ) {
return *fb == *fb2;
} else {
// either both 0, or return false;
return fb2 == fb;
}
}
protected:
IncidenceBase *mIncidence2;
};
bool IncidenceChanger::incidencesEqual( Incidence *inc1, Incidence *inc2 )
{
ComparisonVisitor v;
return ( v.act( inc1, inc2 ) );
}
bool IncidenceChanger::assignIncidence( Incidence *inc1, Incidence *inc2 )
{
if ( !inc1 || !inc2 ) {
return false;
}
AssignmentVisitor v;
return v.assign( inc1, inc2 );
}
bool IncidenceChanger::myAttendeeStatusChanged( Incidence *oldInc, Incidence *newInc )
{
Attendee *oldMe = oldInc->attendeeByMails( KOPrefs::instance()->allEmails() );
Attendee *newMe = newInc->attendeeByMails( KOPrefs::instance()->allEmails() );
if ( oldMe && newMe && ( oldMe->status() != newMe->status() ) ) {
return true;
}
return false;
}
bool IncidenceChanger::changeIncidence( Incidence *oldinc, Incidence *newinc,
int action )
{
kDebug() << "for incidence \"" << newinc->summary() << "\""
<< "( old one was \"" << oldinc->summary() << "\")";
if ( incidencesEqual( newinc, oldinc ) ) {
// Don't do anything
kDebug() << "Incidence not changed";
} else {
kDebug() << "Changing incidence";
bool statusChanged = myAttendeeStatusChanged( oldinc, newinc );
int revision = newinc->revision();
newinc->setRevision( revision + 1 );
// FIXME: Use a generic method for this! Ideally, have an interface class
// for group cheduling. Each implementation could then just do what
// it wants with the event. If no groupware is used,use the null
// pattern...
bool revert = KOPrefs::instance()->mUseGroupwareCommunication;
if ( revert &&
KOGroupware::instance()->sendICalMessage( 0,
KCal::iTIPRequest,
newinc, false, statusChanged ) ) {
// Accept the event changes
if ( action < 0 ) {
emit incidenceChanged( oldinc, newinc );
} else {
emit incidenceChanged( oldinc, newinc, action );
}
revert = false;
}
if ( revert ) {
assignIncidence( newinc, oldinc );
return false;
}
}
return true;
}
bool IncidenceChanger::addIncidence( Incidence *incidence, QWidget *parent )
{
kDebug() << "\"" << incidence->summary() << "\"";
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( !KOGroupware::instance()->sendICalMessage( parent,
KCal::iTIPRequest,
incidence ) ) {
return false;
}
}
// FIXME: This is a nasty hack, since we need to set a parent for the
// resource selection dialog. However, we don't have any UI methods
// in the calendar, only in the CalendarResources::DestinationPolicy
// So we need to type-cast it and extract it from the CalendarResources
CalendarResources *stdcal = dynamic_cast<CalendarResources*>( mCalendar );
QWidget *tmpparent = 0;
if ( stdcal ) {
tmpparent = stdcal->dialogParentWidget();
stdcal->setDialogParentWidget( parent );
}
bool success = mCalendar->addIncidence( incidence );
if ( stdcal ) {
// Reset the parent widget, otherwise we'll end up with pointers to deleted
// widgets sooner or later
stdcal->setDialogParentWidget( tmpparent );
}
if ( !success ) {
// We can have a failure if the user pressed [cancel] in the resource
// selectdialog, so check the exception.
ErrorFormat *e = stdcal->exception();
if ( !e || ( e && ( e->errorCode() != KCal::ErrorFormat::UserCancel ) ) ) {
KMessageBox::sorry( parent,
i18n( "Unable to save %1 \"%2\".",
i18n( incidence->type() ),
incidence->summary() ) );
}
return false;
}
emit incidenceAdded( incidence );
return true;
}
#include "incidencechanger.moc"
<commit_msg>- Undoing modifications was only working if "Use Groupware Communication" was enabled. - Recording completed tasks to journals was only working if "Use Groupware Communication" was enabled. - Undoing "Also Delete Future" now works.<commit_after>/*
This file is part of KOrganizer.
Copyright (C) 2004 Reinhold Kainhofer <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "incidencechanger.h"
#include "kogroupware.h"
#include "koprefs.h"
#include "mailscheduler.h"
#include <KCal/AssignmentVisitor>
#include <KCal/CalendarResources>
#include <KCal/DndFactory>
#include <KCal/FreeBusy>
#include <KCal/Incidence>
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
bool IncidenceChanger::beginChange( Incidence *incidence )
{
if ( !incidence ) {
return false;
}
kDebug() << "for incidence \"" << incidence->summary() << "\"";
return mCalendar->beginChange( incidence );
}
bool IncidenceChanger::sendGroupwareMessage( KCal::Incidence *incidence,
KCal::iTIPMethod method, bool deleting )
{
if ( KOPrefs::instance()->thatIsMe( incidence->organizer().email() ) &&
incidence->attendeeCount() > 0 &&
!KOPrefs::instance()->mUseGroupwareCommunication ) {
emit schedule( method, incidence );
return true;
} else if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
// FIXME: Find a widget to use as parent, instead of 0
return KOGroupware::instance()->sendICalMessage( 0, method, incidence, deleting );
}
return true;
}
void IncidenceChanger::cancelAttendees( Incidence *incidence )
{
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( KMessageBox::questionYesNo(
0,
i18n( "Some attendees were removed from the incidence. "
"Shall cancel messages be sent to these attendees?" ),
i18n( "Attendees Removed" ), KGuiItem( i18n( "Send Messages" ) ),
KGuiItem( i18n( "Do Not Send" ) ) ) == KMessageBox::Yes ) {
// don't use KOGroupware::sendICalMessage here, because that asks just
// a very general question "Other people are involved, send message to
// them?", which isn't helpful at all in this situation. Afterwards, it
// would only call the MailScheduler::performTransaction, so do this
// manually.
// FIXME: Groupware schedulling should be factored out to it's own class
// anyway
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( incidence, iTIPCancel );
}
}
}
bool IncidenceChanger::endChange( Incidence *incidence )
{
// FIXME: if that's a groupware incidence, and I'm not the organizer,
// send out a mail to the organizer with a counterproposal instead
// of actually changing the incidence. Then no locking is needed.
// FIXME: if that's a groupware incidence, and the incidence was
// never locked, we can't unlock it with endChange().
if ( !incidence ) {
return false;
}
kDebug() << "\"" << incidence->summary() << "\"";
return mCalendar->endChange( incidence );
}
bool IncidenceChanger::deleteIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel, true );
if( doDelete ) {
// @TODO: let Calendar::deleteIncidence do the locking...
Incidence *tmp = incidence->clone();
emit incidenceToBeDeleted( incidence );
doDelete = mCalendar->deleteIncidence( incidence );
if ( !KOPrefs::instance()->thatIsMe( tmp->organizer().email() ) ) {
const QStringList myEmails = KOPrefs::instance()->allEmails();
bool notifyOrganizer = false;
for ( QStringList::ConstIterator it = myEmails.begin(); it != myEmails.end(); ++it ) {
QString email = *it;
Attendee *me = tmp->attendeeByMail(email);
if ( me ) {
if ( me->status() == KCal::Attendee::Accepted ||
me->status() == KCal::Attendee::Delegated ) {
notifyOrganizer = true;
}
Attendee *newMe = new Attendee( *me );
newMe->setStatus( KCal::Attendee::Declined );
tmp->clearAttendees();
tmp->addAttendee( newMe );
break;
}
}
if ( notifyOrganizer ) {
KCal::MailScheduler scheduler( mCalendar );
scheduler.performTransaction( tmp, KCal::iTIPReply );
}
}
emit incidenceDeleted( incidence );
}
return doDelete;
}
bool IncidenceChanger::cutIncidence( Incidence *incidence )
{
if ( !incidence ) {
return true;
}
kDebug() << "\"" << incidence->summary() << "\"";
bool doDelete = sendGroupwareMessage( incidence, KCal::iTIPCancel );
if( doDelete ) {
// @TODO: the factory needs to do the locking!
DndFactory factory( mCalendar );
emit incidenceToBeDeleted( incidence );
factory.cutIncidence( incidence );
emit incidenceDeleted( incidence );
}
return doDelete;
}
class IncidenceChanger::ComparisonVisitor : public IncidenceBase::Visitor
{
public:
ComparisonVisitor() {}
bool act( IncidenceBase *incidence, IncidenceBase *inc2 )
{
mIncidence2 = inc2;
if ( incidence ) {
return incidence->accept( *this );
} else {
return inc2 == 0;
}
}
protected:
bool visit( Event *event )
{
Event *ev2 = dynamic_cast<Event*>(mIncidence2);
if ( event && ev2 ) {
return *event == *ev2;
} else {
// either both 0, or return false;
return ev2 == event;
}
}
bool visit( Todo *todo )
{
Todo *to2 = dynamic_cast<Todo*>( mIncidence2 );
if ( todo && to2 ) {
return *todo == *to2;
} else {
// either both 0, or return false;
return todo == to2;
}
}
bool visit( Journal *journal )
{
Journal *j2 = dynamic_cast<Journal*>( mIncidence2 );
if ( journal && j2 ) {
return *journal == *j2;
} else {
// either both 0, or return false;
return journal == j2;
}
}
bool visit( FreeBusy *fb )
{
FreeBusy *fb2 = dynamic_cast<FreeBusy*>( mIncidence2 );
if ( fb && fb2 ) {
return *fb == *fb2;
} else {
// either both 0, or return false;
return fb2 == fb;
}
}
protected:
IncidenceBase *mIncidence2;
};
bool IncidenceChanger::incidencesEqual( Incidence *inc1, Incidence *inc2 )
{
ComparisonVisitor v;
return ( v.act( inc1, inc2 ) );
}
bool IncidenceChanger::assignIncidence( Incidence *inc1, Incidence *inc2 )
{
if ( !inc1 || !inc2 ) {
return false;
}
AssignmentVisitor v;
return v.assign( inc1, inc2 );
}
bool IncidenceChanger::myAttendeeStatusChanged( Incidence *oldInc, Incidence *newInc )
{
Attendee *oldMe = oldInc->attendeeByMails( KOPrefs::instance()->allEmails() );
Attendee *newMe = newInc->attendeeByMails( KOPrefs::instance()->allEmails() );
if ( oldMe && newMe && ( oldMe->status() != newMe->status() ) ) {
return true;
}
return false;
}
bool IncidenceChanger::changeIncidence( Incidence *oldinc, Incidence *newinc,
int action )
{
kDebug() << "for incidence \"" << newinc->summary() << "\""
<< "( old one was \"" << oldinc->summary() << "\")";
if ( incidencesEqual( newinc, oldinc ) ) {
// Don't do anything
kDebug() << "Incidence not changed";
} else {
kDebug() << "Changing incidence";
bool statusChanged = myAttendeeStatusChanged( oldinc, newinc );
int revision = newinc->revision();
newinc->setRevision( revision + 1 );
// FIXME: Use a generic method for this! Ideally, have an interface class
// for group cheduling. Each implementation could then just do what
// it wants with the event. If no groupware is used,use the null
// pattern...
bool success = true;
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
success = KOGroupware::instance()->sendICalMessage( 0,
KCal::iTIPRequest,
newinc, false, statusChanged );
}
if ( success ) {
// Accept the event changes
if ( action < 0 ) {
emit incidenceChanged( oldinc, newinc );
} else {
emit incidenceChanged( oldinc, newinc, action );
}
} else {
// revert changes
assignIncidence( newinc, oldinc );
return false;
}
}
return true;
}
bool IncidenceChanger::addIncidence( Incidence *incidence, QWidget *parent )
{
kDebug() << "\"" << incidence->summary() << "\"";
if ( KOPrefs::instance()->mUseGroupwareCommunication ) {
if ( !KOGroupware::instance()->sendICalMessage( parent,
KCal::iTIPRequest,
incidence ) ) {
return false;
}
}
// FIXME: This is a nasty hack, since we need to set a parent for the
// resource selection dialog. However, we don't have any UI methods
// in the calendar, only in the CalendarResources::DestinationPolicy
// So we need to type-cast it and extract it from the CalendarResources
CalendarResources *stdcal = dynamic_cast<CalendarResources*>( mCalendar );
QWidget *tmpparent = 0;
if ( stdcal ) {
tmpparent = stdcal->dialogParentWidget();
stdcal->setDialogParentWidget( parent );
}
bool success = mCalendar->addIncidence( incidence );
if ( stdcal ) {
// Reset the parent widget, otherwise we'll end up with pointers to deleted
// widgets sooner or later
stdcal->setDialogParentWidget( tmpparent );
}
if ( !success ) {
// We can have a failure if the user pressed [cancel] in the resource
// selectdialog, so check the exception.
ErrorFormat *e = stdcal->exception();
if ( !e || ( e && ( e->errorCode() != KCal::ErrorFormat::UserCancel ) ) ) {
KMessageBox::sorry( parent,
i18n( "Unable to save %1 \"%2\".",
i18n( incidence->type() ),
incidence->summary() ) );
}
return false;
}
emit incidenceAdded( incidence );
return true;
}
#include "incidencechanger.moc"
<|endoftext|> |
<commit_before>#include "multipart.h"
namespace cpr {
Multipart::Multipart(const std::initializer_list<Part>& parts) {
for (auto part = parts.begin(); part != parts.end(); ++part) {
this->parts.push_back(*part);
}
}
}
<commit_msg>std::vector can be constructed via initializer_list<commit_after>#include "multipart.h"
namespace cpr {
Multipart::Multipart(const std::initializer_list<Part>& parts)
: parts{parts} { }
}
<|endoftext|> |
<commit_before>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <mapper/mapper.h>
#include "pwm_synth/pwm.h"
int done = 0;
void ctrlc(int)
{
done = 1;
}
void handler_freq(mapper_signal sig, mapper_id instance, const void *value,
int count, mapper_timetag_t *timetag)
{
if (value) {
float *pfreq = (float*)value;
set_freq(*pfreq);
}
}
void handler_gain(mapper_signal sig, mapper_id instance, const void *value,
int count, mapper_timetag_t *timetag)
{
if (value) {
float *pgain = (float*)value;
set_gain(*pgain);
}
else
set_gain(0);
}
void handler_duty(mapper_signal sig, mapper_id instance, const void *value,
int count, mapper_timetag_t *timetag)
{
if (value) {
float *pduty = (float*)value;
set_duty(*pduty);
}
}
int main()
{
signal(SIGINT, ctrlc);
mapper_device dev = mapper_device_new("pwm", 9000, 0);
float min0 = 0;
float max1 = 1;
float max1000 = 1000;
mapper_device_add_input(dev, "/freq", 1, 'f', "Hz", &min0, &max1000,
handler_freq, 0);
mapper_device_add_input(dev, "/gain", 1, 'f', "Hz", &min0, &max1,
handler_gain, 0);
mapper_device_add_input(dev, "/duty", 1, 'f', "Hz", &min0, &max1,
handler_duty, 0);
run_synth();
set_duty(0.1);
set_freq(110.0);
set_gain(0.1);
printf("Press Ctrl-C to quit.\n");
while (!done)
mapper_device_poll(dev, 10);
mapper_device_free(dev);
set_freq(0);
sleep(1);
stop_synth();
}
<commit_msg>Updated PWM example.<commit_after>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <mapper/mapper.h>
#include "pwm_synth/pwm.h"
int done = 0;
void ctrlc(int)
{
done = 1;
}
void handler_freq(mapper_signal sig, mapper_id instance, const void *value,
int count, mapper_timetag_t *timetag)
{
if (value) {
float *pfreq = (float*)value;
set_freq(*pfreq);
}
}
void handler_gain(mapper_signal sig, mapper_id instance, const void *value,
int count, mapper_timetag_t *timetag)
{
if (value) {
float *pgain = (float*)value;
set_gain(*pgain);
}
else
set_gain(0);
}
void handler_duty(mapper_signal sig, mapper_id instance, const void *value,
int count, mapper_timetag_t *timetag)
{
if (value) {
float *pduty = (float*)value;
set_duty(*pduty);
}
}
int main()
{
signal(SIGINT, ctrlc);
mapper_device dev = mapper_device_new("pwm", 9000, 0);
float min0 = 0;
float max1 = 1;
float max1000 = 1000;
mapper_device_add_input_signal(dev, "/freq", 1, 'f', "Hz", &min0, &max1000,
handler_freq, 0);
mapper_device_add_input_signal(dev, "/gain", 1, 'f', "Hz", &min0, &max1,
handler_gain, 0);
mapper_device_add_input_signal(dev, "/duty", 1, 'f', "Hz", &min0, &max1,
handler_duty, 0);
run_synth();
set_duty(0.1);
set_freq(110.0);
set_gain(0.1);
printf("Press Ctrl-C to quit.\n");
while (!done)
mapper_device_poll(dev, 10);
mapper_device_free(dev);
set_freq(0);
sleep(1);
stop_synth();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#define BOOST_TEST_MODULE core
#include <boost/test/unit_test.hpp>
#include <array>
#include <boost/program_options.hpp>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include "utils/enum_option.hh"
namespace po = boost::program_options;
namespace {
struct days {
enum enumeration { Mo, Tu, We, Th, Fr, Sa, Su };
static std::unordered_map<std::string, enumeration> map() {
return {{"Mon", Mo}, {"Tue", Tu}, {"Wed", We}, {"Thu", Th}, {"Fri", Fr}, {"Sat", Sa}, {"Sun", Su}};
}
};
template <typename T>
enum_option<T> parse(const char* value) {
po::options_description desc("Allowed options");
desc.add_options()("opt", po::value<enum_option<T>>(), "Option");
po::variables_map vm;
const char* argv[] = {"$0", "--opt", value};
po::store(po::parse_command_line(3, argv, desc), vm);
return vm["opt"].as<enum_option<T>>();
}
template <typename T>
std::string format(typename T::enumeration d) {
std::ostringstream os;
os << enum_option<T>(d);
return os.str();
}
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_parsing) {
BOOST_CHECK_EQUAL(parse<days>("Sun"), days::Su);
BOOST_CHECK_EQUAL(parse<days>("Mon"), days::Mo);
BOOST_CHECK_EQUAL(parse<days>("Tue"), days::Tu);
BOOST_CHECK_EQUAL(parse<days>("Wed"), days::We);
BOOST_CHECK_EQUAL(parse<days>("Thu"), days::Th);
BOOST_CHECK_EQUAL(parse<days>("Fri"), days::Fr);
BOOST_CHECK_EQUAL(parse<days>("Sat"), days::Sa);
}
BOOST_AUTO_TEST_CASE(test_parsing_error) {
BOOST_REQUIRE_THROW(parse<days>("Sunday"), po::invalid_option_value);
BOOST_REQUIRE_THROW(parse<days>(""), po::invalid_option_value);
BOOST_REQUIRE_THROW(parse<days>(" "), po::invalid_option_value);
BOOST_REQUIRE_THROW(parse<days>(" Sun"), po::invalid_option_value);
}
BOOST_AUTO_TEST_CASE(test_formatting) {
BOOST_CHECK_EQUAL(format<days>(days::Mo), "Mon");
BOOST_CHECK_EQUAL(format<days>(days::Tu), "Tue");
BOOST_CHECK_EQUAL(format<days>(days::We), "Wed");
BOOST_CHECK_EQUAL(format<days>(days::Th), "Thu");
BOOST_CHECK_EQUAL(format<days>(days::Fr), "Fri");
BOOST_CHECK_EQUAL(format<days>(days::Sa), "Sat");
BOOST_CHECK_EQUAL(format<days>(days::Su), "Sun");
}
BOOST_AUTO_TEST_CASE(test_formatting_unknown) {
BOOST_CHECK_EQUAL(format<days>(static_cast<days::enumeration>(77)), "?unknown");
}
namespace {
struct names {
enum enumeration { John, Jane, Jim };
static std::map<std::string, enumeration> map() {
return {{"John", John}, {"Jane", Jane}, {"James", Jim}};
}
};
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_ordered_map) {
BOOST_CHECK_EQUAL(parse<names>("James"), names::Jim);
BOOST_CHECK_EQUAL(format<names>(names::Jim), "James");
BOOST_CHECK_EQUAL(parse<names>("John"), names::John);
BOOST_CHECK_EQUAL(format<names>(names::John), "John");
BOOST_CHECK_EQUAL(parse<names>("Jane"), names::Jane);
BOOST_CHECK_EQUAL(format<names>(names::Jane), "Jane");
BOOST_CHECK_THROW(parse<names>("Jimbo"), po::invalid_option_value);
BOOST_CHECK_EQUAL(format<names>(static_cast<names::enumeration>(77)), "?unknown");
}
namespace {
struct cities {
enum enumeration { SF, TO, NY };
static std::unordered_map<std::string, enumeration> map() {
return {
{"SanFrancisco", SF}, {"SF", SF}, {"SFO", SF}, {"Frisco", SF},
{"Toronto", TO}, {"TO", TO}, {"YYZ", TO}, {"TheSix", TO},
{"NewYork", NY}, {"NY", NY}, {"NYC", NY}, {"BigApple", NY},
};
}
};
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_multiple_parse) {
BOOST_CHECK_EQUAL(parse<cities>("SanFrancisco"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("SF"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("SFO"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("Frisco"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("Toronto"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("TO"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("YYZ"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("TheSix"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("NewYork"), cities::NY);
BOOST_CHECK_EQUAL(parse<cities>("NY"), cities::NY);
BOOST_CHECK_EQUAL(parse<cities>("NYC"), cities::NY);
BOOST_CHECK_EQUAL(parse<cities>("BigApple"), cities::NY);
}
BOOST_AUTO_TEST_CASE(test_multiple_format) {
BOOST_CHECK((std::set<std::string>{"SanFrancisco", "SF", "SFO", "Frisco"}).count(format<cities>(cities::SF)));
BOOST_CHECK((std::set<std::string>{"Toronto", "TO", "YYZ", "TheSix"}).count(format<cities>(cities::TO)));
BOOST_CHECK((std::set<std::string>{"NewYork", "NY", "NYC", "BigApple"}).count(format<cities>(cities::NY)));
}
namespace {
struct numbers {
enum enumeration { ONE, TWO };
static std::unordered_map<int, enumeration> map() {
return {{1, ONE}, {2, TWO}};
}
};
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_non_string) {
BOOST_CHECK_EQUAL(parse<numbers>("1"), numbers::ONE);
BOOST_CHECK_EQUAL(parse<numbers>("2"), numbers::TWO);
BOOST_CHECK_THROW(parse<numbers>("3"), po::invalid_option_value);
BOOST_CHECK_THROW(parse<numbers>("xx"), po::invalid_option_value);
BOOST_CHECK_THROW(parse<numbers>(""), po::invalid_option_value);
BOOST_CHECK_EQUAL(format<numbers>(numbers::ONE), "1");
BOOST_CHECK_EQUAL(format<numbers>(numbers::TWO), "2");
BOOST_CHECK_EQUAL(format<numbers>(static_cast<numbers::enumeration>(77)), "?unknown");
}
<commit_msg>enum_option_test: Add an explicit underlying type to an enum<commit_after>/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#define BOOST_TEST_MODULE core
#include <boost/test/unit_test.hpp>
#include <array>
#include <boost/program_options.hpp>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include "utils/enum_option.hh"
namespace po = boost::program_options;
namespace {
struct days {
enum enumeration : uint8_t { Mo, Tu, We, Th, Fr, Sa, Su };
static std::unordered_map<std::string, enumeration> map() {
return {{"Mon", Mo}, {"Tue", Tu}, {"Wed", We}, {"Thu", Th}, {"Fri", Fr}, {"Sat", Sa}, {"Sun", Su}};
}
};
template <typename T>
enum_option<T> parse(const char* value) {
po::options_description desc("Allowed options");
desc.add_options()("opt", po::value<enum_option<T>>(), "Option");
po::variables_map vm;
const char* argv[] = {"$0", "--opt", value};
po::store(po::parse_command_line(3, argv, desc), vm);
return vm["opt"].as<enum_option<T>>();
}
template <typename T>
std::string format(typename T::enumeration d) {
std::ostringstream os;
os << enum_option<T>(d);
return os.str();
}
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_parsing) {
BOOST_CHECK_EQUAL(parse<days>("Sun"), days::Su);
BOOST_CHECK_EQUAL(parse<days>("Mon"), days::Mo);
BOOST_CHECK_EQUAL(parse<days>("Tue"), days::Tu);
BOOST_CHECK_EQUAL(parse<days>("Wed"), days::We);
BOOST_CHECK_EQUAL(parse<days>("Thu"), days::Th);
BOOST_CHECK_EQUAL(parse<days>("Fri"), days::Fr);
BOOST_CHECK_EQUAL(parse<days>("Sat"), days::Sa);
}
BOOST_AUTO_TEST_CASE(test_parsing_error) {
BOOST_REQUIRE_THROW(parse<days>("Sunday"), po::invalid_option_value);
BOOST_REQUIRE_THROW(parse<days>(""), po::invalid_option_value);
BOOST_REQUIRE_THROW(parse<days>(" "), po::invalid_option_value);
BOOST_REQUIRE_THROW(parse<days>(" Sun"), po::invalid_option_value);
}
BOOST_AUTO_TEST_CASE(test_formatting) {
BOOST_CHECK_EQUAL(format<days>(days::Mo), "Mon");
BOOST_CHECK_EQUAL(format<days>(days::Tu), "Tue");
BOOST_CHECK_EQUAL(format<days>(days::We), "Wed");
BOOST_CHECK_EQUAL(format<days>(days::Th), "Thu");
BOOST_CHECK_EQUAL(format<days>(days::Fr), "Fri");
BOOST_CHECK_EQUAL(format<days>(days::Sa), "Sat");
BOOST_CHECK_EQUAL(format<days>(days::Su), "Sun");
}
BOOST_AUTO_TEST_CASE(test_formatting_unknown) {
BOOST_CHECK_EQUAL(format<days>(static_cast<days::enumeration>(77)), "?unknown");
}
namespace {
struct names {
enum enumeration { John, Jane, Jim };
static std::map<std::string, enumeration> map() {
return {{"John", John}, {"Jane", Jane}, {"James", Jim}};
}
};
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_ordered_map) {
BOOST_CHECK_EQUAL(parse<names>("James"), names::Jim);
BOOST_CHECK_EQUAL(format<names>(names::Jim), "James");
BOOST_CHECK_EQUAL(parse<names>("John"), names::John);
BOOST_CHECK_EQUAL(format<names>(names::John), "John");
BOOST_CHECK_EQUAL(parse<names>("Jane"), names::Jane);
BOOST_CHECK_EQUAL(format<names>(names::Jane), "Jane");
BOOST_CHECK_THROW(parse<names>("Jimbo"), po::invalid_option_value);
BOOST_CHECK_EQUAL(format<names>(static_cast<names::enumeration>(77)), "?unknown");
}
namespace {
struct cities {
enum enumeration { SF, TO, NY };
static std::unordered_map<std::string, enumeration> map() {
return {
{"SanFrancisco", SF}, {"SF", SF}, {"SFO", SF}, {"Frisco", SF},
{"Toronto", TO}, {"TO", TO}, {"YYZ", TO}, {"TheSix", TO},
{"NewYork", NY}, {"NY", NY}, {"NYC", NY}, {"BigApple", NY},
};
}
};
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_multiple_parse) {
BOOST_CHECK_EQUAL(parse<cities>("SanFrancisco"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("SF"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("SFO"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("Frisco"), cities::SF);
BOOST_CHECK_EQUAL(parse<cities>("Toronto"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("TO"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("YYZ"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("TheSix"), cities::TO);
BOOST_CHECK_EQUAL(parse<cities>("NewYork"), cities::NY);
BOOST_CHECK_EQUAL(parse<cities>("NY"), cities::NY);
BOOST_CHECK_EQUAL(parse<cities>("NYC"), cities::NY);
BOOST_CHECK_EQUAL(parse<cities>("BigApple"), cities::NY);
}
BOOST_AUTO_TEST_CASE(test_multiple_format) {
BOOST_CHECK((std::set<std::string>{"SanFrancisco", "SF", "SFO", "Frisco"}).count(format<cities>(cities::SF)));
BOOST_CHECK((std::set<std::string>{"Toronto", "TO", "YYZ", "TheSix"}).count(format<cities>(cities::TO)));
BOOST_CHECK((std::set<std::string>{"NewYork", "NY", "NYC", "BigApple"}).count(format<cities>(cities::NY)));
}
namespace {
struct numbers {
enum enumeration { ONE, TWO };
static std::unordered_map<int, enumeration> map() {
return {{1, ONE}, {2, TWO}};
}
};
} // anonymous namespace
BOOST_AUTO_TEST_CASE(test_non_string) {
BOOST_CHECK_EQUAL(parse<numbers>("1"), numbers::ONE);
BOOST_CHECK_EQUAL(parse<numbers>("2"), numbers::TWO);
BOOST_CHECK_THROW(parse<numbers>("3"), po::invalid_option_value);
BOOST_CHECK_THROW(parse<numbers>("xx"), po::invalid_option_value);
BOOST_CHECK_THROW(parse<numbers>(""), po::invalid_option_value);
BOOST_CHECK_EQUAL(format<numbers>(numbers::ONE), "1");
BOOST_CHECK_EQUAL(format<numbers>(numbers::TWO), "2");
BOOST_CHECK_EQUAL(format<numbers>(static_cast<numbers::enumeration>(77)), "?unknown");
}
<|endoftext|> |
<commit_before>/* dhcpclient.cpp - dhcp client request handling
*
* (c) 2011-2016 Nicholas J. Kain <njkain at gmail dot 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sstream>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <net/if.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <format.hpp>
#include "dhcpclient.hpp"
#include "leasestore.hpp"
#include "dhcplua.hpp"
#include "clientid.hpp"
extern "C" {
#include "options.h"
}
namespace ba = boost::asio;
extern std::unique_ptr<LeaseStore> gLeaseStore;
extern std::unique_ptr<DhcpLua> gLua;
std::unique_ptr<ClientStates> client_states_v4;
void init_client_states_v4(ba::io_service &io_service)
{
client_states_v4 = std::make_unique<ClientStates>(io_service);
}
ClientListener::ClientListener(ba::io_service &io_service,
const ba::ip::udp::endpoint &endpoint,
const std::string &ifname)
: socket_(io_service)
{
socket_.open(endpoint.protocol());
socket_.set_option(ba::ip::udp::socket::broadcast(true));
socket_.set_option(ba::ip::udp::socket::do_not_route(true));
socket_.set_option(ba::ip::udp::socket::reuse_address(true));
socket_.bind(endpoint);
int fd = socket_.native();
struct ifreq ifr;
memset(&ifr, 0, sizeof (struct ifreq));
memcpy(ifr.ifr_name, ifname.c_str(), ifname.size());
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof ifr) < 0) {
fmt::print(stderr, "failed to bind socket to device: {}\n", strerror(errno));
exit(EXIT_FAILURE);
}
struct ifaddrs *ifaddr, *ifa;
if (getifaddrs(&ifaddr) == -1) {
fmt::print(stderr, "failed to get list of interface ips: {}\n", strerror(errno));
exit(EXIT_FAILURE);
}
for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr)
continue;
if (strcmp(ifa->ifa_name, ifname.c_str()))
continue;
if (ifa->ifa_addr->sa_family != AF_INET)
continue;
char lipbuf[INET_ADDRSTRLEN];
if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
lipbuf, sizeof lipbuf)) {
fmt::print(stderr, "failed to parse IP for interface ({}): {}\n",
ifname, strerror(errno));
exit(EXIT_FAILURE);
}
local_ip_ = ba::ip::address::from_string(lipbuf);
break;
}
freeifaddrs(ifaddr);
if (!local_ip_.is_v4()) {
fmt::print(stderr, "interface ({}) has no IP address\n", ifname);
exit(EXIT_FAILURE);
}
start_receive();
}
void ClientListener::dhcpmsg_init(dhcpmsg &dm, char type, uint32_t xid,
const ClientID &clientid) const
{
memset(&dm, 0, sizeof (struct dhcpmsg));
dm.op = 2; // BOOTREPLY (server)
dm.htype = 1;
dm.hlen = 6;
dm.xid = xid;
dm.cookie = htonl(DHCP_MAGIC);
dm.options[0] = DCODE_END;
memcpy(&dm.chaddr, &dhcpmsg_.chaddr, sizeof dhcpmsg_.chaddr);
add_option_msgtype(&dm, type);
add_option_serverid(&dm, local_ip());
if (clientid.had_option()) {
auto &cid = clientid.value();
add_option_clientid(&dm, cid.data(), cid.size());
}
}
uint32_t ClientListener::local_ip() const
{
uint32_t ret;
if (inet_pton(AF_INET, local_ip_.to_string().c_str(), &ret) != 1) {
fmt::print(stderr, "inet_pton failed: {}\n", strerror(errno));
return 0;
}
return ret;
}
void ClientListener::send_reply_do(const dhcpmsg &dm, SendReplyType srt)
{
ssize_t endloc = get_end_option_idx(&dm);
if (endloc < 0)
return;
boost::system::error_code ignored_error;
auto buf = boost::asio::buffer((const char *)&dm, sizeof dm -
(sizeof dm.options - 1 - endloc));
switch (srt) {
case SendReplyType::UnicastCi: {
auto uct = ba::ip::address_v4(ntohl(dhcpmsg_.ciaddr));
socket_.send_to(buf, ba::ip::udp::endpoint(uct, 68), 0, ignored_error);
break;
}
case SendReplyType::Broadcast: {
auto remotebcast = remote_endpoint_.address().to_v4().broadcast();
socket_.send_to(buf, ba::ip::udp::endpoint(remotebcast, 68),
0, ignored_error);
break;
}
case SendReplyType::Relay: {
auto relay = ba::ip::address_v4(ntohl(dhcpmsg_.giaddr));
socket_.send_to(buf, ba::ip::udp::endpoint(relay, 67),
0, ignored_error);
break;
}
case SendReplyType::UnicastYiCh: {
auto uct = ba::ip::address_v4(ntohl(dhcpmsg_.yiaddr));
socket_.send_to(buf, ba::ip::udp::endpoint(uct, 68), 0, ignored_error);
break;
}
}
}
std::string ClientListener::ipStr(uint32_t ip) const
{
char addrbuf[INET_ADDRSTRLEN];
auto r = inet_ntop(AF_INET, &ip, addrbuf, sizeof addrbuf);
if (!r)
return std::string("");
return std::string(addrbuf);
}
uint64_t ClientListener::getNowTs(void) const {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
void ClientListener::send_reply(const dhcpmsg &reply)
{
if (dhcpmsg_.giaddr)
send_reply_do(reply, SendReplyType::Relay);
else if (dhcpmsg_.ciaddr)
send_reply_do(reply, SendReplyType::UnicastCi);
else if (ntohs(dhcpmsg_.flags) & 0x8000u)
send_reply_do(reply, SendReplyType::Broadcast);
else if (dhcpmsg_.yiaddr)
send_reply_do(reply, SendReplyType::UnicastYiCh);
else
send_reply_do(reply, SendReplyType::Broadcast);
}
void ClientListener::reply_discover(const ClientID &clientid)
{
struct dhcpmsg reply;
dhcpmsg_init(reply, DHCPOFFER, dhcpmsg_.xid, clientid);
if (gLua->reply_discover(reply, local_ip_.to_string(),
remote_endpoint_.address().to_string(),
clientid)) {
send_reply(reply);
}
}
void ClientListener::reply_request(const ClientID &clientid, bool is_direct)
{
struct dhcpmsg reply;
std::string leaseip;
dhcpmsg_init(reply, DHCPACK, dhcpmsg_.xid, clientid);
if (gLua->reply_request(reply, local_ip_.to_string(),
remote_endpoint_.address().to_string(),
clientid)) {
leaseip = ipStr(reply.yiaddr);
if (!leaseip.size())
goto out;
gLeaseStore->addLease(local_ip_.to_string(), clientid, leaseip,
getNowTs() + get_option_leasetime(&reply));
send_reply(reply);
}
out:
client_states_v4->stateKill(dhcpmsg_.xid, clientid);
}
static ba::ip::address_v4 zero_v4(0lu);
void ClientListener::reply_inform(const ClientID &clientid)
{
struct dhcpmsg reply;
dhcpmsg_init(reply, DHCPACK, dhcpmsg_.xid, clientid);
if (gLua->reply_inform(reply, local_ip_.to_string(),
remote_endpoint_.address().to_string(), clientid)) {
// http://tools.ietf.org/html/draft-ietf-dhc-dhcpinform-clarify-06
reply.htype = dhcpmsg_.htype;
reply.hlen = dhcpmsg_.hlen;
memcpy(&reply.chaddr, &dhcpmsg_.chaddr, sizeof reply.chaddr);
reply.ciaddr = dhcpmsg_.ciaddr;
// xid was already set equal
reply.flags = dhcpmsg_.flags;
reply.hops = 0;
reply.secs = 0;
reply.yiaddr = 0;
reply.siaddr = 0;
if (dhcpmsg_.ciaddr)
send_reply_do(reply, SendReplyType::UnicastCi);
else if (dhcpmsg_.giaddr) {
auto fl = ntohs(reply.flags);
reply.flags = htons(fl | 0x8000u);
send_reply_do(reply, SendReplyType::Relay);
} else if (remote_endpoint_.address() != zero_v4)
send_reply_do(reply, SendReplyType::UnicastCi);
else
send_reply_do(reply, SendReplyType::Broadcast);
}
}
void ClientListener::do_release(const ClientID &clientid) {
std::string lip =
gLeaseStore->getLease(socket_.local_endpoint().address().to_string(),
clientid);
if (lip != remote_endpoint_.address().to_string()) {
fmt::print("do_release: ignoring spoofed release request. {} != {}.\n",
remote_endpoint_.address().to_string(), lip);
std::fflush(stdout);
return;
}
gLeaseStore->delLease(socket_.local_endpoint().address().to_string(),
clientid);
}
std::string ClientListener::getChaddr(const struct dhcpmsg &dm) const
{
char mac[7];
memcpy(mac, dm.chaddr, sizeof mac - 1);
return std::string(mac, 6);
}
std::string ClientListener::getClientId(const struct dhcpmsg &dm) const
{
char buf[MAX_DOPT_SIZE];
auto len = get_option_clientid(&dm, buf, sizeof buf);
if (len < 2)
return std::string("");
return std::string(buf, len);
}
uint8_t ClientListener::validate_dhcp(size_t len) const
{
if (len < offsetof(struct dhcpmsg, options))
return DHCPNULL;
if (ntohl(dhcpmsg_.cookie) != DHCP_MAGIC)
return DHCPNULL;
return get_option_msgtype(&dhcpmsg_);
}
void ClientListener::start_receive()
{
socket_.async_receive_from
(ba::buffer(recv_buffer_), remote_endpoint_,
[this](const boost::system::error_code &error,
std::size_t bytes_xferred)
{
bool direct_request = false;
size_t msglen = std::min(bytes_xferred, sizeof dhcpmsg_);
memset(&dhcpmsg_, 0, sizeof dhcpmsg_);
memcpy(&dhcpmsg_, recv_buffer_.data(), msglen);
uint8_t msgtype = validate_dhcp(msglen);
if (!msgtype) {
start_receive();
return;
}
ClientID clientid(getClientId(dhcpmsg_), getChaddr(dhcpmsg_));
auto cs = client_states_v4->stateGet(dhcpmsg_.xid, clientid);
if (cs == DHCPNULL) {
switch (msgtype) {
case DHCPREQUEST:
direct_request = true;
case DHCPDISCOVER:
cs = msgtype;
client_states_v4->stateAdd(dhcpmsg_.xid, clientid, cs);
break;
case DHCPINFORM:
// No need to track state since we just INFORM => ACK
case DHCPDECLINE:
case DHCPRELEASE:
cs = msgtype;
break;
default:
start_receive();
return;
}
} else {
if (cs == DHCPDISCOVER && msgtype == DHCPREQUEST)
cs = DHCPREQUEST;
}
switch (cs) {
case DHCPDISCOVER: reply_discover(clientid); break;
case DHCPREQUEST: reply_request(clientid, direct_request); break;
case DHCPINFORM: reply_inform(clientid); break;
case DHCPDECLINE:
fmt::print("Received a DHCPDECLINE. Clients conflict?\n");
case DHCPRELEASE: do_release(clientid); break;
}
start_receive();
});
}
<commit_msg>sstream is not used.<commit_after>/* dhcpclient.cpp - dhcp client request handling
*
* (c) 2011-2016 Nicholas J. Kain <njkain at gmail dot 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <net/if.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <format.hpp>
#include "dhcpclient.hpp"
#include "leasestore.hpp"
#include "dhcplua.hpp"
#include "clientid.hpp"
extern "C" {
#include "options.h"
}
namespace ba = boost::asio;
extern std::unique_ptr<LeaseStore> gLeaseStore;
extern std::unique_ptr<DhcpLua> gLua;
std::unique_ptr<ClientStates> client_states_v4;
void init_client_states_v4(ba::io_service &io_service)
{
client_states_v4 = std::make_unique<ClientStates>(io_service);
}
ClientListener::ClientListener(ba::io_service &io_service,
const ba::ip::udp::endpoint &endpoint,
const std::string &ifname)
: socket_(io_service)
{
socket_.open(endpoint.protocol());
socket_.set_option(ba::ip::udp::socket::broadcast(true));
socket_.set_option(ba::ip::udp::socket::do_not_route(true));
socket_.set_option(ba::ip::udp::socket::reuse_address(true));
socket_.bind(endpoint);
int fd = socket_.native();
struct ifreq ifr;
memset(&ifr, 0, sizeof (struct ifreq));
memcpy(ifr.ifr_name, ifname.c_str(), ifname.size());
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof ifr) < 0) {
fmt::print(stderr, "failed to bind socket to device: {}\n", strerror(errno));
exit(EXIT_FAILURE);
}
struct ifaddrs *ifaddr, *ifa;
if (getifaddrs(&ifaddr) == -1) {
fmt::print(stderr, "failed to get list of interface ips: {}\n", strerror(errno));
exit(EXIT_FAILURE);
}
for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr)
continue;
if (strcmp(ifa->ifa_name, ifname.c_str()))
continue;
if (ifa->ifa_addr->sa_family != AF_INET)
continue;
char lipbuf[INET_ADDRSTRLEN];
if (!inet_ntop(AF_INET, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
lipbuf, sizeof lipbuf)) {
fmt::print(stderr, "failed to parse IP for interface ({}): {}\n",
ifname, strerror(errno));
exit(EXIT_FAILURE);
}
local_ip_ = ba::ip::address::from_string(lipbuf);
break;
}
freeifaddrs(ifaddr);
if (!local_ip_.is_v4()) {
fmt::print(stderr, "interface ({}) has no IP address\n", ifname);
exit(EXIT_FAILURE);
}
start_receive();
}
void ClientListener::dhcpmsg_init(dhcpmsg &dm, char type, uint32_t xid,
const ClientID &clientid) const
{
memset(&dm, 0, sizeof (struct dhcpmsg));
dm.op = 2; // BOOTREPLY (server)
dm.htype = 1;
dm.hlen = 6;
dm.xid = xid;
dm.cookie = htonl(DHCP_MAGIC);
dm.options[0] = DCODE_END;
memcpy(&dm.chaddr, &dhcpmsg_.chaddr, sizeof dhcpmsg_.chaddr);
add_option_msgtype(&dm, type);
add_option_serverid(&dm, local_ip());
if (clientid.had_option()) {
auto &cid = clientid.value();
add_option_clientid(&dm, cid.data(), cid.size());
}
}
uint32_t ClientListener::local_ip() const
{
uint32_t ret;
if (inet_pton(AF_INET, local_ip_.to_string().c_str(), &ret) != 1) {
fmt::print(stderr, "inet_pton failed: {}\n", strerror(errno));
return 0;
}
return ret;
}
void ClientListener::send_reply_do(const dhcpmsg &dm, SendReplyType srt)
{
ssize_t endloc = get_end_option_idx(&dm);
if (endloc < 0)
return;
boost::system::error_code ignored_error;
auto buf = boost::asio::buffer((const char *)&dm, sizeof dm -
(sizeof dm.options - 1 - endloc));
switch (srt) {
case SendReplyType::UnicastCi: {
auto uct = ba::ip::address_v4(ntohl(dhcpmsg_.ciaddr));
socket_.send_to(buf, ba::ip::udp::endpoint(uct, 68), 0, ignored_error);
break;
}
case SendReplyType::Broadcast: {
auto remotebcast = remote_endpoint_.address().to_v4().broadcast();
socket_.send_to(buf, ba::ip::udp::endpoint(remotebcast, 68),
0, ignored_error);
break;
}
case SendReplyType::Relay: {
auto relay = ba::ip::address_v4(ntohl(dhcpmsg_.giaddr));
socket_.send_to(buf, ba::ip::udp::endpoint(relay, 67),
0, ignored_error);
break;
}
case SendReplyType::UnicastYiCh: {
auto uct = ba::ip::address_v4(ntohl(dhcpmsg_.yiaddr));
socket_.send_to(buf, ba::ip::udp::endpoint(uct, 68), 0, ignored_error);
break;
}
}
}
std::string ClientListener::ipStr(uint32_t ip) const
{
char addrbuf[INET_ADDRSTRLEN];
auto r = inet_ntop(AF_INET, &ip, addrbuf, sizeof addrbuf);
if (!r)
return std::string("");
return std::string(addrbuf);
}
uint64_t ClientListener::getNowTs(void) const {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
void ClientListener::send_reply(const dhcpmsg &reply)
{
if (dhcpmsg_.giaddr)
send_reply_do(reply, SendReplyType::Relay);
else if (dhcpmsg_.ciaddr)
send_reply_do(reply, SendReplyType::UnicastCi);
else if (ntohs(dhcpmsg_.flags) & 0x8000u)
send_reply_do(reply, SendReplyType::Broadcast);
else if (dhcpmsg_.yiaddr)
send_reply_do(reply, SendReplyType::UnicastYiCh);
else
send_reply_do(reply, SendReplyType::Broadcast);
}
void ClientListener::reply_discover(const ClientID &clientid)
{
struct dhcpmsg reply;
dhcpmsg_init(reply, DHCPOFFER, dhcpmsg_.xid, clientid);
if (gLua->reply_discover(reply, local_ip_.to_string(),
remote_endpoint_.address().to_string(),
clientid)) {
send_reply(reply);
}
}
void ClientListener::reply_request(const ClientID &clientid, bool is_direct)
{
struct dhcpmsg reply;
std::string leaseip;
dhcpmsg_init(reply, DHCPACK, dhcpmsg_.xid, clientid);
if (gLua->reply_request(reply, local_ip_.to_string(),
remote_endpoint_.address().to_string(),
clientid)) {
leaseip = ipStr(reply.yiaddr);
if (!leaseip.size())
goto out;
gLeaseStore->addLease(local_ip_.to_string(), clientid, leaseip,
getNowTs() + get_option_leasetime(&reply));
send_reply(reply);
}
out:
client_states_v4->stateKill(dhcpmsg_.xid, clientid);
}
static ba::ip::address_v4 zero_v4(0lu);
void ClientListener::reply_inform(const ClientID &clientid)
{
struct dhcpmsg reply;
dhcpmsg_init(reply, DHCPACK, dhcpmsg_.xid, clientid);
if (gLua->reply_inform(reply, local_ip_.to_string(),
remote_endpoint_.address().to_string(), clientid)) {
// http://tools.ietf.org/html/draft-ietf-dhc-dhcpinform-clarify-06
reply.htype = dhcpmsg_.htype;
reply.hlen = dhcpmsg_.hlen;
memcpy(&reply.chaddr, &dhcpmsg_.chaddr, sizeof reply.chaddr);
reply.ciaddr = dhcpmsg_.ciaddr;
// xid was already set equal
reply.flags = dhcpmsg_.flags;
reply.hops = 0;
reply.secs = 0;
reply.yiaddr = 0;
reply.siaddr = 0;
if (dhcpmsg_.ciaddr)
send_reply_do(reply, SendReplyType::UnicastCi);
else if (dhcpmsg_.giaddr) {
auto fl = ntohs(reply.flags);
reply.flags = htons(fl | 0x8000u);
send_reply_do(reply, SendReplyType::Relay);
} else if (remote_endpoint_.address() != zero_v4)
send_reply_do(reply, SendReplyType::UnicastCi);
else
send_reply_do(reply, SendReplyType::Broadcast);
}
}
void ClientListener::do_release(const ClientID &clientid) {
std::string lip =
gLeaseStore->getLease(socket_.local_endpoint().address().to_string(),
clientid);
if (lip != remote_endpoint_.address().to_string()) {
fmt::print("do_release: ignoring spoofed release request. {} != {}.\n",
remote_endpoint_.address().to_string(), lip);
std::fflush(stdout);
return;
}
gLeaseStore->delLease(socket_.local_endpoint().address().to_string(),
clientid);
}
std::string ClientListener::getChaddr(const struct dhcpmsg &dm) const
{
char mac[7];
memcpy(mac, dm.chaddr, sizeof mac - 1);
return std::string(mac, 6);
}
std::string ClientListener::getClientId(const struct dhcpmsg &dm) const
{
char buf[MAX_DOPT_SIZE];
auto len = get_option_clientid(&dm, buf, sizeof buf);
if (len < 2)
return std::string("");
return std::string(buf, len);
}
uint8_t ClientListener::validate_dhcp(size_t len) const
{
if (len < offsetof(struct dhcpmsg, options))
return DHCPNULL;
if (ntohl(dhcpmsg_.cookie) != DHCP_MAGIC)
return DHCPNULL;
return get_option_msgtype(&dhcpmsg_);
}
void ClientListener::start_receive()
{
socket_.async_receive_from
(ba::buffer(recv_buffer_), remote_endpoint_,
[this](const boost::system::error_code &error,
std::size_t bytes_xferred)
{
bool direct_request = false;
size_t msglen = std::min(bytes_xferred, sizeof dhcpmsg_);
memset(&dhcpmsg_, 0, sizeof dhcpmsg_);
memcpy(&dhcpmsg_, recv_buffer_.data(), msglen);
uint8_t msgtype = validate_dhcp(msglen);
if (!msgtype) {
start_receive();
return;
}
ClientID clientid(getClientId(dhcpmsg_), getChaddr(dhcpmsg_));
auto cs = client_states_v4->stateGet(dhcpmsg_.xid, clientid);
if (cs == DHCPNULL) {
switch (msgtype) {
case DHCPREQUEST:
direct_request = true;
case DHCPDISCOVER:
cs = msgtype;
client_states_v4->stateAdd(dhcpmsg_.xid, clientid, cs);
break;
case DHCPINFORM:
// No need to track state since we just INFORM => ACK
case DHCPDECLINE:
case DHCPRELEASE:
cs = msgtype;
break;
default:
start_receive();
return;
}
} else {
if (cs == DHCPDISCOVER && msgtype == DHCPREQUEST)
cs = DHCPREQUEST;
}
switch (cs) {
case DHCPDISCOVER: reply_discover(clientid); break;
case DHCPREQUEST: reply_request(clientid, direct_request); break;
case DHCPINFORM: reply_inform(clientid); break;
case DHCPDECLINE:
fmt::print("Received a DHCPDECLINE. Clients conflict?\n");
case DHCPRELEASE: do_release(clientid); break;
}
start_receive();
});
}
<|endoftext|> |
<commit_before>#include "Matcher.h"
using cv::vconcat;
using cv::DMatch;
namespace cmt {
void Matcher::initialize(const vector<Point2f> & pts_fg_norm, const Mat desc_fg, const vector<int> & classes_fg,
const Mat desc_bg, const Point2f center)
{
FILE_LOG(logDEBUG) << "Matcher::initialize() call";
//Copy normalized points
this->pts_fg_norm = pts_fg_norm;
//Remember number of background points
this->num_bg_points = desc_bg.rows;
//Form database by stacking background and foreground features
vconcat(desc_bg, desc_fg, database);
//Extract descriptor length from features
desc_length = database.cols*8;
//Create background classes (-1)
vector<int> classes_bg = vector<int>(desc_bg.rows,-1);
//Concatenate fg and bg classes
classes = classes_bg;
classes.insert(classes.end(), classes_fg.begin(), classes_fg.end());
//Create descriptor matcher
bfmatcher = DescriptorMatcher::create("BruteForce-Hamming");
FILE_LOG(logDEBUG) << "Matcher::initialize() return";
}
void Matcher::matchGlobal(const vector<KeyPoint> & keypoints, const Mat descriptors,
vector<Point2f> & points_matched, vector<int> & classes_matched)
{
FILE_LOG(logDEBUG) << "Matcher::matchGlobal() call";
if (keypoints.size() == 0)
{
FILE_LOG(logDEBUG) << "Matcher::matchGlobal() return";
return;
}
vector<vector<DMatch> > matches;
bfmatcher->knnMatch(descriptors, database, matches, 2);
for (size_t i = 0; i < matches.size(); i++)
{
vector<DMatch> m = matches[i];
float distance1 = m[0].distance / desc_length;
float distance2 = m[1].distance / desc_length;
int matched_class = classes[m[0].trainIdx];
if (matched_class == -1) continue;
if (distance1 > thr_dist) continue;
if (distance1/distance2 > thr_ratio) continue;
points_matched.push_back(keypoints[i].pt);
classes_matched.push_back(matched_class);
}
FILE_LOG(logDEBUG) << "Matcher::matchGlobal() return";
}
void Matcher::matchLocal(const vector<KeyPoint> & keypoints, const Mat descriptors,
const Point2f center, const float scale, const float rotation,
vector<Point2f> & points_matched, vector<int> & classes_matched)
{
FILE_LOG(logDEBUG) << "Matcher::matchLocal() call";
if (keypoints.size() == 0) {
FILE_LOG(logDEBUG) << "Matcher::matchLocal() return";
return;
}
//Transform initial points
vector<Point2f> pts_fg_trans;
pts_fg_trans.reserve(pts_fg_norm.size());
for (size_t i = 0; i < pts_fg_norm.size(); i++)
{
pts_fg_trans.push_back(scale * rotate(pts_fg_norm[i], -rotation));
}
//Perform local matching
for (size_t i = 0; i < keypoints.size(); i++)
{
Point2f location_rel = keypoints[i].pt - center;
//Find potential indices for matching
vector<int> indices_potential;
for (size_t j = 0; j < pts_fg_trans.size(); j++)
{
float l2norm = norm(pts_fg_trans[j] - location_rel);
if (l2norm < thr_cutoff) {
indices_potential.push_back(num_bg_points + j);
}
}
//Build descriptor matrix and classes from potential indices
Mat database_potential = Mat(indices_potential.size(), database.cols, database.type());
for (size_t j = 0; j < indices_potential.size(); j++) {
database.row(indices_potential[j]).copyTo(database_potential.row(j));
}
//Find distances between descriptors
vector<vector<DMatch> > matches;
bfmatcher->knnMatch(database_potential, descriptors.row(i), matches, 2);
//Perform matching
for (size_t j = 0; j < matches.size(); j++)
{
vector<DMatch> m = matches[j];
float distance1 = m[0].distance / desc_length;
float distance2 = m[1].distance / desc_length;
int matched_class = classes[indices_potential[m[0].queryIdx]];
if (distance1 > thr_dist) continue;
if (distance1/distance2 > thr_ratio) continue;
points_matched.push_back(keypoints[i].pt);
classes_matched.push_back(matched_class);
}
}
FILE_LOG(logDEBUG) << "Matcher::matchLocal() return";
}
} /* namespace CMT */
<commit_msg>Fixed bug in Matcher<commit_after>#include "Matcher.h"
using cv::vconcat;
using cv::DMatch;
namespace cmt {
void Matcher::initialize(const vector<Point2f> & pts_fg_norm, const Mat desc_fg, const vector<int> & classes_fg,
const Mat desc_bg, const Point2f center)
{
FILE_LOG(logDEBUG) << "Matcher::initialize() call";
//Copy normalized points
this->pts_fg_norm = pts_fg_norm;
//Remember number of background points
this->num_bg_points = desc_bg.rows;
//Form database by stacking background and foreground features
vconcat(desc_bg, desc_fg, database);
//Extract descriptor length from features
desc_length = database.cols*8;
//Create background classes (-1)
vector<int> classes_bg = vector<int>(desc_bg.rows,-1);
//Concatenate fg and bg classes
classes = classes_bg;
classes.insert(classes.end(), classes_fg.begin(), classes_fg.end());
//Create descriptor matcher
bfmatcher = DescriptorMatcher::create("BruteForce-Hamming");
FILE_LOG(logDEBUG) << "Matcher::initialize() return";
}
void Matcher::matchGlobal(const vector<KeyPoint> & keypoints, const Mat descriptors,
vector<Point2f> & points_matched, vector<int> & classes_matched)
{
FILE_LOG(logDEBUG) << "Matcher::matchGlobal() call";
if (keypoints.size() == 0)
{
FILE_LOG(logDEBUG) << "Matcher::matchGlobal() return";
return;
}
vector<vector<DMatch> > matches;
bfmatcher->knnMatch(descriptors, database, matches, 2);
for (size_t i = 0; i < matches.size(); i++)
{
vector<DMatch> m = matches[i];
float distance1 = m[0].distance / desc_length;
float distance2 = m[1].distance / desc_length;
int matched_class = classes[m[0].trainIdx];
if (matched_class == -1) continue;
if (distance1 > thr_dist) continue;
if (distance1/distance2 > thr_ratio) continue;
points_matched.push_back(keypoints[i].pt);
classes_matched.push_back(matched_class);
}
FILE_LOG(logDEBUG) << "Matcher::matchGlobal() return";
}
void Matcher::matchLocal(const vector<KeyPoint> & keypoints, const Mat descriptors,
const Point2f center, const float scale, const float rotation,
vector<Point2f> & points_matched, vector<int> & classes_matched)
{
FILE_LOG(logDEBUG) << "Matcher::matchLocal() call";
if (keypoints.size() == 0) {
FILE_LOG(logDEBUG) << "Matcher::matchLocal() return";
return;
}
//Transform initial points
vector<Point2f> pts_fg_trans;
pts_fg_trans.reserve(pts_fg_norm.size());
for (size_t i = 0; i < pts_fg_norm.size(); i++)
{
pts_fg_trans.push_back(scale * rotate(pts_fg_norm[i], -rotation));
}
//Perform local matching
for (size_t i = 0; i < keypoints.size(); i++)
{
Point2f location_rel = keypoints[i].pt - center;
//Find potential indices for matching
vector<int> indices_potential;
for (size_t j = 0; j < pts_fg_trans.size(); j++)
{
float l2norm = norm(pts_fg_trans[j] - location_rel);
if (l2norm < thr_cutoff) {
indices_potential.push_back(num_bg_points + j);
}
}
//Build descriptor matrix and classes from potential indices
Mat database_potential = Mat(indices_potential.size(), database.cols, database.type());
for (size_t j = 0; j < indices_potential.size(); j++) {
database.row(indices_potential[j]).copyTo(database_potential.row(j));
}
//Find distances between descriptors
vector<vector<DMatch> > matches;
bfmatcher->knnMatch(database_potential, descriptors.row(i), matches, 2);
//Perform matching
for (size_t j = 0; j < matches.size(); j++)
{
vector<DMatch> m = matches[j];
float distance1 = m[0].distance / desc_length;
//TODO: Check the following line for correctness
float distance2 = m.size() > 1 ? m[1].distance / desc_length : 1;
int matched_class = classes[indices_potential[m[0].queryIdx]];
if (distance1 > thr_dist) continue;
if (distance1/distance2 > thr_ratio) continue;
points_matched.push_back(keypoints[i].pt);
classes_matched.push_back(matched_class);
}
}
FILE_LOG(logDEBUG) << "Matcher::matchLocal() return";
}
} /* namespace CMT */
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright(c) 2016, Jeff Hutchinson
// 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 threadGL nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include <stdio.h>
#include "jbl/types.h"
#include "jbl/list.h"
S32 main(S32 argc, const char **argv)
{
List<S32> list;
for (S32 i = 0; i < 20; ++i)
{
list.add(i * i);
}
for (S32 i : list)
{
printf("%d\n", i);
}
printf("Remove 4...\n");
list.remove(4);
for (S32 i : list)
{
printf("%d\n", i);
}
#ifdef _WIN32
system("pause");
#endif
return 0;
}<commit_msg>cleanup and remove list<commit_after><|endoftext|> |
<commit_before>// wake.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "wake.h"
NAMESPACE_BEGIN(CryptoPP)
void WAKE_TestInstantiations()
{
WAKE_OFB<>::Encryption x2;
WAKE_OFB<>::Decryption x4;
}
inline word32 WAKE_Base::M(word32 x, word32 y)
{
word32 w = x+y;
return (w>>8) ^ t[w & 0xff];
}
void WAKE_Base::GenKey(word32 k0, word32 k1, word32 k2, word32 k3)
{
// this code is mostly copied from David Wheeler's paper "A Bulk Data Encryption Algorithm"
signed int x, z, p;
// x and z were declared as "long" in Wheeler's paper, which is a signed type. I don't know if that was intentional, but it's too late to change it now. -- Wei 7/4/2010
CRYPTOPP_COMPILE_ASSERT(sizeof(x) == 4);
static int tt[10]= {
(int)0x726a8f3b, // table
(int)0xe69a3b5c,
(int)0xd3c71fe5,
(int)0xab3c73d2,
(int)0x4d3a8eb3,
(int)0x0396d6e8,
(int)0x3d4c2f7a,
(int)0x9ee27cf3, } ;
t[0] = k0;
t[1] = k1;
t[2] = k2;
t[3] = k3;
for (p=4 ; p<256 ; p++)
{
x=t[p-4]+t[p-1] ; // fill t
t[p]= (x>>3) ^ tt[x&7] ;
}
for (p=0 ; p<23 ; p++)
t[p]+=t[p+89] ; // mix first entries
x=t[33] ; z=t[59] | 0x01000001 ;
z=z&0xff7fffff ;
for (p=0 ; p<256 ; p++) { //change top byte to
x=(x&0xff7fffff)+z ; // a permutation etc
t[p]=(t[p] & 0x00ffffff) ^ x ; }
t[256]=t[0] ;
byte y=byte(x);
for (p=0 ; p<256 ; p++) { // further change perm.
t[p]=t[y=byte(t[p^y]^y)] ; // and other digits
t[y]=t[p+1] ; }
}
template <class B>
void WAKE_Policy<B>::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length)
{
word32 k0, k1, k2, k3;
BlockGetAndPut<word32, BigEndian>::Get(key)(r3)(r4)(r5)(r6)(k0)(k1)(k2)(k3);
GenKey(k0, k1, k2, k3);
}
// OFB
template <class B>
void WAKE_Policy<B>::OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)
{
#define WAKE_OUTPUT(x)\
while (iterationCount--)\
{\
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, B::ToEnum(), 0, r6);\
r3 = M(r3, r6);\
r4 = M(r4, r3);\
r5 = M(r5, r4);\
r6 = M(r6, r5);\
output += 4;\
if (!(x & INPUT_NULL))\
input += 4;\
}
typedef word32 WordType;
CRYPTOPP_KEYSTREAM_OUTPUT_SWITCH(WAKE_OUTPUT, 0);
}
/*
template <class B>
void WAKE_ROFB_Policy<B>::Iterate(KeystreamOperation operation, byte *output, const byte *input, unsigned int iterationCount)
{
KeystreamOutput<B> keystreamOperation(operation, output, input);
while (iterationCount--)
{
keystreamOperation(r6);
r3 = M(r3, r6);
r4 = M(r4, r3);
r5 = M(r5, r4);
r6 = M(r6, r5);
}
}
*/
template class WAKE_Policy<BigEndian>;
template class WAKE_Policy<LittleEndian>;
//template class WAKE_ROFB_Policy<BigEndian>;
//template class WAKE_ROFB_Policy<LittleEndian>;
NAMESPACE_END
<commit_msg>Using word32 for bitfied manimulation instead of mixing signed and unsigned.<commit_after>// wake.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "wake.h"
NAMESPACE_BEGIN(CryptoPP)
void WAKE_TestInstantiations()
{
WAKE_OFB<>::Encryption x2;
WAKE_OFB<>::Decryption x4;
}
inline word32 WAKE_Base::M(word32 x, word32 y)
{
word32 w = x+y;
return (w>>8) ^ t[w & 0xff];
}
void WAKE_Base::GenKey(word32 k0, word32 k1, word32 k2, word32 k3)
{
// this code is mostly copied from David Wheeler's paper "A Bulk Data Encryption Algorithm"
word32 x, z, p;
// x and z were declared as "long" in Wheeler's paper, which is a signed type. I don't know if that was intentional, but it's too late to change it now. -- Wei 7/4/2010
CRYPTOPP_COMPILE_ASSERT(sizeof(x) == 4);
word32 tt[10]= {
0x726a8f3bu, // table
0xe69a3b5cu,
0xd3c71fe5u,
0xab3c73d2u,
0x4d3a8eb3u,
0x0396d6e8u,
0x3d4c2f7au,
0x9ee27cf3u, } ;
t[0] = k0;
t[1] = k1;
t[2] = k2;
t[3] = k3;
for (p=4 ; p<256 ; p++)
{
x=t[p-4]+t[p-1] ; // fill t
t[p]= (x>>3) ^ tt[x&7] ;
}
for (p=0 ; p<23 ; p++)
t[p]+=t[p+89] ; // mix first entries
x=t[33] ; z=t[59] | 0x01000001 ;
z=z&0xff7fffff ;
for (p=0 ; p<256 ; p++) { //change top byte to
x=(x&0xff7fffff)+z ; // a permutation etc
t[p]=(t[p] & 0x00ffffff) ^ x ; }
t[256]=t[0] ;
byte y=byte(x);
for (p=0 ; p<256 ; p++) { // further change perm.
t[p]=t[y=byte(t[p^y]^y)] ; // and other digits
t[y]=t[p+1] ; }
}
template <class B>
void WAKE_Policy<B>::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length)
{
word32 k0, k1, k2, k3;
BlockGetAndPut<word32, BigEndian>::Get(key)(r3)(r4)(r5)(r6)(k0)(k1)(k2)(k3);
GenKey(k0, k1, k2, k3);
}
// OFB
template <class B>
void WAKE_Policy<B>::OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount)
{
#define WAKE_OUTPUT(x)\
while (iterationCount--)\
{\
CRYPTOPP_KEYSTREAM_OUTPUT_WORD(x, B::ToEnum(), 0, r6);\
r3 = M(r3, r6);\
r4 = M(r4, r3);\
r5 = M(r5, r4);\
r6 = M(r6, r5);\
output += 4;\
if (!(x & INPUT_NULL))\
input += 4;\
}
typedef word32 WordType;
CRYPTOPP_KEYSTREAM_OUTPUT_SWITCH(WAKE_OUTPUT, 0);
}
/*
template <class B>
void WAKE_ROFB_Policy<B>::Iterate(KeystreamOperation operation, byte *output, const byte *input, unsigned int iterationCount)
{
KeystreamOutput<B> keystreamOperation(operation, output, input);
while (iterationCount--)
{
keystreamOperation(r6);
r3 = M(r3, r6);
r4 = M(r4, r3);
r5 = M(r5, r4);
r6 = M(r6, r5);
}
}
*/
template class WAKE_Policy<BigEndian>;
template class WAKE_Policy<LittleEndian>;
//template class WAKE_ROFB_Policy<BigEndian>;
//template class WAKE_ROFB_Policy<LittleEndian>;
NAMESPACE_END
<|endoftext|> |
<commit_before>//===- Dominators.cpp - Dominator Calculation -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators. Postdominators are available in libanalysis, but are not
// included in libvmcore, because it's not needed. Forward dominators are
// needed to support the Verifier pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Dominators.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GenericDomTreeConstruction.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
// Always verify dominfo if expensive checking is enabled.
#ifdef XDEBUG
static bool VerifyDomInfo = true;
#else
static bool VerifyDomInfo = false;
#endif
static cl::opt<bool,true>
VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
cl::desc("Verify dominator info (time consuming)"));
bool BasicBlockEdge::isSingleEdge() const {
const TerminatorInst *TI = Start->getTerminator();
unsigned NumEdgesToEnd = 0;
for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
if (TI->getSuccessor(i) == End)
++NumEdgesToEnd;
if (NumEdgesToEnd >= 2)
return false;
}
assert(NumEdgesToEnd == 1);
return true;
}
//===----------------------------------------------------------------------===//
// DominatorTree Implementation
//===----------------------------------------------------------------------===//
//
// Provide public access to DominatorTree information. Implementation details
// can be found in Dominators.h, GenericDomTree.h, and
// GenericDomTreeConstruction.h.
//
//===----------------------------------------------------------------------===//
TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
#define LLVM_COMMA ,
TEMPLATE_INSTANTIATION(void llvm::Calculate<Function LLVM_COMMA BasicBlock *>(
DominatorTreeBase<typename GraphTraits<BasicBlock *>::NodeType> &DT
LLVM_COMMA Function &F));
TEMPLATE_INSTANTIATION(void llvm::Calculate<
Function LLVM_COMMA Inverse<BasicBlock *> >(DominatorTreeBase<
typename GraphTraits<Inverse<BasicBlock *> >::NodeType> &DT LLVM_COMMA
Function &F));
#undef LLVM_COMMA
// dominates - Return true if Def dominates a use in User. This performs
// the special checks necessary if Def and User are in the same basic block.
// Note that Def doesn't dominate a use in Def itself!
bool DominatorTree::dominates(const Instruction *Def,
const Instruction *User) const {
const BasicBlock *UseBB = User->getParent();
const BasicBlock *DefBB = Def->getParent();
// Any unreachable use is dominated, even if Def == User.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
// An instruction doesn't dominate a use in itself.
if (Def == User)
return false;
// The value defined by an invoke dominates an instruction only if
// it dominates every instruction in UseBB.
// A PHI is dominated only if the instruction dominates every possible use
// in the UseBB.
if (isa<InvokeInst>(Def) || isa<PHINode>(User))
return dominates(Def, UseBB);
if (DefBB != UseBB)
return dominates(DefBB, UseBB);
// Loop through the basic block until we find Def or User.
BasicBlock::const_iterator I = DefBB->begin();
for (; &*I != Def && &*I != User; ++I)
/*empty*/;
return &*I == Def;
}
// true if Def would dominate a use in any instruction in UseBB.
// note that dominates(Def, Def->getParent()) is false.
bool DominatorTree::dominates(const Instruction *Def,
const BasicBlock *UseBB) const {
const BasicBlock *DefBB = Def->getParent();
// Any unreachable use is dominated, even if DefBB == UseBB.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
if (DefBB == UseBB)
return false;
const InvokeInst *II = dyn_cast<InvokeInst>(Def);
if (!II)
return dominates(DefBB, UseBB);
// Invoke results are only usable in the normal destination, not in the
// exceptional destination.
BasicBlock *NormalDest = II->getNormalDest();
BasicBlockEdge E(DefBB, NormalDest);
return dominates(E, UseBB);
}
bool DominatorTree::dominates(const BasicBlockEdge &BBE,
const BasicBlock *UseBB) const {
// Assert that we have a single edge. We could handle them by simply
// returning false, but since isSingleEdge is linear on the number of
// edges, the callers can normally handle them more efficiently.
assert(BBE.isSingleEdge());
// If the BB the edge ends in doesn't dominate the use BB, then the
// edge also doesn't.
const BasicBlock *Start = BBE.getStart();
const BasicBlock *End = BBE.getEnd();
if (!dominates(End, UseBB))
return false;
// Simple case: if the end BB has a single predecessor, the fact that it
// dominates the use block implies that the edge also does.
if (End->getSinglePredecessor())
return true;
// The normal edge from the invoke is critical. Conceptually, what we would
// like to do is split it and check if the new block dominates the use.
// With X being the new block, the graph would look like:
//
// DefBB
// /\ . .
// / \ . .
// / \ . .
// / \ | |
// A X B C
// | \ | /
// . \|/
// . NormalDest
// .
//
// Given the definition of dominance, NormalDest is dominated by X iff X
// dominates all of NormalDest's predecessors (X, B, C in the example). X
// trivially dominates itself, so we only have to find if it dominates the
// other predecessors. Since the only way out of X is via NormalDest, X can
// only properly dominate a node if NormalDest dominates that node too.
for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
PI != E; ++PI) {
const BasicBlock *BB = *PI;
if (BB == Start)
continue;
if (!dominates(End, BB))
return false;
}
return true;
}
bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
// Assert that we have a single edge. We could handle them by simply
// returning false, but since isSingleEdge is linear on the number of
// edges, the callers can normally handle them more efficiently.
assert(BBE.isSingleEdge());
Instruction *UserInst = cast<Instruction>(U.getUser());
// A PHI in the end of the edge is dominated by it.
PHINode *PN = dyn_cast<PHINode>(UserInst);
if (PN && PN->getParent() == BBE.getEnd() &&
PN->getIncomingBlock(U) == BBE.getStart())
return true;
// Otherwise use the edge-dominates-block query, which
// handles the crazy critical edge cases properly.
const BasicBlock *UseBB;
if (PN)
UseBB = PN->getIncomingBlock(U);
else
UseBB = UserInst->getParent();
return dominates(BBE, UseBB);
}
bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
Instruction *UserInst = cast<Instruction>(U.getUser());
const BasicBlock *DefBB = Def->getParent();
// Determine the block in which the use happens. PHI nodes use
// their operands on edges; simulate this by thinking of the use
// happening at the end of the predecessor block.
const BasicBlock *UseBB;
if (PHINode *PN = dyn_cast<PHINode>(UserInst))
UseBB = PN->getIncomingBlock(U);
else
UseBB = UserInst->getParent();
// Any unreachable use is dominated, even if Def == User.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
// Invoke instructions define their return values on the edges
// to their normal successors, so we have to handle them specially.
// Among other things, this means they don't dominate anything in
// their own block, except possibly a phi, so we don't need to
// walk the block in any case.
if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
BasicBlock *NormalDest = II->getNormalDest();
BasicBlockEdge E(DefBB, NormalDest);
return dominates(E, U);
}
// If the def and use are in different blocks, do a simple CFG dominator
// tree query.
if (DefBB != UseBB)
return dominates(DefBB, UseBB);
// Ok, def and use are in the same block. If the def is an invoke, it
// doesn't dominate anything in the block. If it's a PHI, it dominates
// everything in the block.
if (isa<PHINode>(UserInst))
return true;
// Otherwise, just loop through the basic block until we find Def or User.
BasicBlock::const_iterator I = DefBB->begin();
for (; &*I != Def && &*I != UserInst; ++I)
/*empty*/;
return &*I != UserInst;
}
bool DominatorTree::isReachableFromEntry(const Use &U) const {
Instruction *I = dyn_cast<Instruction>(U.getUser());
// ConstantExprs aren't really reachable from the entry block, but they
// don't need to be treated like unreachable code either.
if (!I) return true;
// PHI nodes use their operands on their incoming edges.
if (PHINode *PN = dyn_cast<PHINode>(I))
return isReachableFromEntry(PN->getIncomingBlock(U));
// Everything else uses their operands in their own block.
return isReachableFromEntry(I->getParent());
}
void DominatorTree::verifyDomTree() const {
if (!VerifyDomInfo)
return;
Function &F = *getRoot()->getParent();
DominatorTree OtherDT;
OtherDT.recalculate(F);
if (compare(OtherDT)) {
errs() << "DominatorTree is not up to date!\nComputed:\n";
print(errs());
errs() << "\nActual:\n";
OtherDT.print(errs());
abort();
}
}
//===----------------------------------------------------------------------===//
// DominatorTreeWrapperPass Implementation
//===----------------------------------------------------------------------===//
//
// The implementation details of the wrapper pass that holds a DominatorTree.
//
//===----------------------------------------------------------------------===//
char DominatorTreeWrapperPass::ID = 0;
INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
"Dominator Tree Construction", true, true)
bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
DT.recalculate(F);
return false;
}
void DominatorTreeWrapperPass::verifyAnalysis() const { DT.verifyDomTree(); }
void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
DT.print(OS);
}
<commit_msg>Remove unnecessary typename.<commit_after>//===- Dominators.cpp - Dominator Calculation -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators. Postdominators are available in libanalysis, but are not
// included in libvmcore, because it's not needed. Forward dominators are
// needed to support the Verifier pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Dominators.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GenericDomTreeConstruction.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
// Always verify dominfo if expensive checking is enabled.
#ifdef XDEBUG
static bool VerifyDomInfo = true;
#else
static bool VerifyDomInfo = false;
#endif
static cl::opt<bool,true>
VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
cl::desc("Verify dominator info (time consuming)"));
bool BasicBlockEdge::isSingleEdge() const {
const TerminatorInst *TI = Start->getTerminator();
unsigned NumEdgesToEnd = 0;
for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
if (TI->getSuccessor(i) == End)
++NumEdgesToEnd;
if (NumEdgesToEnd >= 2)
return false;
}
assert(NumEdgesToEnd == 1);
return true;
}
//===----------------------------------------------------------------------===//
// DominatorTree Implementation
//===----------------------------------------------------------------------===//
//
// Provide public access to DominatorTree information. Implementation details
// can be found in Dominators.h, GenericDomTree.h, and
// GenericDomTreeConstruction.h.
//
//===----------------------------------------------------------------------===//
TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
#define LLVM_COMMA ,
TEMPLATE_INSTANTIATION(void llvm::Calculate<Function LLVM_COMMA BasicBlock *>(
DominatorTreeBase<GraphTraits<BasicBlock *>::NodeType> &DT LLVM_COMMA
Function &F));
TEMPLATE_INSTANTIATION(
void llvm::Calculate<Function LLVM_COMMA Inverse<BasicBlock *> >(
DominatorTreeBase<GraphTraits<Inverse<BasicBlock *> >::NodeType> &DT
LLVM_COMMA Function &F));
#undef LLVM_COMMA
// dominates - Return true if Def dominates a use in User. This performs
// the special checks necessary if Def and User are in the same basic block.
// Note that Def doesn't dominate a use in Def itself!
bool DominatorTree::dominates(const Instruction *Def,
const Instruction *User) const {
const BasicBlock *UseBB = User->getParent();
const BasicBlock *DefBB = Def->getParent();
// Any unreachable use is dominated, even if Def == User.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
// An instruction doesn't dominate a use in itself.
if (Def == User)
return false;
// The value defined by an invoke dominates an instruction only if
// it dominates every instruction in UseBB.
// A PHI is dominated only if the instruction dominates every possible use
// in the UseBB.
if (isa<InvokeInst>(Def) || isa<PHINode>(User))
return dominates(Def, UseBB);
if (DefBB != UseBB)
return dominates(DefBB, UseBB);
// Loop through the basic block until we find Def or User.
BasicBlock::const_iterator I = DefBB->begin();
for (; &*I != Def && &*I != User; ++I)
/*empty*/;
return &*I == Def;
}
// true if Def would dominate a use in any instruction in UseBB.
// note that dominates(Def, Def->getParent()) is false.
bool DominatorTree::dominates(const Instruction *Def,
const BasicBlock *UseBB) const {
const BasicBlock *DefBB = Def->getParent();
// Any unreachable use is dominated, even if DefBB == UseBB.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
if (DefBB == UseBB)
return false;
const InvokeInst *II = dyn_cast<InvokeInst>(Def);
if (!II)
return dominates(DefBB, UseBB);
// Invoke results are only usable in the normal destination, not in the
// exceptional destination.
BasicBlock *NormalDest = II->getNormalDest();
BasicBlockEdge E(DefBB, NormalDest);
return dominates(E, UseBB);
}
bool DominatorTree::dominates(const BasicBlockEdge &BBE,
const BasicBlock *UseBB) const {
// Assert that we have a single edge. We could handle them by simply
// returning false, but since isSingleEdge is linear on the number of
// edges, the callers can normally handle them more efficiently.
assert(BBE.isSingleEdge());
// If the BB the edge ends in doesn't dominate the use BB, then the
// edge also doesn't.
const BasicBlock *Start = BBE.getStart();
const BasicBlock *End = BBE.getEnd();
if (!dominates(End, UseBB))
return false;
// Simple case: if the end BB has a single predecessor, the fact that it
// dominates the use block implies that the edge also does.
if (End->getSinglePredecessor())
return true;
// The normal edge from the invoke is critical. Conceptually, what we would
// like to do is split it and check if the new block dominates the use.
// With X being the new block, the graph would look like:
//
// DefBB
// /\ . .
// / \ . .
// / \ . .
// / \ | |
// A X B C
// | \ | /
// . \|/
// . NormalDest
// .
//
// Given the definition of dominance, NormalDest is dominated by X iff X
// dominates all of NormalDest's predecessors (X, B, C in the example). X
// trivially dominates itself, so we only have to find if it dominates the
// other predecessors. Since the only way out of X is via NormalDest, X can
// only properly dominate a node if NormalDest dominates that node too.
for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
PI != E; ++PI) {
const BasicBlock *BB = *PI;
if (BB == Start)
continue;
if (!dominates(End, BB))
return false;
}
return true;
}
bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
// Assert that we have a single edge. We could handle them by simply
// returning false, but since isSingleEdge is linear on the number of
// edges, the callers can normally handle them more efficiently.
assert(BBE.isSingleEdge());
Instruction *UserInst = cast<Instruction>(U.getUser());
// A PHI in the end of the edge is dominated by it.
PHINode *PN = dyn_cast<PHINode>(UserInst);
if (PN && PN->getParent() == BBE.getEnd() &&
PN->getIncomingBlock(U) == BBE.getStart())
return true;
// Otherwise use the edge-dominates-block query, which
// handles the crazy critical edge cases properly.
const BasicBlock *UseBB;
if (PN)
UseBB = PN->getIncomingBlock(U);
else
UseBB = UserInst->getParent();
return dominates(BBE, UseBB);
}
bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
Instruction *UserInst = cast<Instruction>(U.getUser());
const BasicBlock *DefBB = Def->getParent();
// Determine the block in which the use happens. PHI nodes use
// their operands on edges; simulate this by thinking of the use
// happening at the end of the predecessor block.
const BasicBlock *UseBB;
if (PHINode *PN = dyn_cast<PHINode>(UserInst))
UseBB = PN->getIncomingBlock(U);
else
UseBB = UserInst->getParent();
// Any unreachable use is dominated, even if Def == User.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
// Invoke instructions define their return values on the edges
// to their normal successors, so we have to handle them specially.
// Among other things, this means they don't dominate anything in
// their own block, except possibly a phi, so we don't need to
// walk the block in any case.
if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
BasicBlock *NormalDest = II->getNormalDest();
BasicBlockEdge E(DefBB, NormalDest);
return dominates(E, U);
}
// If the def and use are in different blocks, do a simple CFG dominator
// tree query.
if (DefBB != UseBB)
return dominates(DefBB, UseBB);
// Ok, def and use are in the same block. If the def is an invoke, it
// doesn't dominate anything in the block. If it's a PHI, it dominates
// everything in the block.
if (isa<PHINode>(UserInst))
return true;
// Otherwise, just loop through the basic block until we find Def or User.
BasicBlock::const_iterator I = DefBB->begin();
for (; &*I != Def && &*I != UserInst; ++I)
/*empty*/;
return &*I != UserInst;
}
bool DominatorTree::isReachableFromEntry(const Use &U) const {
Instruction *I = dyn_cast<Instruction>(U.getUser());
// ConstantExprs aren't really reachable from the entry block, but they
// don't need to be treated like unreachable code either.
if (!I) return true;
// PHI nodes use their operands on their incoming edges.
if (PHINode *PN = dyn_cast<PHINode>(I))
return isReachableFromEntry(PN->getIncomingBlock(U));
// Everything else uses their operands in their own block.
return isReachableFromEntry(I->getParent());
}
void DominatorTree::verifyDomTree() const {
if (!VerifyDomInfo)
return;
Function &F = *getRoot()->getParent();
DominatorTree OtherDT;
OtherDT.recalculate(F);
if (compare(OtherDT)) {
errs() << "DominatorTree is not up to date!\nComputed:\n";
print(errs());
errs() << "\nActual:\n";
OtherDT.print(errs());
abort();
}
}
//===----------------------------------------------------------------------===//
// DominatorTreeWrapperPass Implementation
//===----------------------------------------------------------------------===//
//
// The implementation details of the wrapper pass that holds a DominatorTree.
//
//===----------------------------------------------------------------------===//
char DominatorTreeWrapperPass::ID = 0;
INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
"Dominator Tree Construction", true, true)
bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
DT.recalculate(F);
return false;
}
void DominatorTreeWrapperPass::verifyAnalysis() const { DT.verifyDomTree(); }
void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
DT.print(OS);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/win/src/process_mitigations.h"
#include "base/win/windows_version.h"
#include "sandbox/win/src/nt_internals.h"
#include "sandbox/win/src/sandbox_utils.h"
#include "sandbox/win/src/win_utils.h"
namespace {
// Functions for enabling policies.
typedef BOOL (WINAPI *SetProcessDEPPolicyFunction)(DWORD dwFlags);
typedef BOOL (WINAPI *SetProcessMitigationPolicyFunction)(
PROCESS_MITIGATION_POLICY mitigation_policy,
PVOID buffer,
SIZE_T length);
typedef BOOL (WINAPI *SetDefaultDllDirectoriesFunction)(
DWORD DirectoryFlags);
} // namespace
namespace sandbox {
bool ApplyProcessMitigationsToCurrentProcess(MitigationFlags flags) {
if (!CanSetProcessMitigationsPostStartup(flags))
return false;
// We can't apply anything before Win XP, so just return cleanly.
if (!IsXPSP2OrLater())
return true;
HMODULE module = ::GetModuleHandleA("kernel32.dll");
if (flags & MITIGATION_DLL_SEARCH_ORDER) {
SetDefaultDllDirectoriesFunction set_default_dll_directories =
reinterpret_cast<SetDefaultDllDirectoriesFunction>(
::GetProcAddress(module, "SetDefaultDllDirectories"));
// Check for SetDefaultDllDirectories since it requires KB2533623.
if (set_default_dll_directories) {
if (!set_default_dll_directories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS))
return false;
}
}
// Set the heap to terminate on corruption
if (flags & MITIGATION_HEAP_TERMINATE) {
if (!::HeapSetInformation(NULL, HeapEnableTerminationOnCorruption,
NULL, 0))
return false;
}
#if !defined(_WIN64) // DEP is always enabled on 64-bit.
if (flags & MITIGATION_DEP) {
DWORD dep_flags = PROCESS_DEP_ENABLE;
if (flags & MITIGATION_DEP_NO_ATL_THUNK)
dep_flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
SetProcessDEPPolicyFunction set_process_dep_policy =
reinterpret_cast<SetProcessDEPPolicyFunction>(
::GetProcAddress(module, "SetProcessDEPPolicy"));
if (set_process_dep_policy) {
if (!set_process_dep_policy(dep_flags) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
} else {
// We're on XP sp2, so use the less standard approach.
// For reference: http://www.uninformed.org/?v=2&a=4
const int MEM_EXECUTE_OPTION_ENABLE = 1;
const int MEM_EXECUTE_OPTION_DISABLE = 2;
const int MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION = 4;
const int MEM_EXECUTE_OPTION_PERMANENT = 8;
NtSetInformationProcessFunction set_information_process = NULL;
ResolveNTFunctionPtr("NtSetInformationProcess",
&set_information_process);
if (!set_information_process)
return false;
ULONG dep = MEM_EXECUTE_OPTION_DISABLE | MEM_EXECUTE_OPTION_PERMANENT;
if (!(dep_flags & PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION))
dep |= MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION;
if (!SUCCEEDED(set_information_process(GetCurrentProcess(),
ProcessExecuteFlags,
&dep, sizeof(dep))) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
}
#endif
// This is all we can do in Win7 and below.
base::win::Version version = base::win::GetVersion();
if (version < base::win::VERSION_WIN8)
return true;
SetProcessMitigationPolicyFunction set_process_mitigation_policy =
reinterpret_cast<SetProcessMitigationPolicyFunction>(
::GetProcAddress(module, "SetProcessMitigationPolicy"));
if (!set_process_mitigation_policy)
return false;
// Enable ASLR policies.
if (flags & MITIGATION_RELOCATE_IMAGE) {
PROCESS_MITIGATION_ASLR_POLICY policy = { 0 };
policy.EnableForceRelocateImages = true;
policy.DisallowStrippedImages = (flags &
MITIGATION_RELOCATE_IMAGE_REQUIRED) ==
MITIGATION_RELOCATE_IMAGE_REQUIRED;
if (!set_process_mitigation_policy(ProcessASLRPolicy, &policy,
sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
// Enable strict handle policies.
if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {
PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY policy = { 0 };
policy.HandleExceptionsPermanentlyEnabled =
policy.RaiseExceptionOnInvalidHandleReference = true;
if (!set_process_mitigation_policy(ProcessStrictHandleCheckPolicy, &policy,
sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
// Enable system call policies.
if (flags & MITIGATION_WIN32K_DISABLE) {
PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy = { 0 };
policy.DisallowWin32kSystemCalls = true;
if (!set_process_mitigation_policy(ProcessSystemCallDisablePolicy, &policy,
sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
// Enable system call policies.
if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {
PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY policy = { 0 };
policy.DisableExtensionPoints = true;
if (!set_process_mitigation_policy(ProcessExtensionPointDisablePolicy,
&policy, sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
return true;
}
void ConvertProcessMitigationsToPolicy(MitigationFlags flags,
DWORD64* policy_flags, size_t* size) {
base::win::Version version = base::win::GetVersion();
*policy_flags = 0;
#if defined(_WIN64)
*size = sizeof(*policy_flags);
#elif defined(_M_IX86)
// A 64-bit flags attribute is illegal on 32-bit Win 7 and below.
if (version < base::win::VERSION_WIN8)
*size = sizeof(DWORD);
else
*size = sizeof(*policy_flags);
#else
#error This platform is not supported.
#endif
// Nothing for Win XP or Vista.
if (version <= base::win::VERSION_VISTA)
return;
if (flags & MITIGATION_DEP) {
*policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE;
if (!(flags & MITIGATION_DEP_NO_ATL_THUNK))
*policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE;
}
if (flags & MITIGATION_SEHOP)
*policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE;
// Win 7
if (version < base::win::VERSION_WIN8)
return;
if (flags & MITIGATION_RELOCATE_IMAGE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON;
if (flags & MITIGATION_RELOCATE_IMAGE_REQUIRED) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS;
}
}
if (flags & MITIGATION_HEAP_TERMINATE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON;
}
if (flags & MITIGATION_BOTTOM_UP_ASLR) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON;
}
if (flags & MITIGATION_HIGH_ENTROPY_ASLR) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON;
}
if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON;
}
if (flags & MITIGATION_WIN32K_DISABLE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON;
}
if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON;
}
}
MitigationFlags FilterPostStartupProcessMitigations(MitigationFlags flags) {
// Anything prior to XP SP2.
if (!IsXPSP2OrLater())
return 0;
base::win::Version version = base::win::GetVersion();
// Windows XP SP2+.
if (version < base::win::VERSION_VISTA) {
return flags & (MITIGATION_DEP |
MITIGATION_DEP_NO_ATL_THUNK);
// Windows Vista
if (version < base::win::VERSION_WIN7) {
return flags & (MITIGATION_DEP |
MITIGATION_DEP_NO_ATL_THUNK |
MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_DLL_SEARCH_ORDER |
MITIGATION_HEAP_TERMINATE);
}
// Windows 7 and Vista.
} else if (version < base::win::VERSION_WIN8) {
return flags & (MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_DLL_SEARCH_ORDER |
MITIGATION_HEAP_TERMINATE);
}
// Windows 8 and above.
return flags & (MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_DLL_SEARCH_ORDER);
}
bool ApplyProcessMitigationsToSuspendedProcess(HANDLE process,
MitigationFlags flags) {
// This is a hack to fake a weak bottom-up ASLR on 32-bit Windows.
#if !defined(_WIN64)
if (flags & MITIGATION_BOTTOM_UP_ASLR) {
unsigned int limit;
rand_s(&limit);
char* ptr = 0;
const size_t kMask64k = 0xFFFF;
// Random range (512k-16.5mb) in 64k steps.
const char* end = ptr + ((((limit % 16384) + 512) * 1024) & ~kMask64k);
while (ptr < end) {
MEMORY_BASIC_INFORMATION memory_info;
if (!::VirtualQueryEx(process, ptr, &memory_info, sizeof(memory_info)))
break;
size_t size = std::min((memory_info.RegionSize + kMask64k) & ~kMask64k,
static_cast<SIZE_T>(end - ptr));
if (ptr && memory_info.State == MEM_FREE)
::VirtualAllocEx(process, ptr, size, MEM_RESERVE, PAGE_NOACCESS);
ptr += size;
}
}
#endif
return true;
}
bool CanSetProcessMitigationsPostStartup(MitigationFlags flags) {
// All of these mitigations can be enabled after startup.
return !(flags & ~(MITIGATION_HEAP_TERMINATE |
MITIGATION_DEP |
MITIGATION_DEP_NO_ATL_THUNK |
MITIGATION_RELOCATE_IMAGE |
MITIGATION_RELOCATE_IMAGE_REQUIRED |
MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_STRICT_HANDLE_CHECKS |
MITIGATION_WIN32K_DISABLE |
MITIGATION_EXTENSION_DLL_DISABLE |
MITIGATION_DLL_SEARCH_ORDER));
}
bool CanSetProcessMitigationsPreStartup(MitigationFlags flags) {
// These mitigations cannot be enabled prior to startup.
return !(flags & (MITIGATION_STRICT_HANDLE_CHECKS |
MITIGATION_WIN32K_DISABLE |
MITIGATION_DLL_SEARCH_ORDER));
}
} // namespace sandbox
<commit_msg>Fix compilation error on Windows<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/win/src/process_mitigations.h"
#include "base/win/windows_version.h"
#include "sandbox/win/src/nt_internals.h"
#include "sandbox/win/src/sandbox_utils.h"
#include "sandbox/win/src/win_utils.h"
namespace {
// Functions for enabling policies.
typedef BOOL (WINAPI *SetProcessDEPPolicyFunction)(DWORD dwFlags);
typedef BOOL (WINAPI *SetProcessMitigationPolicyFunction)(
PROCESS_MITIGATION_POLICY mitigation_policy,
PVOID buffer,
SIZE_T length);
typedef BOOL (WINAPI *SetDefaultDllDirectoriesFunction)(
DWORD DirectoryFlags);
} // namespace
namespace sandbox {
bool ApplyProcessMitigationsToCurrentProcess(MitigationFlags flags) {
if (!CanSetProcessMitigationsPostStartup(flags))
return false;
// We can't apply anything before Win XP, so just return cleanly.
if (!IsXPSP2OrLater())
return true;
HMODULE module = ::GetModuleHandleA("kernel32.dll");
if (flags & MITIGATION_DLL_SEARCH_ORDER) {
SetDefaultDllDirectoriesFunction set_default_dll_directories =
reinterpret_cast<SetDefaultDllDirectoriesFunction>(
::GetProcAddress(module, "SetDefaultDllDirectories"));
// Check for SetDefaultDllDirectories since it requires KB2533623.
if (set_default_dll_directories) {
if (!set_default_dll_directories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS))
return false;
}
}
// Set the heap to terminate on corruption
if (flags & MITIGATION_HEAP_TERMINATE) {
if (!::HeapSetInformation(NULL, HeapEnableTerminationOnCorruption,
NULL, 0))
return false;
}
#if !defined(_WIN64) // DEP is always enabled on 64-bit.
if (flags & MITIGATION_DEP) {
DWORD dep_flags = PROCESS_DEP_ENABLE;
if (flags & MITIGATION_DEP_NO_ATL_THUNK)
dep_flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
SetProcessDEPPolicyFunction set_process_dep_policy =
reinterpret_cast<SetProcessDEPPolicyFunction>(
::GetProcAddress(module, "SetProcessDEPPolicy"));
if (set_process_dep_policy) {
if (!set_process_dep_policy(dep_flags) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
} else {
// We're on XP sp2, so use the less standard approach.
// For reference: http://www.uninformed.org/?v=2&a=4
const int MEM_EXECUTE_OPTION_ENABLE = 1;
const int MEM_EXECUTE_OPTION_DISABLE = 2;
const int MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION = 4;
const int MEM_EXECUTE_OPTION_PERMANENT = 8;
NtSetInformationProcessFunction set_information_process = NULL;
ResolveNTFunctionPtr("NtSetInformationProcess",
&set_information_process);
if (!set_information_process)
return false;
ULONG dep = MEM_EXECUTE_OPTION_DISABLE | MEM_EXECUTE_OPTION_PERMANENT;
if (!(dep_flags & PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION))
dep |= MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION;
if (!SUCCEEDED(set_information_process(GetCurrentProcess(),
ProcessExecuteFlags,
&dep, sizeof(dep))) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
}
#endif
// This is all we can do in Win7 and below.
base::win::Version version = base::win::GetVersion();
if (version < base::win::VERSION_WIN8)
return true;
SetProcessMitigationPolicyFunction set_process_mitigation_policy =
reinterpret_cast<SetProcessMitigationPolicyFunction>(
::GetProcAddress(module, "SetProcessMitigationPolicy"));
if (!set_process_mitigation_policy)
return false;
// Enable ASLR policies.
if (flags & MITIGATION_RELOCATE_IMAGE) {
PROCESS_MITIGATION_ASLR_POLICY policy = { 0 };
policy.EnableForceRelocateImages = true;
policy.DisallowStrippedImages = (flags &
MITIGATION_RELOCATE_IMAGE_REQUIRED) ==
MITIGATION_RELOCATE_IMAGE_REQUIRED;
if (!set_process_mitigation_policy(ProcessASLRPolicy, &policy,
sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
// Enable strict handle policies.
if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {
PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY policy = { 0 };
policy.HandleExceptionsPermanentlyEnabled =
policy.RaiseExceptionOnInvalidHandleReference = true;
if (!set_process_mitigation_policy(ProcessStrictHandleCheckPolicy, &policy,
sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
// Enable system call policies.
if (flags & MITIGATION_WIN32K_DISABLE) {
PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy = { 0 };
policy.DisallowWin32kSystemCalls = true;
if (!set_process_mitigation_policy(ProcessSystemCallDisablePolicy, &policy,
sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
// Enable system call policies.
if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {
PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY policy = { 0 };
policy.DisableExtensionPoints = true;
if (!set_process_mitigation_policy(ProcessExtensionPointDisablePolicy,
&policy, sizeof(policy)) &&
ERROR_ACCESS_DENIED != ::GetLastError()) {
return false;
}
}
return true;
}
void ConvertProcessMitigationsToPolicy(MitigationFlags flags,
DWORD64* policy_flags, size_t* size) {
base::win::Version version = base::win::GetVersion();
*policy_flags = 0;
#if defined(_WIN64)
*size = sizeof(*policy_flags);
#elif defined(_M_IX86)
// A 64-bit flags attribute is illegal on 32-bit Win 7 and below.
if (version < base::win::VERSION_WIN8)
*size = sizeof(DWORD);
else
*size = sizeof(*policy_flags);
#else
#error This platform is not supported.
#endif
// Nothing for Win XP or Vista.
if (version <= base::win::VERSION_VISTA)
return;
if (flags & MITIGATION_DEP) {
*policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE;
if (!(flags & MITIGATION_DEP_NO_ATL_THUNK))
*policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE;
}
if (flags & MITIGATION_SEHOP)
*policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE;
// Win 7
if (version < base::win::VERSION_WIN8)
return;
#if 0
if (flags & MITIGATION_RELOCATE_IMAGE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON;
if (flags & MITIGATION_RELOCATE_IMAGE_REQUIRED) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS;
}
}
if (flags & MITIGATION_HEAP_TERMINATE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON;
}
if (flags & MITIGATION_BOTTOM_UP_ASLR) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON;
}
if (flags & MITIGATION_HIGH_ENTROPY_ASLR) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON;
}
if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON;
}
if (flags & MITIGATION_WIN32K_DISABLE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON;
}
if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {
*policy_flags |=
PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON;
}
#endif
}
MitigationFlags FilterPostStartupProcessMitigations(MitigationFlags flags) {
// Anything prior to XP SP2.
if (!IsXPSP2OrLater())
return 0;
base::win::Version version = base::win::GetVersion();
// Windows XP SP2+.
if (version < base::win::VERSION_VISTA) {
return flags & (MITIGATION_DEP |
MITIGATION_DEP_NO_ATL_THUNK);
// Windows Vista
if (version < base::win::VERSION_WIN7) {
return flags & (MITIGATION_DEP |
MITIGATION_DEP_NO_ATL_THUNK |
MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_DLL_SEARCH_ORDER |
MITIGATION_HEAP_TERMINATE);
}
// Windows 7 and Vista.
} else if (version < base::win::VERSION_WIN8) {
return flags & (MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_DLL_SEARCH_ORDER |
MITIGATION_HEAP_TERMINATE);
}
// Windows 8 and above.
return flags & (MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_DLL_SEARCH_ORDER);
}
bool ApplyProcessMitigationsToSuspendedProcess(HANDLE process,
MitigationFlags flags) {
// This is a hack to fake a weak bottom-up ASLR on 32-bit Windows.
#if !defined(_WIN64)
if (flags & MITIGATION_BOTTOM_UP_ASLR) {
unsigned int limit;
rand_s(&limit);
char* ptr = 0;
const size_t kMask64k = 0xFFFF;
// Random range (512k-16.5mb) in 64k steps.
const char* end = ptr + ((((limit % 16384) + 512) * 1024) & ~kMask64k);
while (ptr < end) {
MEMORY_BASIC_INFORMATION memory_info;
if (!::VirtualQueryEx(process, ptr, &memory_info, sizeof(memory_info)))
break;
size_t size = std::min((memory_info.RegionSize + kMask64k) & ~kMask64k,
static_cast<SIZE_T>(end - ptr));
if (ptr && memory_info.State == MEM_FREE)
::VirtualAllocEx(process, ptr, size, MEM_RESERVE, PAGE_NOACCESS);
ptr += size;
}
}
#endif
return true;
}
bool CanSetProcessMitigationsPostStartup(MitigationFlags flags) {
// All of these mitigations can be enabled after startup.
return !(flags & ~(MITIGATION_HEAP_TERMINATE |
MITIGATION_DEP |
MITIGATION_DEP_NO_ATL_THUNK |
MITIGATION_RELOCATE_IMAGE |
MITIGATION_RELOCATE_IMAGE_REQUIRED |
MITIGATION_BOTTOM_UP_ASLR |
MITIGATION_STRICT_HANDLE_CHECKS |
MITIGATION_WIN32K_DISABLE |
MITIGATION_EXTENSION_DLL_DISABLE |
MITIGATION_DLL_SEARCH_ORDER));
}
bool CanSetProcessMitigationsPreStartup(MitigationFlags flags) {
// These mitigations cannot be enabled prior to startup.
return !(flags & (MITIGATION_STRICT_HANDLE_CHECKS |
MITIGATION_WIN32K_DISABLE |
MITIGATION_DLL_SEARCH_ORDER));
}
} // namespace sandbox
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#ifdef ETL_CUBLAS_MODE
#include "etl/impl/cublas/cuda.hpp"
#include "etl/impl/cublas/cublas.hpp"
#endif
/*!
* \file
* \brief Use CRTP technique to inject GPU-related functions to
* ETL value classes.
*/
namespace etl {
#ifdef ETL_CUBLAS_MODE
/*!
* \brief CRTP class to inject GPU-related functions
*
* Allocations and copy to GPU are considered const-functions,
* because the state of the expression itself is not modified. On
* the other hand, copy back from the GPU to the expression is
* non-const.
*/
template <typename T, typename D>
struct gpu_able {
using value_type = T;
using derived_t = D;
mutable impl::cuda::cuda_memory<value_type> gpu_memory_handler;
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
const derived_t& as_derived() const noexcept {
return *static_cast<const derived_t*>(this);
}
/*!
* \brief Indicates if the expression is allocated in GPU.
* \return true if the expression is allocated in GPU, false otherwise
*/
bool is_gpu_allocated() const noexcept {
return gpu_memory_handler.is_set();
}
/*!
* \brief Evict the expression from GPU.
*/
void gpu_evict() const noexcept {
gpu_memory_handler.reset();
}
/*!
* \brief Return GPU memory of this expression, if any.
* \return a pointer to the GPU memory or nullptr if not allocated in GPU.
*/
value_type* gpu_memory() const noexcept {
return gpu_memory_handler.get();
}
/*!
* \brief Allocate memory on the GPU for the expression
*/
void gpu_allocate() const {
gpu_memory_handler = impl::cuda::cuda_allocate(as_derived());
}
/*!
* \brief Allocate memory on the GPU for the expression, only if not already allocated
*/
void gpu_allocate_if_necessary() const {
if(!is_gpu_allocated()){
gpu_allocate();
}
}
/*!
* \brief Allocate memory on the GPU for the expression and copy the values into the GPU.
*/
void gpu_allocate_copy() const {
gpu_memory_handler = impl::cuda::cuda_allocate_copy(as_derived());
}
/*!
* \brief Allocate memory on the GPU for the expression and copy the values into the GPU, only if not already allocated.
*/
void gpu_allocate_copy_if_necessary() const {
if(!is_gpu_allocated()){
gpu_allocate_copy();
}
}
/*!
* \brief Reallocate the GPU memory.
* \param memory The new GPU memory (will be moved)
*/
void gpu_reallocate(impl::cuda::cuda_memory<T>&& memory){
gpu_memory_handler = std::move(memory);
}
/*!
* \brief Release the GPU memory for another expression to use
* \return A rvalue reference to the gpu_memory_handler.
*/
impl::cuda::cuda_memory<T>&& gpu_release(){
return std::move(gpu_memory_handler);
}
/*!
* \brief Copy back from the GPU to the expression memory.
*/
void gpu_copy_from(){
cpp_assert(is_gpu_allocated(), "Cannot copy from unallocated GPU memory()");
cudaMemcpy(as_derived().memory_start(), gpu_memory(), etl::size(as_derived()) * sizeof(T), cudaMemcpyDeviceToHost);
}
};
#else
template <typename T, typename D>
struct gpu_able {};
#endif //ETL_CUBLAS_MODE
} //end of namespace etl
<commit_msg>Fix gpu_release<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#ifdef ETL_CUBLAS_MODE
#include "etl/impl/cublas/cuda.hpp"
#include "etl/impl/cublas/cublas.hpp"
#endif
/*!
* \file
* \brief Use CRTP technique to inject GPU-related functions to
* ETL value classes.
*/
namespace etl {
#ifdef ETL_CUBLAS_MODE
/*!
* \brief CRTP class to inject GPU-related functions
*
* Allocations and copy to GPU are considered const-functions,
* because the state of the expression itself is not modified. On
* the other hand, copy back from the GPU to the expression is
* non-const.
*/
template <typename T, typename D>
struct gpu_able {
using value_type = T;
using derived_t = D;
mutable impl::cuda::cuda_memory<value_type> gpu_memory_handler;
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
const derived_t& as_derived() const noexcept {
return *static_cast<const derived_t*>(this);
}
/*!
* \brief Indicates if the expression is allocated in GPU.
* \return true if the expression is allocated in GPU, false otherwise
*/
bool is_gpu_allocated() const noexcept {
return gpu_memory_handler.is_set();
}
/*!
* \brief Evict the expression from GPU.
*/
void gpu_evict() const noexcept {
gpu_memory_handler.reset();
}
/*!
* \brief Return GPU memory of this expression, if any.
* \return a pointer to the GPU memory or nullptr if not allocated in GPU.
*/
value_type* gpu_memory() const noexcept {
return gpu_memory_handler.get();
}
/*!
* \brief Allocate memory on the GPU for the expression
*/
void gpu_allocate() const {
gpu_memory_handler = impl::cuda::cuda_allocate(as_derived());
}
/*!
* \brief Allocate memory on the GPU for the expression, only if not already allocated
*/
void gpu_allocate_if_necessary() const {
if(!is_gpu_allocated()){
gpu_allocate();
}
}
/*!
* \brief Allocate memory on the GPU for the expression and copy the values into the GPU.
*/
void gpu_allocate_copy() const {
gpu_memory_handler = impl::cuda::cuda_allocate_copy(as_derived());
}
/*!
* \brief Allocate memory on the GPU for the expression and copy the values into the GPU, only if not already allocated.
*/
void gpu_allocate_copy_if_necessary() const {
if(!is_gpu_allocated()){
gpu_allocate_copy();
}
}
/*!
* \brief Reallocate the GPU memory.
* \param memory The new GPU memory (will be moved)
*/
void gpu_reallocate(impl::cuda::cuda_memory<T>&& memory){
gpu_memory_handler = std::move(memory);
}
/*!
* \brief Release the GPU memory for another expression to use
* \return A rvalue reference to the gpu_memory_handler.
*/
impl::cuda::cuda_memory<T>&& gpu_release() const {
return std::move(gpu_memory_handler);
}
/*!
* \brief Copy back from the GPU to the expression memory.
*/
void gpu_copy_from(){
cpp_assert(is_gpu_allocated(), "Cannot copy from unallocated GPU memory()");
cudaMemcpy(as_derived().memory_start(), gpu_memory(), etl::size(as_derived()) * sizeof(T), cudaMemcpyDeviceToHost);
}
};
#else
template <typename T, typename D>
struct gpu_able {};
#endif //ETL_CUBLAS_MODE
} //end of namespace etl
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/impl/vec/gemm_blis.hpp" // BLIS-Like optimized kernel
// Allocations to row major
#include "etl/impl/vec/gemm_rr_to_r.hpp"
#include "etl/impl/vec/gemm_cr_to_r.hpp"
#include "etl/impl/vec/gemm_rc_to_r.hpp"
// Allocations to column major
#include "etl/impl/vec/gemm_cc_to_c.hpp"
#include "etl/impl/vec/gemm_cr_to_c.hpp"
#include "etl/impl/vec/gemm_rc_to_c.hpp"
// The idea of the GEMM kernels is largely inspired by the kernels in Blaze by
// Klaus Igleberg
namespace etl {
namespace impl {
namespace vec {
/*!
* \brief Optimized version of GEMM for row major version
*
* \param a The lhs matrix
* \param b The rhs matrix
* \param c The result matrix
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, B, C>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_rr_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Unoptimized version of GEMM for column major version
* \param a The lhs matrix
* \param b The rhs matrix
* \param c The result matrix
*/
template <typename A, typename B, typename C, cpp_enable_if((all_column_major<A, B, C>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_cc_to_c(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<B, C>::value && all_column_major<A>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_cr_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, C>::value && all_column_major<B>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_rc_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, B, C>::value))>
void gemm_tn(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::columns(a); // rows(trans(A)) = rows(C)
const size_t N = etl::columns(b); // columns (B) = columns(C)
const size_t K = etl::rows(a); // columns(trans(A)) = rows(B)
gemm_cr_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in column-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_column_major<A, B, C>::value))>
void gemm_tn(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::columns(a); // rows(trans(A)) = rows(C)
const size_t N = etl::columns(b); // columns (B) = columns(C)
const size_t K = etl::rows(a); // columns(trans(A)) = rows(B)
gemm_rc_to_c(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = A * trans(B) where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, B, C>::value))>
void gemm_nt(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::rows(b);
const size_t K = etl::columns(a);
gemm_rc_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = A * trans(B) where all matrices are
* stored in colum-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_column_major<A, B, C>::value))>
void gemm_nt(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::rows(b);
const size_t K = etl::columns(a);
gemm_cr_to_c(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
} //end of namespace vec
} //end of namespace impl
} //end of namespace etl
<commit_msg>New VEC support for mixed GEMM<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "etl/impl/vec/gemm_blis.hpp" // BLIS-Like optimized kernel
// Allocations to row major
#include "etl/impl/vec/gemm_rr_to_r.hpp"
#include "etl/impl/vec/gemm_cr_to_r.hpp"
#include "etl/impl/vec/gemm_rc_to_r.hpp"
// Allocations to column major
#include "etl/impl/vec/gemm_cc_to_c.hpp"
#include "etl/impl/vec/gemm_cr_to_c.hpp"
#include "etl/impl/vec/gemm_rc_to_c.hpp"
// The idea of the GEMM kernels is largely inspired by the kernels in Blaze by
// Klaus Igleberg
namespace etl {
namespace impl {
namespace vec {
/*!
* \brief Optimized version of GEMM for row major version
*
* \param a The lhs matrix
* \param b The rhs matrix
* \param c The result matrix
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, B, C>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_rr_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Unoptimized version of GEMM for column major version
* \param a The lhs matrix
* \param b The rhs matrix
* \param c The result matrix
*/
template <typename A, typename B, typename C, cpp_enable_if((all_column_major<A, B, C>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_cc_to_c(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<B, C>::value && all_column_major<A>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_cr_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, C>::value && all_column_major<B>::value))>
void gemm(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
gemm_rc_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<C>::value && all_column_major<A, B>::value))>
void gemm(A&& a, B&& b, C&& c) {
const size_t M = etl::rows(a);
const size_t N = etl::columns(b);
const size_t K = etl::columns(a);
if(etl::size(a) < etl::size(b)){
auto t_a = force_temporary_opp(a);
t_a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
gemm_rc_to_r(a.memory_start(), t_a.memory_start(), c.memory_start(), M, N, K);
} else {
auto t_b = force_temporary_opp(b);
t_b.ensure_cpu_up_to_date();
a.ensure_cpu_up_to_date();
gemm_cr_to_r(a.memory_start(), t_b.memory_start(), c.memory_start(), M, N, K);
}
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, B, C>::value))>
void gemm_tn(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::columns(a); // rows(trans(A)) = rows(C)
const size_t N = etl::columns(b); // columns (B) = columns(C)
const size_t K = etl::rows(a); // columns(trans(A)) = rows(B)
gemm_cr_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = trans(A) * B where all matrices are
* stored in column-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_column_major<A, B, C>::value))>
void gemm_tn(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::columns(a); // rows(trans(A)) = rows(C)
const size_t N = etl::columns(b); // columns (B) = columns(C)
const size_t K = etl::rows(a); // columns(trans(A)) = rows(B)
gemm_rc_to_c(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = A * trans(B) where all matrices are
* stored in row-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_row_major<A, B, C>::value))>
void gemm_nt(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::rows(b);
const size_t K = etl::columns(a);
gemm_rc_to_r(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
/*!
* \brief Optimized version of GEMM for C = A * trans(B) where all matrices are
* stored in colum-major order.
*
* \param a The lhs matrix (row major)
* \param b The rhs matrix (transposed row major)
* \param c The result matrix (row major)
*/
template <typename A, typename B, typename C, cpp_enable_if((all_column_major<A, B, C>::value))>
void gemm_nt(A&& a, B&& b, C&& c) {
a.ensure_cpu_up_to_date();
b.ensure_cpu_up_to_date();
const size_t M = etl::rows(a);
const size_t N = etl::rows(b);
const size_t K = etl::columns(a);
gemm_cr_to_c(a.memory_start(), b.memory_start(), c.memory_start(), M, N, K);
c.invalidate_gpu();
}
} //end of namespace vec
} //end of namespace impl
} //end of namespace etl
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_CREATE_HPP
#define FLUSSPFERD_CREATE_HPP
#ifndef PREPROC_DEBUG
#include "object.hpp"
#include "function.hpp"
#include "native_function.hpp"
#include "root.hpp"
#include <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/parameter/name.hpp>
#include <boost/parameter/binding.hpp>
#include <boost/type_traits.hpp>
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>
#include <boost/parameter/config.hpp>
namespace flusspferd {
class native_object_base;
class function;
class native_function_base;
namespace param {
#ifndef IN_DOXYGEN
BOOST_PARAMETER_NAME(container)
BOOST_PARAMETER_NAME(name)
BOOST_PARAMETER_NAME(attributes)
BOOST_PARAMETER_NAME(length)
BOOST_PARAMETER_NAME(contents)
BOOST_PARAMETER_NAME(prototype)
BOOST_PARAMETER_NAME(parent)
BOOST_PARAMETER_NAME(argument_names)
BOOST_PARAMETER_NAME(function)
BOOST_PARAMETER_NAME(file)
BOOST_PARAMETER_NAME(line)
BOOST_PARAMETER_NAME(signature)
BOOST_PARAMETER_NAME(arity)
BOOST_PARAMETER_NAME(arguments)
#else
unspecified_parameter_keyword_type _container;
unspecified_parameter_keyword_type _name;
unspecified_parameter_keyword_type _attributes;
unspecified_parameter_keyword_type _length;
unspecified_parameter_keyword_type _contents;
unspecified_parameter_keyword_type _prototype;
unspecified_parameter_keyword_type _parent;
unspecified_parameter_keyword_type _argument_names;
unspecified_parameter_keyword_type _function;
unspecified_parameter_keyword_type _file;
unspecified_parameter_keyword_type _line;
unspecified_parameter_keyword_type _signature;
unspecified_parameter_keyword_type _arity;
unspecified_parameter_keyword_type _arguments;
#endif
/**
* For passing types as function parameters.
*
* @code
_param = flusspferd::param::type<int>()
@endcode
*/
template<typename T>
struct type {
typedef T parameter;
};
}
#ifndef IN_DOXYGEN
namespace detail {
template<typename Class>
struct new_functor {
template<typename>
struct result {
typedef Class &type;
};
Class &operator()() {
return *new Class;
}
#define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \
template< \
BOOST_PP_ENUM_PARAMS(n, typename T) \
> \
Class &operator()( \
BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \
) \
{ \
return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \
} \
/* */
BOOST_PP_REPEAT_FROM_TO(
1,
BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
FLUSSPFERD_NEW_FUNCTOR_INVOKE,
~)
#undef FLUSSPFERD_NEW_FUNCTOR_INVOKE
};
template<typename Class, typename Cond = void>
struct create_traits;
typedef param::tag::container container_spec;
typedef param::tag::name name_spec;
typedef param::tag::attributes attributes_spec;
template<typename Class, typename ArgPack>
typename boost::enable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::container,
void
>::type,
void
>,
typename create_traits<Class>::result_type
>::type
create_helper(ArgPack const &arg) {
return create_traits<Class>::create(arg);
}
template<typename Class, typename ArgPack>
typename boost::disable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::container,
void
>::type,
void
>,
typename create_traits<Class>::result_type
>::type
create_helper(ArgPack const &arg) {
typedef create_traits<Class> traits;
object container_o(arg[param::_container]);
root_object container(container_o);
typename traits::result_type result(traits::create(arg));
root_value root_result(result);
container.define_property(
arg[param::_name],
result,
arg[param::_attributes | dont_enumerate]);
return result;
}
}
template<typename Class>
typename detail::create_traits<Class>::result_type
create()
{
return detail::create_traits<Class>::create();
}
#define FLUSSPFERD_CREATE(z, n, d) \
template< \
typename Class, \
BOOST_PP_ENUM_PARAMS(n, typename T) \
> \
typename detail::create_traits<Class>::result_type \
create( \
BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \
typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \
{ \
typedef detail::create_traits<Class> traits; \
return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \
} \
/* */
BOOST_PP_REPEAT_FROM_TO(
1,
BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),
FLUSSPFERD_CREATE,
~)
#undef FLUSSPFERD_CREATE
#else //IN_DOXYGEN
/**
* Create an %object or %value of a type implied by @p Class.
*
* This %function takes a number of named parameters. Some named parameters can
* be specified in a specific order, or even in any order, depending on @p Class.
*
* The return %value is always convertible to flusspferd::value.
*
* A few simple examples:
* @code
// Create an empty object.
flusspferd::object o = flusspferd::create< flusspferd::object >();
// Create an empty object with a prototype.
o = flusspferd::create< flusspferd::object >(
flusspferd::param::_prototype = proto);
// Create an array with three elements.
flusspferd::array a = flusspferd::create< flusspferd::array >(boost::assign::list_of(1)(2)(3));
@endcode
*
*
* <dl>
* <dt><b>Common parameters:</b></dt>
* <dd>
* <dl>
* <dt>flusspferd::param::_container</dt>
* <dd>The container object for storing the created %object.</dd>
* <dt>flusspferd::param::_name</dt>
* <dd>The name of the property to be used for storing the %object.</dd>
* <dt>flusspferd::param::_attributes</dt>
* <dd>Attributes to be used for creating the property.<br>
* <em>Default</em>: flusspferd::dont_enumerate</dt>
* </dl>
* </dd>
* <dt><b>object</b></dt>
* <dd>TODO</dd>
* <dt><b>array</b></dt>
* <dd>TODO</dd>
* <dt><b>function</b> / <b>method</b></dt>
* <dd>TODO</dd>
* </dl>
*
* @ingroup create
*/
template<typename Class>
unspecified_type create(...);
#endif
}
#endif
<commit_msg>new_create/doc: header files and parameters for create<object><commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License
Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
http://flusspferd.org/contributors.txt)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_CREATE_HPP
#define FLUSSPFERD_CREATE_HPP
#ifndef PREPROC_DEBUG
#include "object.hpp"
#include "function.hpp"
#include "native_function.hpp"
#include "root.hpp"
#include <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/parameter/name.hpp>
#include <boost/parameter/binding.hpp>
#include <boost/type_traits.hpp>
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>
#include <boost/parameter/config.hpp>
namespace flusspferd {
class native_object_base;
class function;
class native_function_base;
namespace param {
#ifndef IN_DOXYGEN
BOOST_PARAMETER_NAME(container)
BOOST_PARAMETER_NAME(name)
BOOST_PARAMETER_NAME(attributes)
BOOST_PARAMETER_NAME(length)
BOOST_PARAMETER_NAME(contents)
BOOST_PARAMETER_NAME(prototype)
BOOST_PARAMETER_NAME(parent)
BOOST_PARAMETER_NAME(argument_names)
BOOST_PARAMETER_NAME(function)
BOOST_PARAMETER_NAME(file)
BOOST_PARAMETER_NAME(line)
BOOST_PARAMETER_NAME(signature)
BOOST_PARAMETER_NAME(arity)
BOOST_PARAMETER_NAME(arguments)
#else
unspecified_parameter_keyword_type _container;
unspecified_parameter_keyword_type _name;
unspecified_parameter_keyword_type _attributes;
unspecified_parameter_keyword_type _length;
unspecified_parameter_keyword_type _contents;
unspecified_parameter_keyword_type _prototype;
unspecified_parameter_keyword_type _parent;
unspecified_parameter_keyword_type _argument_names;
unspecified_parameter_keyword_type _function;
unspecified_parameter_keyword_type _file;
unspecified_parameter_keyword_type _line;
unspecified_parameter_keyword_type _signature;
unspecified_parameter_keyword_type _arity;
unspecified_parameter_keyword_type _arguments;
#endif
/**
* For passing types as function parameters.
*
* @code
_param = flusspferd::param::type<int>()
@endcode
*/
template<typename T>
struct type {
typedef T parameter;
};
}
#ifndef IN_DOXYGEN
namespace detail {
template<typename Class>
struct new_functor {
template<typename>
struct result {
typedef Class &type;
};
Class &operator()() {
return *new Class;
}
#define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \
template< \
BOOST_PP_ENUM_PARAMS(n, typename T) \
> \
Class &operator()( \
BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \
) \
{ \
return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \
} \
/* */
BOOST_PP_REPEAT_FROM_TO(
1,
BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
FLUSSPFERD_NEW_FUNCTOR_INVOKE,
~)
#undef FLUSSPFERD_NEW_FUNCTOR_INVOKE
};
template<typename Class, typename Cond = void>
struct create_traits;
typedef param::tag::container container_spec;
typedef param::tag::name name_spec;
typedef param::tag::attributes attributes_spec;
template<typename Class, typename ArgPack>
typename boost::enable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::container,
void
>::type,
void
>,
typename create_traits<Class>::result_type
>::type
create_helper(ArgPack const &arg) {
return create_traits<Class>::create(arg);
}
template<typename Class, typename ArgPack>
typename boost::disable_if<
boost::is_same<
typename boost::parameter::binding<
ArgPack,
param::tag::container,
void
>::type,
void
>,
typename create_traits<Class>::result_type
>::type
create_helper(ArgPack const &arg) {
typedef create_traits<Class> traits;
object container_o(arg[param::_container]);
root_object container(container_o);
typename traits::result_type result(traits::create(arg));
root_value root_result(result);
container.define_property(
arg[param::_name],
result,
arg[param::_attributes | dont_enumerate]);
return result;
}
}
template<typename Class>
typename detail::create_traits<Class>::result_type
create()
{
return detail::create_traits<Class>::create();
}
#define FLUSSPFERD_CREATE(z, n, d) \
template< \
typename Class, \
BOOST_PP_ENUM_PARAMS(n, typename T) \
> \
typename detail::create_traits<Class>::result_type \
create( \
BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \
typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \
{ \
typedef detail::create_traits<Class> traits; \
return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \
} \
/* */
BOOST_PP_REPEAT_FROM_TO(
1,
BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),
FLUSSPFERD_CREATE,
~)
#undef FLUSSPFERD_CREATE
#else //IN_DOXYGEN
/**
* Create an %object or %value of a type implied by @p Class.
*
* This %function takes a number of named parameters. Some named parameters can
* be specified in a specific order, or even in any order, depending on @p Class.
*
* The return %value is always convertible to flusspferd::value.
*
* A few simple examples:
* @code
// Create an empty object.
flusspferd::object o = flusspferd::create< flusspferd::object >();
// Create an empty object with a prototype.
o = flusspferd::create< flusspferd::object >(
flusspferd::param::_prototype = proto);
// Create an array with three elements.
flusspferd::array a = flusspferd::create< flusspferd::array >(boost::assign::list_of(1)(2)(3));
@endcode
*
*
* <dl>
* <dt><b>Common parameters:</b></dt>
* <dd>
* <dl>
* <dt>flusspferd::param::_container</dt>
* <dd>The container object for storing the created %object.</dd>
* <dt>flusspferd::param::_name</dt>
* <dd>The name of the property to be used for storing the %object.</dd>
* <dt>flusspferd::param::_attributes</dt>
* <dd>Attributes to be used for creating the property.<br>
* <em>Default</em>: flusspferd::dont_enumerate</dt>
* </dl>
* <br>
* </dd>
* <dt><tt>Class</tt> = <b>object</b></dt>
* <dd><em>Header</em>: flusspferd/create/object.hpp<br><br>
* <dl>
* <dt>flusspferd::param::_prototype</dt>
* <dd>The prototype object to be used.<br>
* <em>Default</em>: <tt>Object.prototype</tt>
* </dd>
* <dt>flusspferd::param::_parent</dt>
* <dd>The parent object to be used.<br>
* <em>Default</em>: Determined by the Javascript engine.
* </dd>
* </dl>
* <br><em>Parameter order</em>:
* flusspferd::param::_prototype, flusspferd::param::_parent
* <br><br>
* </dd>
* <dt><tt>Class</tt> = <b>array</b></dt>
* <dd>Header: flusspferd/create/object.hpp</dd>
* <dt><tt>Class</tt> = <b>function</b> / <b>method</b></dt>
* <dd>Header: flusspferd/create/function.hpp</dd>
* <dt><tt>Class</tt> = class derived from <b>native_object_base</b></dt>
* <dd>Header: flusspferd/create/native_object.hpp</dd>
* <dt><tt>Class</tt> = class derived from <b>native_function_base</b></dt>
* <dd>Header: flusspferd/create/native_function.hpp</dd>
* </dl>
*
* @ingroup create
*/
template<typename Class>
unspecified_type create(...);
#endif
}
#endif
<|endoftext|> |
<commit_before>#include "ex13_44_47.h"
#include <algorithm>
#include <iostream>
std::pair<char*, char*> String::alloc_n_copy(const char* b, const char* e)
{
auto str = alloc.allocate(e - b);
return {str, std::uninitialized_copy(b, e, str)};
}
void String::range_initializer(const char* first, const char* last)
{
auto newstr = alloc_n_copy(first, last);
elements = newstr.first;
end = newstr.second;
}
String::String(const char* s)
{
char* sl = const_cast<char*>(s);
while (*sl) ++sl;
range_initializer(s, ++sl);
}
String::String(const String& rhs)
{
range_initializer(rhs.elements, rhs.end);
std::cout << "copy constructor" << std::endl;
}
void String::free()
{
if (elements) {
std::for_each(elements, end, [this](char& c) { alloc.destroy(&c); });
alloc.deallocate(elements, end - elements);
}
}
String::~String()
{
free();
}
String& String::operator=(const String& rhs)
{
auto newstr = alloc_n_copy(rhs.elements, rhs.end);
free();
elements = newstr.first;
end = newstr.second;
std::cout << "copy-assignment" << std::endl;
return *this;
}
<commit_msg>Update ex13_44_47.cpp<commit_after>#include <iostream>
#include <memory>
#include <utility>
#include <algorithm>
#include "ex13_44_47.h"
using namespace std;
pair<char*, char*> String::alloc_n_copy(const char *b, const char *e)
{
auto str=alloc.allocate(e-b);
return {str, uninitialized_copy(b, e, str)};
}
void String::range_initialize(const char *first, const char *last)
{
auto newstr=alloc_n_copy(first, last);
elements=newstr.first;
end=newstr.second;
}
String::String(const char *s)
{
char *sl=const_cast<char*>(s);
while(*sl)
++sl;
range_initialize(s, ++sl);
}
String::String(const String &s)
{
range_initialize(s.elements, s.end);
cout<<"copy constructor"<<endl;
}
void String::free()
{
if(elements)
{
for_each(elements, end, [this](char &c) {alloc.destroy(&c);});
alloc.deallocate(elements, end-elements);
}
}
String::~String()
{
free();
}
String &String::operator=(const String &rhs)
{
auto newstr=alloc_n_copy(rhs.elements, rhs.end);
free();
elements=newstr.first;
end=newstr.second;
cout<<"copy-assignment operator"<<endl;
return *this;
}
<|endoftext|> |
<commit_before>
//
// wasm intepreter for asm2wasm output, in a js environment. receives asm.js,
// generates a runnable module suitable as a polyfill.
//
// this polyfills an emscripten --separate-asm *.asm.js file, as a drop-in
// replacement. it writes the wasm module to Module.asm, and sets Module.buffer.
//
#include <emscripten.h>
#include "asm2wasm.h"
#include "wasm-interpreter.h"
using namespace cashew;
using namespace wasm;
ModuleInstance* instance = nullptr;
// receives asm.js code, parses into wasm and returns an instance handle.
// this creates a module, an external interface, and a module instance,
// all of which are then the responsibility of the caller to free.
// note: this modifies the input.
extern "C" void EMSCRIPTEN_KEEPALIVE load_asm(char *input) {
assert(instance == nullptr); // singleton
// emcc --separate-asm modules look like
//
// Module["asm"] = (function(global, env, buffer) {
// ..
// });
//
// we need to clean that up.
size_t num = strlen(input);
assert(*input == 'M');
while (*input != 'f') {
input++;
num--;
}
char *end = input + num - 1;
while (*end != '}') {
*end = 0;
end--;
}
int debug = 0;
if (debug) std::cerr << "parsing...\n";
cashew::Parser<Ref, DotZeroValueBuilder> builder;
Ref asmjs = builder.parseToplevel(input);
Module* wasm = new Module();
if (debug) std::cerr << "wasming...\n";
Asm2WasmBuilder asm2wasm(*wasm);
asm2wasm.processAsm(asmjs);
if (debug) std::cerr << "optimizing...\n";
asm2wasm.optimize();
//std::cerr << *wasm << '\n';
if (debug) std::cerr << "generating exports...\n";
EM_ASM({
Module['asmExports'] = {};
});
for (auto& curr : wasm->exports) {
EM_ASM_({
var name = Pointer_stringify($0);
Module['asmExports'][name] = function() {
Module['tempArguments'] = Array.prototype.slice.call(arguments);
return Module['_call_from_js']($0);
};
}, curr.name.str);
}
if (debug) std::cerr << "creating instance...\n";
struct JSExternalInterface : ModuleInstance::ExternalInterface {
Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {
EM_ASM({
Module['tempArguments'] = [];
});
for (auto& argument : arguments) {
if (argument.type == i32) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.geti32());
} else if (argument.type == f64) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.getf64());
} else {
abort();
}
}
return Literal(EM_ASM_DOUBLE({
var mod = Pointer_stringify($0);
var base = Pointer_stringify($1);
var tempArguments = Module['tempArguments'];
Module['tempArguments'] = null;
return Module['instance'][mod][base].apply(null, tempArguments);
}, import->module.str, import->base.str));
}
Literal load(Load* load, Literal ptr) override {
size_t addr = ptr.geti32();
assert(load->align == load->bytes);
if (!load->float_) {
if (load->bytes == 1) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP8'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU8'][$0] }, addr));
}
} else if (load->bytes == 2) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP16'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU16'][$0] }, addr));
}
} else if (load->bytes == 4) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP32'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU32'][$0] }, addr));
}
}
abort();
} else {
if (load->bytes == 4) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF32'][$0] }, addr));
} else if (load->bytes == 8) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF64'][$0] }, addr));
}
abort();
}
}
void store(Store* store, Literal ptr, Literal value) override {
size_t addr = ptr.geti32();
assert(store->align == store->bytes);
if (!store->float_) {
if (store->bytes == 1) {
EM_ASM_INT({ Module['info'].parent['HEAP8'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 2) {
EM_ASM_INT({ Module['info'].parent['HEAP16'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 4) {
EM_ASM_INT({ Module['info'].parent['HEAP32'][$0] = $1 }, addr, value.geti32());
} else {
abort();
}
} else {
if (store->bytes == 4) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF32'][$0] = $1 }, addr, value.getf64());
} else if (store->bytes == 8) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF64'][$0] = $1 }, addr, value.getf64());
} else {
abort();
}
}
}
};
instance = new ModuleInstance(*wasm, new JSExternalInterface());
}
// Does a call from js into an export of the module.
extern "C" double EMSCRIPTEN_KEEPALIVE call_from_js(const char *target) {
IString name(target);
assert(instance->functions.find(name) != instance->functions.end());
Function *function = instance->functions[name];
size_t num = EM_ASM_INT_V({ return Module['tempArguments'].length });
if (num != function->params.size()) {
std::cerr << "warning: bad # of arguments to " << target << ": got " << num << ", but expect " << function->params.size() << '\n';
abort(); // TODO: fake missing/extra args?
#if 0
if (num > function->params.size()) {
num = function->params.size(); // ignore the rest
} else {
.. fake missing ..
}
#endif
}
ModuleInstance::LiteralList arguments;
for (size_t i = 0; i < num; i++) {
WasmType type = function->params[i].type;
if (type == i32) {
arguments.push_back(Literal(EM_ASM_INT({ return Module['tempArguments'][$0] }, i)));
} else if (type == f64) {
arguments.push_back(Literal(EM_ASM_DOUBLE({ return Module['tempArguments'][$0] }, i)));
} else {
abort();
}
}
Literal ret = instance->callFunction(name, arguments);
if (ret.type == i32) return ret.i32;
if (ret.type == f64) return ret.f64;
abort();
}
<commit_msg>not not free builder - we stil need its allocator<commit_after>
//
// wasm intepreter for asm2wasm output, in a js environment. receives asm.js,
// generates a runnable module suitable as a polyfill.
//
// this polyfills an emscripten --separate-asm *.asm.js file, as a drop-in
// replacement. it writes the wasm module to Module.asm, and sets Module.buffer.
//
#include <emscripten.h>
#include "asm2wasm.h"
#include "wasm-interpreter.h"
using namespace cashew;
using namespace wasm;
ModuleInstance* instance = nullptr;
// receives asm.js code, parses into wasm and returns an instance handle.
// this creates a module, an external interface, a builder, and a module instance,
// all of which are then the responsibility of the caller to free.
// note: this modifies the input.
extern "C" void EMSCRIPTEN_KEEPALIVE load_asm(char *input) {
assert(instance == nullptr); // singleton
// emcc --separate-asm modules look like
//
// Module["asm"] = (function(global, env, buffer) {
// ..
// });
//
// we need to clean that up.
size_t num = strlen(input);
assert(*input == 'M');
while (*input != 'f') {
input++;
num--;
}
char *end = input + num - 1;
while (*end != '}') {
*end = 0;
end--;
}
int debug = 0;
if (debug) std::cerr << "parsing...\n";
cashew::Parser<Ref, DotZeroValueBuilder> builder;
Ref asmjs = builder.parseToplevel(input);
Module* wasm = new Module();
if (debug) std::cerr << "wasming...\n";
Asm2WasmBuilder* asm2wasm = new Asm2WasmBuilder(*wasm);
asm2wasm->processAsm(asmjs);
if (debug) std::cerr << "optimizing...\n";
asm2wasm->optimize();
//std::cerr << *wasm << '\n';
if (debug) std::cerr << "generating exports...\n";
EM_ASM({
Module['asmExports'] = {};
});
for (auto& curr : wasm->exports) {
EM_ASM_({
var name = Pointer_stringify($0);
Module['asmExports'][name] = function() {
Module['tempArguments'] = Array.prototype.slice.call(arguments);
return Module['_call_from_js']($0);
};
}, curr.name.str);
}
if (debug) std::cerr << "creating instance...\n";
struct JSExternalInterface : ModuleInstance::ExternalInterface {
Literal callImport(Import *import, ModuleInstance::LiteralList& arguments) override {
EM_ASM({
Module['tempArguments'] = [];
});
for (auto& argument : arguments) {
if (argument.type == i32) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.geti32());
} else if (argument.type == f64) {
EM_ASM_({ Module['tempArguments'].push($0) }, argument.getf64());
} else {
abort();
}
}
return Literal(EM_ASM_DOUBLE({
var mod = Pointer_stringify($0);
var base = Pointer_stringify($1);
var tempArguments = Module['tempArguments'];
Module['tempArguments'] = null;
return Module['instance'][mod][base].apply(null, tempArguments);
}, import->module.str, import->base.str));
}
Literal load(Load* load, Literal ptr) override {
size_t addr = ptr.geti32();
assert(load->align == load->bytes);
if (!load->float_) {
if (load->bytes == 1) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP8'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU8'][$0] }, addr));
}
} else if (load->bytes == 2) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP16'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU16'][$0] }, addr));
}
} else if (load->bytes == 4) {
if (load->signed_) {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAP32'][$0] }, addr));
} else {
return Literal(EM_ASM_INT({ return Module['info'].parent['HEAPU32'][$0] }, addr));
}
}
abort();
} else {
if (load->bytes == 4) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF32'][$0] }, addr));
} else if (load->bytes == 8) {
return Literal(EM_ASM_DOUBLE({ return Module['info'].parent['HEAPF64'][$0] }, addr));
}
abort();
}
}
void store(Store* store, Literal ptr, Literal value) override {
size_t addr = ptr.geti32();
assert(store->align == store->bytes);
if (!store->float_) {
if (store->bytes == 1) {
EM_ASM_INT({ Module['info'].parent['HEAP8'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 2) {
EM_ASM_INT({ Module['info'].parent['HEAP16'][$0] = $1 }, addr, value.geti32());
} else if (store->bytes == 4) {
EM_ASM_INT({ Module['info'].parent['HEAP32'][$0] = $1 }, addr, value.geti32());
} else {
abort();
}
} else {
if (store->bytes == 4) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF32'][$0] = $1 }, addr, value.getf64());
} else if (store->bytes == 8) {
EM_ASM_DOUBLE({ Module['info'].parent['HEAPF64'][$0] = $1 }, addr, value.getf64());
} else {
abort();
}
}
}
};
instance = new ModuleInstance(*wasm, new JSExternalInterface());
}
// Does a call from js into an export of the module.
extern "C" double EMSCRIPTEN_KEEPALIVE call_from_js(const char *target) {
IString name(target);
assert(instance->functions.find(name) != instance->functions.end());
Function *function = instance->functions[name];
size_t num = EM_ASM_INT_V({ return Module['tempArguments'].length });
if (num != function->params.size()) {
std::cerr << "warning: bad # of arguments to " << target << ": got " << num << ", but expect " << function->params.size() << '\n';
abort(); // TODO: fake missing/extra args?
#if 0
if (num > function->params.size()) {
num = function->params.size(); // ignore the rest
} else {
.. fake missing ..
}
#endif
}
ModuleInstance::LiteralList arguments;
for (size_t i = 0; i < num; i++) {
WasmType type = function->params[i].type;
if (type == i32) {
arguments.push_back(Literal(EM_ASM_INT({ return Module['tempArguments'][$0] }, i)));
} else if (type == f64) {
arguments.push_back(Literal(EM_ASM_DOUBLE({ return Module['tempArguments'][$0] }, i)));
} else {
abort();
}
}
Literal ret = instance->callFunction(name, arguments);
if (ret.type == i32) return ret.i32;
if (ret.type == f64) return ret.f64;
abort();
}
<|endoftext|> |
<commit_before># ifndef H_GOO_APPLICATION_H
# define H_GOO_APPLICATION_H
# include <sys/types.h>
# include <unistd.h>
# include <signal.h>
# include <string>
# include <map>
# include <utility>
# include <vector>
# include <typeinfo>
# include <cstdlib>
# include <ostream>
# include <cassert>
# include "goo_types.h"
# include "goo_exception.hpp"
namespace goo {
template<typename ConfigObjectT,
typename LogStreamT> class App;
namespace aux {
/// Abstract application base class.
class iApp {
public:
/// System signal handler callback type.
typedef void(*SignalHandler)(int, siginfo_t *, void*);
/// System signal code.
enum SignalCode {
_SIGHUP = 1, _SIGINT = 2, _SIGFPE = 8,
_SIGUSR1 = 10, _SIGUSR2 = 12, _SIGPIPE = 13,
_SIGALARM = 14, _SIGTERM = 15, _SIGCHLD = 17,
_SIGCONT = 18, _SIGSTP = 20,
};
protected:
/// Registered handlers. Should be invoked in order of addition.
std::map<SignalCode,
std::vector<
std::pair<SignalHandler, std::string> > > _handlers;
/// Private method that dispatches system signals to app.
static void _signal_handler_dispatcher(int signum, siginfo_t *info, void * context);
/// Private constructor that should only be used by App-subclass type.
iApp() {}
virtual ~iApp(){}
/// Used by dispatcher routine instead of System V's ucontext_t.
static iApp * _self;
/// Configured application entry point pure-virtual function.
virtual int _V_run() = 0;
public:
/// Returns application instance.
static iApp & self() { assert(_self); return *_self; }
/// Adds new handler to handlers stack.
void add_handler( SignalCode, SignalHandler, const std::string, bool suppressDefault=false );
/// Prints bound hadlers to stream.
void dump_handlers( std::ostream & ) const;
/// Alias to standard UNIX getpid() function.
inline pid_t PID() const { return getpid(); }
/// C++ alias to standart UNIX hethostname() function.
std::string hostname() const;
/// Goo's alias to acquire environmental variable (std::getenv())
std::string envvar( const std::string & ) const;
template<typename ConfigObjectT,
typename LogStreamT> friend class goo::App;
};
} // namespace goo::aux
/**@brief Application object acquizition shortcut.
*
* Since abstract App singletone itself provides a self()-method
* only for it's own type we need downcast it in order to get a
* concrete class instance. Dynamic casting is slow, so we should
* cache it via special laconic template function. The best
* practice is define alias to this function invokation in user's
* code just after concrete application class declaration.
*/
template<typename ConcreteAppType>
ConcreteAppType & app() {
try {
static ConcreteAppType & casted =
dynamic_cast<ConcreteAppType&>(ConcreteAppType::self());
return casted;
} catch(std::bad_cast & e) {
emraise(badCast, "Invalid application object type casting.");
}
}
/**@brief Abstract application template.
*
* ConfigObjectT is a template parameter describing currently
* used config object (e.g. boost::variables_map). This object
* should be allocated and initialized at _V_configure_app()
* pure-virtual method.
*
* LogStreamT is a template parameter describing currently used
* logging stream object (e.g. std::stringstream or std::cout).
* Concrete onject should be acquired by _V_acquire_stream()
* pure-virtual method.
*/
template<typename ConfigObjectT,
typename LogStreamT>
class App : public aux::iApp {
public:
typedef App<ConfigObjectT, LogStreamT> SelfAbstractType;
private:
/// Stream for standard logging.
LogStreamT * _lStr;
/// Config object.
ConfigObjectT * _cObj;
protected:
/// Creates instance of type ConfigObjectT according to command-line arguments
virtual ConfigObjectT * _V_construct_config_object( int argc, char * const argv[] ) const = 0;
/// Configures application according to recently constructed config object.
virtual void _V_configure_application( const ConfigObjectT * ) = 0;
/// Should create the logging stream of type LogStreamT (app already configured).
virtual LogStreamT * _V_acquire_stream() = 0;
protected:
App() : _lStr(nullptr), _cObj(nullptr) {}
virtual ~App() {}
public:
// general application management
/// Creates application instance. Must be invoked just after entry point.
static SelfAbstractType * init(int argc_, char * argv_[], App<ConfigObjectT, LogStreamT> * app) {
_self = app;
app->_V_configure_application(
app->_cObj = app->_V_construct_config_object(argc_, argv_) );
app->_lStr = app->_V_acquire_stream();
return app;
}
/// Configured application entry point.
static int run() { int rc = _self->_V_run();
delete _self; _self = nullptr;
return rc; }
// methods
/// Returns reference on common loging stream object.
inline LogStreamT & ls() { assert(_lStr); return *_lStr; }
/// Returns reference on common config object.
inline ConfigObjectT & co() { assert(_cObj); return *_cObj; }
/// Returns reference on common config object (const version).
inline const ConfigObjectT * co() const { assert(_cObj); return *_cObj; }
};
} // namespace goo
# endif // H_GOO_APPLICATION_H
<commit_msg>+ iApp::exists()<commit_after># ifndef H_GOO_APPLICATION_H
# define H_GOO_APPLICATION_H
# include <sys/types.h>
# include <unistd.h>
# include <signal.h>
# include <string>
# include <map>
# include <utility>
# include <vector>
# include <typeinfo>
# include <cstdlib>
# include <ostream>
# include <cassert>
# include "goo_types.h"
# include "goo_exception.hpp"
namespace goo {
template<typename ConfigObjectT,
typename LogStreamT> class App;
namespace aux {
/// Abstract application base class.
class iApp {
public:
/// System signal handler callback type.
typedef void(*SignalHandler)(int, siginfo_t *, void*);
/// System signal code.
enum SignalCode {
_SIGHUP = 1, _SIGINT = 2, _SIGFPE = 8,
_SIGUSR1 = 10, _SIGUSR2 = 12, _SIGPIPE = 13,
_SIGALARM = 14, _SIGTERM = 15, _SIGCHLD = 17,
_SIGCONT = 18, _SIGSTP = 20,
};
protected:
/// Registered handlers. Should be invoked in order of addition.
std::map<SignalCode,
std::vector<
std::pair<SignalHandler, std::string> > > _handlers;
/// Private method that dispatches system signals to app.
static void _signal_handler_dispatcher(int signum, siginfo_t *info, void * context);
/// Private constructor that should only be used by App-subclass type.
iApp() {}
virtual ~iApp(){}
/// Used by dispatcher routine instead of System V's ucontext_t.
static iApp * _self;
/// Configured application entry point pure-virtual function.
virtual int _V_run() = 0;
public:
/// Returns application instance.
static iApp & self() { assert(_self); return *_self; }
/// Adds new handler to handlers stack.
void add_handler( SignalCode, SignalHandler, const std::string, bool suppressDefault=false );
/// Prints bound hadlers to stream.
void dump_handlers( std::ostream & ) const;
/// Alias to standard UNIX getpid() function.
inline pid_t PID() const { return getpid(); }
/// C++ alias to standart UNIX hethostname() function.
std::string hostname() const;
/// Goo's alias to acquire environmental variable (std::getenv())
std::string envvar( const std::string & ) const;
/// Returns true, if instance was created.
static bool exists() { return _self; }
template<typename ConfigObjectT,
typename LogStreamT> friend class goo::App;
};
} // namespace goo::aux
/**@brief Application object acquizition shortcut.
*
* Since abstract App singletone itself provides a self()-method
* only for it's own type we need downcast it in order to get a
* concrete class instance. Dynamic casting is slow, so we should
* cache it via special laconic template function. The best
* practice is define alias to this function invokation in user's
* code just after concrete application class declaration.
*/
template<typename ConcreteAppType>
ConcreteAppType & app() {
try {
static ConcreteAppType & casted =
dynamic_cast<ConcreteAppType&>(ConcreteAppType::self());
return casted;
} catch(std::bad_cast & e) {
emraise(badCast, "Invalid application object type casting.");
}
}
/**@brief Abstract application template.
*
* ConfigObjectT is a template parameter describing currently
* used config object (e.g. boost::variables_map). This object
* should be allocated and initialized at _V_configure_app()
* pure-virtual method.
*
* LogStreamT is a template parameter describing currently used
* logging stream object (e.g. std::stringstream or std::cout).
* Concrete onject should be acquired by _V_acquire_stream()
* pure-virtual method.
*/
template<typename ConfigObjectT,
typename LogStreamT>
class App : public aux::iApp {
public:
typedef App<ConfigObjectT, LogStreamT> SelfAbstractType;
private:
/// Stream for standard logging.
LogStreamT * _lStr;
/// Config object.
ConfigObjectT * _cObj;
protected:
/// Creates instance of type ConfigObjectT according to command-line arguments
virtual ConfigObjectT * _V_construct_config_object( int argc, char * const argv[] ) const = 0;
/// Configures application according to recently constructed config object.
virtual void _V_configure_application( const ConfigObjectT * ) = 0;
/// Should create the logging stream of type LogStreamT (app already configured).
virtual LogStreamT * _V_acquire_stream() = 0;
protected:
App() : _lStr(nullptr), _cObj(nullptr) {}
virtual ~App() {}
public:
// general application management
/// Creates application instance. Must be invoked just after entry point.
static SelfAbstractType * init(int argc_, char * argv_[], App<ConfigObjectT, LogStreamT> * app) {
_self = app;
app->_V_configure_application(
app->_cObj = app->_V_construct_config_object(argc_, argv_) );
app->_lStr = app->_V_acquire_stream();
return app;
}
/// Configured application entry point.
static int run() { int rc = _self->_V_run();
delete _self; _self = nullptr;
return rc; }
// methods
/// Returns reference on common loging stream object.
inline LogStreamT & ls() { assert(_lStr); return *_lStr; }
/// Returns reference on common config object.
inline ConfigObjectT & co() { assert(_cObj); return *_cObj; }
/// Returns reference on common config object (const version).
inline const ConfigObjectT * co() const { assert(_cObj); return *_cObj; }
};
} // namespace goo
# endif // H_GOO_APPLICATION_H
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_MAKE_UNIQUE_HPP
#define MAPNIK_MAKE_UNIQUE_HPP
#include <memory>
namespace mapnik {
// C++14 backfill from http://herbsutter.com/gotw/_102/
template<typename T, typename ...Args>
inline std::unique_ptr<T> make_unique(Args&& ...args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
#endif // MAPNIK_MAKE_UNIQUE_HPP
<commit_msg>attempt to fix compile on linux<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_MAKE_UNIQUE_HPP
#define MAPNIK_MAKE_UNIQUE_HPP
#include <memory>
#if __cplusplus <= 201103L
namespace std {
// C++14 backfill from http://herbsutter.com/gotw/_102/
template<typename T, typename ...Args>
inline std::unique_ptr<T> make_unique(Args&& ...args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
#endif
#endif // MAPNIK_MAKE_UNIQUE_HPP
<|endoftext|> |
<commit_before>#ifndef LIB_MART_COMMON_GUARD_NW_SOCKET_H
#define LIB_MART_COMMON_GUARD_NW_SOCKET_H
/**
* RaiiSocket.hpp (mart-common/nw)
*
* Copyright (C) 2015-2019: Michael Balszun <[email protected]>
*
* This software may be modified and distributed under the terms
* of the MIT license. See either the LICENSE file in the library's root
* directory or http://opensource.org/licenses/MIT for details.
*
* @author: Michael Balszun <[email protected]>
* @brief: Provides mart::RaiiSocket - an thin RAII-wrapper around the port_layer functions
*
*/
/* ######## INCLUDES ######### */
/* Project Includes */
#include "basic_types.hpp"
#include "port_layer.hpp"
/* Proprietary Library Includes */
#include <mart-common/ArrayView.h>
/* Standard Library Includes */
#include <cerrno>
#include <chrono>
#include <cstring>
#include <string_view>
/* ~~~~~~~~ INCLUDES ~~~~~~~~~ */
namespace mart {
namespace nw {
namespace socks {
namespace _detail_socket_ {
inline byte_range to_byte_range( const ::mart::ConstMemoryView memory )
{
return byte_range {reinterpret_cast<unsigned char const*>( memory.data() ), memory.size()};
}
inline byte_range_mut to_mutable_byte_range( ::mart::MemoryView memory )
{
return byte_range_mut {reinterpret_cast<unsigned char*>( memory.data() ), memory.size()};
}
inline byte_range to_byte_range( const std::string_view memory )
{
return byte_range {reinterpret_cast<unsigned char const*>( memory.data() ), memory.size()};
}
} // namespace _detail_socket_
inline std::string_view to_text_rep( ErrorCode code )
{
#ifdef _MSC_VER
#pragma warning( suppress : 4996 )
return std::string_view( std::strerror( code.raw_value() ) );
#else
return std::string_view( std::strerror( code.raw_value() ) );
#endif
}
/* This class is a very thin RAII wrapper around the OS's native socket handle.
* It also translates the native socket function (like bind, connect send etc.) into member functions
* which sometimes use a little more convenient parameter types (e.g. ArrayView instead of pointer+length)
* It doesn't retain any state except the handle and may cache a few config flags.
*/
class RaiiSocket {
public:
/*##### CTORS / DTORS #####*/
constexpr RaiiSocket() = default;
explicit RaiiSocket( port_layer::handle_t handle ) noexcept
: _handle( handle )
{
_setBlocking_uncached( true );
}
RaiiSocket( Domain domain, TransportType type ) noexcept { _open( domain, type ); }
~RaiiSocket() noexcept { close(); }
/*##### Special member functions #####*/
RaiiSocket( const RaiiSocket& other ) = delete;
RaiiSocket& operator=( const RaiiSocket& other ) = delete;
RaiiSocket( RaiiSocket&& other ) noexcept
: _handle {std::exchange( other._handle, port_layer::handle_t::Invalid )}
, _is_blocking {std::exchange( other._is_blocking, false )}
{
}
RaiiSocket& operator=( RaiiSocket&& other ) noexcept
{
close();
_handle = std::exchange( other._handle, port_layer::handle_t::Invalid );
_is_blocking = std::exchange( other._is_blocking, true );
return *this;
}
/*##### RaiiSocket operations #####*/
bool is_valid() const noexcept { return _handle != port_layer::handle_t::Invalid; }
ErrorCode close() noexcept
{
ErrorCode ret = port_layer::close_socket( _handle );
_handle = port_layer::handle_t::Invalid;
return ret;
}
port_layer::handle_t get_handle() const { return _handle; }
port_layer::handle_t release() { return std::exchange( _handle, port_layer::handle_t::Invalid ); }
/* ###### send / rec ############### */
struct SendResult {
mart::ConstMemoryView remaining_data;
ReturnValue<txrx_size_t> result;
};
SendResult send( mart::ConstMemoryView data, int flags = 0 )
{
auto res = port_layer::send( _handle, _detail_socket_::to_byte_range( data ), flags );
return {data.subview( res.value_or( 0 ) ), res};
}
SendResult sendto( mart::ConstMemoryView data, int flags, const Sockaddr& addr )
{
auto res = port_layer::sendto( _handle, _detail_socket_::to_byte_range( data ), flags, addr );
return {data.subview( res.value_or( 0 ) ), res};
}
struct RecvResult {
mart::MemoryView received_data;
ReturnValue<txrx_size_t> result;
};
RecvResult recv( mart::MemoryView buffer, int flags )
{
auto res = port_layer::recv( _handle, _detail_socket_::to_mutable_byte_range( buffer ), flags );
if( res.success() ) {
return {buffer.subview( 0, res.value() ), res};
} else {
return {mart::MemoryView {}, res};
}
}
RecvResult recvfrom( mart::MemoryView buffer, int flags, Sockaddr& src_addr )
{
auto res = port_layer::recvfrom( _handle, _detail_socket_::to_mutable_byte_range( buffer ), flags, src_addr );
if( res.success() ) {
return {buffer.subview( 0, res.value() ), res};
} else {
return {mart::MemoryView {}, res};
}
}
/* ###### connection related ############### */
auto bind( const Sockaddr& addr ) noexcept { return port_layer::bind( _handle, addr ); }
auto connect( const Sockaddr& addr ) noexcept { return port_layer::connect( _handle, addr ); }
auto listen( int backlog ) { return port_layer::listen( _handle, backlog ); }
RaiiSocket accept() noexcept
{
auto res = port_layer::accept( _handle );
if( res ) {
return RaiiSocket( res.value() );
} else {
return RaiiSocket {};
}
}
RaiiSocket accept( Sockaddr& remote_addr ) noexcept
{
auto res = port_layer::accept( _handle, remote_addr );
if( res ) {
return RaiiSocket( res.value() );
} else {
return RaiiSocket {};
}
}
/* ###### Configuration ############### */
template<class T>
ErrorCode setsockopt( SocketOptionLevel level, SocketOption optname, const T& option_data ) noexcept
{
auto opmem = byte_range_from_pod( option_data );
return port_layer::setsockopt( _handle, level, optname, opmem );
}
template<class T>
ErrorCode getsockopt( SocketOptionLevel level, SocketOption optname, T& option_data ) const noexcept
{
return port_layer::getsockopt( _handle, level, optname, byte_range_from_pod( option_data ) );
}
ErrorCode set_blocking( bool should_block ) noexcept
{
if( _is_blocking == should_block ) { return {ErrorCodeValues::NoError}; }
return _setBlocking_uncached( should_block );
}
bool is_blocking() const noexcept
{
// XXX: acutally query the native socket
return _is_blocking && is_valid();
}
bool set_tx_timeout( std::chrono::microseconds timeout ) noexcept
{
return port_layer::set_timeout( _handle, Direction::Tx, timeout ).success();
}
bool set_rx_timeout( std::chrono::microseconds timeout ) noexcept
{
return port_layer::set_timeout( _handle, Direction::Rx, timeout ).success();
}
std::chrono::microseconds get_tx_timeout() noexcept
{
return port_layer::get_timeout( _handle, Direction::Tx ).value_or( {} );
}
std::chrono::microseconds get_rx_timeout() noexcept
{
return port_layer::get_timeout( _handle, Direction::Rx ).value_or( {} );
}
private:
ErrorCode _open( Domain domain, TransportType type ) noexcept
{
auto res = port_layer::socket( domain, type );
if( res ) {
_handle = res.value();
_setBlocking_uncached( true );
}
return res.error_code();
}
ErrorCode _setBlocking_uncached( bool should_block ) noexcept
{
const auto res = port_layer::set_blocking( _handle, should_block );
if( res.success() ) { _is_blocking = should_block; }
return res;
}
port_layer::handle_t _handle = port_layer::handle_t::Invalid;
bool _is_blocking = true;
};
} // namespace socks
} // namespace nw
} // namespace mart
#endif
<commit_msg>[netlib] Add get() method to RaiiSocket<commit_after>#ifndef LIB_MART_COMMON_GUARD_NW_SOCKET_H
#define LIB_MART_COMMON_GUARD_NW_SOCKET_H
/**
* RaiiSocket.hpp (mart-common/nw)
*
* Copyright (C) 2015-2019: Michael Balszun <[email protected]>
*
* This software may be modified and distributed under the terms
* of the MIT license. See either the LICENSE file in the library's root
* directory or http://opensource.org/licenses/MIT for details.
*
* @author: Michael Balszun <[email protected]>
* @brief: Provides mart::RaiiSocket - an thin RAII-wrapper around the port_layer functions
*
*/
/* ######## INCLUDES ######### */
/* Project Includes */
#include "basic_types.hpp"
#include "port_layer.hpp"
/* Proprietary Library Includes */
#include <mart-common/ArrayView.h>
/* Standard Library Includes */
#include <cerrno>
#include <chrono>
#include <cstring>
#include <string_view>
/* ~~~~~~~~ INCLUDES ~~~~~~~~~ */
namespace mart {
namespace nw {
namespace socks {
namespace _detail_socket_ {
inline byte_range to_byte_range( const ::mart::ConstMemoryView memory )
{
return byte_range {reinterpret_cast<unsigned char const*>( memory.data() ), memory.size()};
}
inline byte_range_mut to_mutable_byte_range( ::mart::MemoryView memory )
{
return byte_range_mut {reinterpret_cast<unsigned char*>( memory.data() ), memory.size()};
}
inline byte_range to_byte_range( const std::string_view memory )
{
return byte_range {reinterpret_cast<unsigned char const*>( memory.data() ), memory.size()};
}
} // namespace _detail_socket_
inline std::string_view to_text_rep( ErrorCode code )
{
#ifdef _MSC_VER
#pragma warning( suppress : 4996 )
return std::string_view( std::strerror( code.raw_value() ) );
#else
return std::string_view( std::strerror( code.raw_value() ) );
#endif
}
/* This class is a very thin RAII wrapper around the OS's native socket handle.
* It also translates the native socket function (like bind, connect send etc.) into member functions
* which sometimes use a little more convenient parameter types (e.g. ArrayView instead of pointer+length)
* It doesn't retain any state except the handle and may cache a few config flags.
*/
class RaiiSocket {
public:
/*##### CTORS / DTORS #####*/
constexpr RaiiSocket() = default;
explicit RaiiSocket( port_layer::handle_t handle ) noexcept
: _handle( handle )
{
_setBlocking_uncached( true );
}
RaiiSocket( Domain domain, TransportType type ) noexcept { _open( domain, type ); }
~RaiiSocket() noexcept { close(); }
/*##### Special member functions #####*/
RaiiSocket( const RaiiSocket& other ) = delete;
RaiiSocket& operator=( const RaiiSocket& other ) = delete;
RaiiSocket( RaiiSocket&& other ) noexcept
: _handle {std::exchange( other._handle, port_layer::handle_t::Invalid )}
, _is_blocking {std::exchange( other._is_blocking, false )}
{
}
RaiiSocket& operator=( RaiiSocket&& other ) noexcept
{
close();
_handle = std::exchange( other._handle, port_layer::handle_t::Invalid );
_is_blocking = std::exchange( other._is_blocking, true );
return *this;
}
/*##### RaiiSocket operations #####*/
bool is_valid() const noexcept { return _handle != port_layer::handle_t::Invalid; }
ErrorCode close() noexcept
{
ErrorCode ret = port_layer::close_socket( _handle );
_handle = port_layer::handle_t::Invalid;
return ret;
}
port_layer::handle_t get_handle() const { return _handle; }
port_layer::handle_t release() { return std::exchange( _handle, port_layer::handle_t::Invalid ); }
/* ###### send / rec ############### */
struct SendResult {
mart::ConstMemoryView remaining_data;
ReturnValue<txrx_size_t> result;
};
SendResult send( mart::ConstMemoryView data, int flags = 0 )
{
auto res = port_layer::send( _handle, _detail_socket_::to_byte_range( data ), flags );
return {data.subview( res.value_or( 0 ) ), res};
}
SendResult sendto( mart::ConstMemoryView data, int flags, const Sockaddr& addr )
{
auto res = port_layer::sendto( _handle, _detail_socket_::to_byte_range( data ), flags, addr );
return {data.subview( res.value_or( 0 ) ), res};
}
struct RecvResult {
mart::MemoryView received_data;
ReturnValue<txrx_size_t> result;
};
RecvResult recv( mart::MemoryView buffer, int flags )
{
auto res = port_layer::recv( _handle, _detail_socket_::to_mutable_byte_range( buffer ), flags );
if( res.success() ) {
return {buffer.subview( 0, res.value() ), res};
} else {
return {mart::MemoryView {}, res};
}
}
RecvResult recvfrom( mart::MemoryView buffer, int flags, Sockaddr& src_addr )
{
auto res = port_layer::recvfrom( _handle, _detail_socket_::to_mutable_byte_range( buffer ), flags, src_addr );
if( res.success() ) {
return {buffer.subview( 0, res.value() ), res};
} else {
return {mart::MemoryView {}, res};
}
}
/* ###### connection related ############### */
auto bind( const Sockaddr& addr ) noexcept { return port_layer::bind( _handle, addr ); }
auto connect( const Sockaddr& addr ) noexcept { return port_layer::connect( _handle, addr ); }
auto listen( int backlog ) { return port_layer::listen( _handle, backlog ); }
RaiiSocket accept() noexcept
{
auto res = port_layer::accept( _handle );
if( res ) {
return RaiiSocket( res.value() );
} else {
return RaiiSocket {};
}
}
RaiiSocket accept( Sockaddr& remote_addr ) noexcept
{
auto res = port_layer::accept( _handle, remote_addr );
if( res ) {
return RaiiSocket( res.value() );
} else {
return RaiiSocket {};
}
}
/* ###### Configuration ############### */
template<class T>
ErrorCode setsockopt( SocketOptionLevel level, SocketOption optname, const T& option_data ) noexcept
{
auto opmem = byte_range_from_pod( option_data );
return port_layer::setsockopt( _handle, level, optname, opmem );
}
template<class T>
ErrorCode getsockopt( SocketOptionLevel level, SocketOption optname, T& option_data ) const noexcept
{
return port_layer::getsockopt( _handle, level, optname, byte_range_from_pod( option_data ) );
}
ErrorCode set_blocking( bool should_block ) noexcept
{
if( _is_blocking == should_block ) { return {ErrorCodeValues::NoError}; }
return _setBlocking_uncached( should_block );
}
bool is_blocking() const noexcept
{
// XXX: acutally query the native socket
return _is_blocking && is_valid();
}
bool set_tx_timeout( std::chrono::microseconds timeout ) noexcept
{
return port_layer::set_timeout( _handle, Direction::Tx, timeout ).success();
}
bool set_rx_timeout( std::chrono::microseconds timeout ) noexcept
{
return port_layer::set_timeout( _handle, Direction::Rx, timeout ).success();
}
std::chrono::microseconds get_tx_timeout() noexcept
{
return port_layer::get_timeout( _handle, Direction::Tx ).value_or( {} );
}
std::chrono::microseconds get_rx_timeout() noexcept
{
return port_layer::get_timeout( _handle, Direction::Rx ).value_or( {} );
}
port_layer::handle_t get() const { return _handle; }
private:
ErrorCode _open( Domain domain, TransportType type ) noexcept
{
auto res = port_layer::socket( domain, type );
if( res ) {
_handle = res.value();
_setBlocking_uncached( true );
}
return res.error_code();
}
ErrorCode _setBlocking_uncached( bool should_block ) noexcept
{
const auto res = port_layer::set_blocking( _handle, should_block );
if( res.success() ) { _is_blocking = should_block; }
return res;
}
port_layer::handle_t _handle = port_layer::handle_t::Invalid;
bool _is_blocking = true;
};
} // namespace socks
} // namespace nw
} // namespace mart
#endif
<|endoftext|> |
<commit_before>#ifndef OBJECTS_H
#define OBJECTS_H
/*
Defines an Object::ref type, which is a tagged pointer type.
Usage:
Object::ref x = Object::to_ref(1);//smallint
Object::ref y = Object::to_ref(new(hp) Generic()); //object
if(is_a<int>(x)) {
std::cout << "x = " << as_a<int>(x) << std::endl;
}
if(is_a<Generic*>(y)) {
std::cout << "y.field = " << as_a<Generic*>(y)->field
<< std::endl;
}
*/
#include<stdint.h>
#include<climits>
#include"unichars.hpp"
#ifdef MY_COMPILER
// without these my compiler signals an error -- stefano
// I suggest you try it now with all_defines.hpp
// included in all source files -- almkglor
#define INTPTR_MIN (-2147483647-1)
#define INTPTR_MAX (2147483647)
#endif // MY_COMPILER
class Generic;
class Symbol;
class Cons;
class Closure;
class KClosure;
namespace Object {
/*-----------------------------------------------------------------------------
Declare
-----------------------------------------------------------------------------*/
class ref;
template<typename T> struct tag_traits;
/*assume we won't ever need more than 7 bits of tag*/
typedef unsigned char tag_type;
template<typename T> static inline ref to_ref(T);
template<typename T> static inline bool _is_a(ref);
template<typename T> static inline T _as_a(ref);
static inline ref t(void);
static inline bool _is_t(ref);
static inline ref nil(void);
static inline bool _is_nil(ref);
static inline ref from_a_scaled_int(int);
static inline int to_a_scaled_int(ref);
}
void throw_TypeError(Object::ref, char const*);
void throw_RangeError(char const*);
template<typename T> static inline bool is_a(Object::ref);
template<typename T> static inline T as_a(Object::ref);
static inline bool is_t(Object::ref);
namespace Object {
/*-----------------------------------------------------------------------------
Configuration
-----------------------------------------------------------------------------*/
static const unsigned char tag_bits = 2;// can bump up to 3 maybe...
template<> struct tag_traits<int> {
static const tag_type tag = 0x1;
};
template<> struct tag_traits<Generic*> {
static const tag_type tag = 0x0;
};
template<> struct tag_traits<Symbol*> {
static const tag_type tag = 0x2;
};
template<> struct tag_traits<UnicodeChar> {
static const tag_type tag = 0x3;
};
/*-----------------------------------------------------------------------------
Provided information
-----------------------------------------------------------------------------*/
static const tag_type alignment = 1 << tag_bits;
static const tag_type tag_mask = alignment - 1;
/*the real range is the smaller of the range of intptr_t
shifted down by tag bits, or the range of the `int' type
*/
static const intptr_t smallint_min =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MIN >> tag_bits :
/*otherwise*/
INT_MIN;
static const intptr_t smallint_max =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MAX >> tag_bits :
/*otherwise*/
INT_MAX;
/*value for "t"*/
static const intptr_t t_value = ~((intptr_t) tag_mask);
/*-----------------------------------------------------------------------------
The tagged pointer type
-----------------------------------------------------------------------------*/
/*stefano prefers to use:
typedef void* ref;
or maybe:
typedef intptr_t ref;
I may change this later on, but for now
I want to see whether the conceptual
separation will help and if compilers,
in general, will be smart enough to
optimize away the structure.
*/
class ref {
private:
intptr_t dat;
ref(intptr_t x) : dat(x) {}
public:
ref(void) : dat(0) {}
inline bool operator==(ref b) {
return dat == b.dat;
}
inline bool operator!=(ref b) {
return dat != b.dat;
}
inline bool operator!(void) {
return dat == 0;
}
/*safe bool idiom*/
typedef intptr_t (ref::*unspecified_bool_type);
inline operator unspecified_bool_type(void) {
return dat != 0 ? &ref::dat : 0;
}
template<typename T> friend ref to_ref(T);
template<typename T> friend bool _is_a(ref);
template<typename T> friend T _as_a(ref);
friend int to_a_scaled_int(ref);
friend ref from_a_scaled_int(int);
friend ref t(void);
friend bool _is_t(ref);
};
/*-----------------------------------------------------------------------------
Tagged pointer factories
-----------------------------------------------------------------------------*/
template<typename T>
static inline ref to_ref(T x) {
/* default to Generic* */
return to_ref<Generic*>(x);
}
template<>
ref to_ref<Generic*>(Generic* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Generic*>::tag);
}
template<>
ref to_ref<Symbol*>(Symbol* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Symbol*>::tag);
}
template<>
ref to_ref<int>(int x) {
#ifdef DEBUG
#if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN)
if(x < smallint_min || x > smallint_max) {
throw_RangeError(
"int out of range of smallint"
);
}
#endif
#endif
intptr_t tmp = (((intptr_t) x) << tag_bits);
return ref(tmp + tag_traits<int>::tag);
}
template<>
ref to_ref<UnicodeChar>(UnicodeChar x) {
intptr_t tmp = x.dat << tag_bits;
return ref(tmp + tag_traits<UnicodeChar>::tag);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert an int computed using
Object::to_a_scaled_int back to an Object::ref. It is not
intended to be used for any other int's.
This function is intended for optimized smallint
mathematics.
*/
static inline ref from_a_scaled_int(int x) {
return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag);
}
static inline ref nil(void) {
return ref();
}
static inline ref t(void) {
return ref(t_value);
}
/*-----------------------------------------------------------------------------
Tagged pointer checking
-----------------------------------------------------------------------------*/
static inline bool _is_nil(ref obj) {
return !obj;
}
static inline bool _is_t(ref obj) {
return obj.dat == t_value;
}
template<typename T>
static inline bool _is_a(ref obj) {
if(tag_traits<T>::tag != 0x0) {
return (obj.dat & tag_mask) == tag_traits<T>::tag;
} else {
return (obj.dat & tag_mask) == tag_traits<T>::tag
&& !_is_nil(obj) && !_is_t(obj);
}
}
/*-----------------------------------------------------------------------------
Tagged pointer referencing
-----------------------------------------------------------------------------*/
template<typename T>
static inline T _as_a(ref obj) {
#ifdef DEBUG
if(!_is_a<T>(obj)) {
throw_TypeError(obj,
"incorrect type for pointer"
);
}
#endif
intptr_t tmp = obj.dat;
return reinterpret_cast<T>(tmp - tag_traits<T>::tag);
/*use subtraction instead of masking, in order to
allow smart compilers to merge a field access with
the tag removal. i.e. the pointers are pointers to
structures, so they will be accessed via fields, and
in all probability those fields will be at some
offset from the actual structure address, meaning
that the processor itself will perform an addition
to access the field. The smart compiler can then
merge the addition of the field offset with the
subtraction of the tag.
*/
}
template<>
int _as_a<int>(ref obj) {
#ifdef DEBUG
if(!_is_a<int>(obj)) {
throw_TypeError(obj,
"incorrect type for small integer"
);
}
#endif
intptr_t tmp = obj.dat;
return (int)(tmp >> tag_bits);
}
template<>
UnicodeChar _as_a<UnicodeChar>(ref obj) {
uint32_t tmp = obj.dat;
return UnicodeChar(tmp >> tag_bits);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert a smallint Object::ref
to a useable int that is equal to the "real" int, shifted
to the left by the number of tag bits (i.e. scaled). It
should be used only for optimizing smallint math operations.
*/
static inline int to_a_scaled_int(ref obj) {
intptr_t tmp = obj.dat;
return (int)((tmp - tag_traits<int>::tag)>>tag_bits);
/*use subtraction instead of masking, again to
allow smart compilers to merge tag adding and
subtracting. For example the typical case would
be something like:
Object::ref result =
Object::from_a_scaled_int(
Object::to_a_scaled_int(a) +
Object::to_a_scaled_int(b)
);
The above case can be reduced by the compiler to:
intptr_t result =
(tag_traits<int>::tag +
a - tag_traits<int>::tag +
b - tag_traits<int>::tag
);
It can then do some maths and cancel out a tag:
intptr_t result = a + b - tag_traits<int>::tag;
*/
}
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
static inline size_t round_up_to_alignment(size_t x) {
return
(x & tag_mask) ? (x + alignment - (x & tag_mask)) :
/*otherwise*/ x ;
}
}
/*-----------------------------------------------------------------------------
Reflectors outside of the namespace
-----------------------------------------------------------------------------*/
template<typename T>
static inline bool is_a(Object::ref obj) {
return Object::_is_a<T>(obj);
}
template<typename T>
static inline T as_a(Object::ref obj) {
return Object::_as_a<T>(obj);
}
static inline bool is_nil(Object::ref obj) {
return Object::_is_nil(obj);
}
static inline bool is_t(Object::ref obj) {
return Object::_is_t(obj);
}
#endif //OBJECTS_H
<commit_msg>inc/objects.hpp: Removed MY_COMPILER block. I *think* it's been resolved now, but feel free to revert if not<commit_after>#ifndef OBJECTS_H
#define OBJECTS_H
/*
Defines an Object::ref type, which is a tagged pointer type.
Usage:
Object::ref x = Object::to_ref(1);//smallint
Object::ref y = Object::to_ref(new(hp) Generic()); //object
if(is_a<int>(x)) {
std::cout << "x = " << as_a<int>(x) << std::endl;
}
if(is_a<Generic*>(y)) {
std::cout << "y.field = " << as_a<Generic*>(y)->field
<< std::endl;
}
*/
#include<stdint.h>
#include<climits>
#include"unichars.hpp"
class Generic;
class Symbol;
class Cons;
class Closure;
class KClosure;
namespace Object {
/*-----------------------------------------------------------------------------
Declare
-----------------------------------------------------------------------------*/
class ref;
template<typename T> struct tag_traits;
/*assume we won't ever need more than 7 bits of tag*/
typedef unsigned char tag_type;
template<typename T> static inline ref to_ref(T);
template<typename T> static inline bool _is_a(ref);
template<typename T> static inline T _as_a(ref);
static inline ref t(void);
static inline bool _is_t(ref);
static inline ref nil(void);
static inline bool _is_nil(ref);
static inline ref from_a_scaled_int(int);
static inline int to_a_scaled_int(ref);
}
void throw_TypeError(Object::ref, char const*);
void throw_RangeError(char const*);
template<typename T> static inline bool is_a(Object::ref);
template<typename T> static inline T as_a(Object::ref);
static inline bool is_t(Object::ref);
namespace Object {
/*-----------------------------------------------------------------------------
Configuration
-----------------------------------------------------------------------------*/
static const unsigned char tag_bits = 2;// can bump up to 3 maybe...
template<> struct tag_traits<int> {
static const tag_type tag = 0x1;
};
template<> struct tag_traits<Generic*> {
static const tag_type tag = 0x0;
};
template<> struct tag_traits<Symbol*> {
static const tag_type tag = 0x2;
};
template<> struct tag_traits<UnicodeChar> {
static const tag_type tag = 0x3;
};
/*-----------------------------------------------------------------------------
Provided information
-----------------------------------------------------------------------------*/
static const tag_type alignment = 1 << tag_bits;
static const tag_type tag_mask = alignment - 1;
/*the real range is the smaller of the range of intptr_t
shifted down by tag bits, or the range of the `int' type
*/
static const intptr_t smallint_min =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MIN >> tag_bits :
/*otherwise*/
INT_MIN;
static const intptr_t smallint_max =
(sizeof(int) >= sizeof(intptr_t)) ?
INTPTR_MAX >> tag_bits :
/*otherwise*/
INT_MAX;
/*value for "t"*/
static const intptr_t t_value = ~((intptr_t) tag_mask);
/*-----------------------------------------------------------------------------
The tagged pointer type
-----------------------------------------------------------------------------*/
/*stefano prefers to use:
typedef void* ref;
or maybe:
typedef intptr_t ref;
I may change this later on, but for now
I want to see whether the conceptual
separation will help and if compilers,
in general, will be smart enough to
optimize away the structure.
*/
class ref {
private:
intptr_t dat;
ref(intptr_t x) : dat(x) {}
public:
ref(void) : dat(0) {}
inline bool operator==(ref b) {
return dat == b.dat;
}
inline bool operator!=(ref b) {
return dat != b.dat;
}
inline bool operator!(void) {
return dat == 0;
}
/*safe bool idiom*/
typedef intptr_t (ref::*unspecified_bool_type);
inline operator unspecified_bool_type(void) {
return dat != 0 ? &ref::dat : 0;
}
template<typename T> friend ref to_ref(T);
template<typename T> friend bool _is_a(ref);
template<typename T> friend T _as_a(ref);
friend int to_a_scaled_int(ref);
friend ref from_a_scaled_int(int);
friend ref t(void);
friend bool _is_t(ref);
};
/*-----------------------------------------------------------------------------
Tagged pointer factories
-----------------------------------------------------------------------------*/
template<typename T>
static inline ref to_ref(T x) {
/* default to Generic* */
return to_ref<Generic*>(x);
}
template<>
ref to_ref<Generic*>(Generic* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Generic*>::tag);
}
template<>
ref to_ref<Symbol*>(Symbol* x) {
intptr_t tmp = reinterpret_cast<intptr_t>(x);
#ifdef DEBUG
if(tmp & tag_mask != 0) {
throw_RangeError("Misaligned pointer");
}
#endif
return ref(tmp + tag_traits<Symbol*>::tag);
}
template<>
ref to_ref<int>(int x) {
#ifdef DEBUG
#if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN)
if(x < smallint_min || x > smallint_max) {
throw_RangeError(
"int out of range of smallint"
);
}
#endif
#endif
intptr_t tmp = (((intptr_t) x) << tag_bits);
return ref(tmp + tag_traits<int>::tag);
}
template<>
ref to_ref<UnicodeChar>(UnicodeChar x) {
intptr_t tmp = x.dat << tag_bits;
return ref(tmp + tag_traits<UnicodeChar>::tag);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert an int computed using
Object::to_a_scaled_int back to an Object::ref. It is not
intended to be used for any other int's.
This function is intended for optimized smallint
mathematics.
*/
static inline ref from_a_scaled_int(int x) {
return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag);
}
static inline ref nil(void) {
return ref();
}
static inline ref t(void) {
return ref(t_value);
}
/*-----------------------------------------------------------------------------
Tagged pointer checking
-----------------------------------------------------------------------------*/
static inline bool _is_nil(ref obj) {
return !obj;
}
static inline bool _is_t(ref obj) {
return obj.dat == t_value;
}
template<typename T>
static inline bool _is_a(ref obj) {
if(tag_traits<T>::tag != 0x0) {
return (obj.dat & tag_mask) == tag_traits<T>::tag;
} else {
return (obj.dat & tag_mask) == tag_traits<T>::tag
&& !_is_nil(obj) && !_is_t(obj);
}
}
/*-----------------------------------------------------------------------------
Tagged pointer referencing
-----------------------------------------------------------------------------*/
template<typename T>
static inline T _as_a(ref obj) {
#ifdef DEBUG
if(!_is_a<T>(obj)) {
throw_TypeError(obj,
"incorrect type for pointer"
);
}
#endif
intptr_t tmp = obj.dat;
return reinterpret_cast<T>(tmp - tag_traits<T>::tag);
/*use subtraction instead of masking, in order to
allow smart compilers to merge a field access with
the tag removal. i.e. the pointers are pointers to
structures, so they will be accessed via fields, and
in all probability those fields will be at some
offset from the actual structure address, meaning
that the processor itself will perform an addition
to access the field. The smart compiler can then
merge the addition of the field offset with the
subtraction of the tag.
*/
}
template<>
int _as_a<int>(ref obj) {
#ifdef DEBUG
if(!_is_a<int>(obj)) {
throw_TypeError(obj,
"incorrect type for small integer"
);
}
#endif
intptr_t tmp = obj.dat;
return (int)(tmp >> tag_bits);
}
template<>
UnicodeChar _as_a<UnicodeChar>(ref obj) {
uint32_t tmp = obj.dat;
return UnicodeChar(tmp >> tag_bits);
}
/*no checking, even in debug mode... achtung!*/
/*This function is used to convert a smallint Object::ref
to a useable int that is equal to the "real" int, shifted
to the left by the number of tag bits (i.e. scaled). It
should be used only for optimizing smallint math operations.
*/
static inline int to_a_scaled_int(ref obj) {
intptr_t tmp = obj.dat;
return (int)((tmp - tag_traits<int>::tag)>>tag_bits);
/*use subtraction instead of masking, again to
allow smart compilers to merge tag adding and
subtracting. For example the typical case would
be something like:
Object::ref result =
Object::from_a_scaled_int(
Object::to_a_scaled_int(a) +
Object::to_a_scaled_int(b)
);
The above case can be reduced by the compiler to:
intptr_t result =
(tag_traits<int>::tag +
a - tag_traits<int>::tag +
b - tag_traits<int>::tag
);
It can then do some maths and cancel out a tag:
intptr_t result = a + b - tag_traits<int>::tag;
*/
}
/*-----------------------------------------------------------------------------
Utility
-----------------------------------------------------------------------------*/
static inline size_t round_up_to_alignment(size_t x) {
return
(x & tag_mask) ? (x + alignment - (x & tag_mask)) :
/*otherwise*/ x ;
}
}
/*-----------------------------------------------------------------------------
Reflectors outside of the namespace
-----------------------------------------------------------------------------*/
template<typename T>
static inline bool is_a(Object::ref obj) {
return Object::_is_a<T>(obj);
}
template<typename T>
static inline T as_a(Object::ref obj) {
return Object::_as_a<T>(obj);
}
static inline bool is_nil(Object::ref obj) {
return Object::_is_nil(obj);
}
static inline bool is_t(Object::ref obj) {
return Object::_is_t(obj);
}
#endif //OBJECTS_H
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, 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.
*/
#ifndef TORRENT_ALLOCA
#include "libtorrent/config.hpp"
#ifdef TORRENT_WINDOWS
#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * n));
#else
#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * n));
#endif
#endif
<commit_msg>alloca macro fix<commit_after>/*
Copyright (c) 2008, 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.
*/
#ifndef TORRENT_ALLOCA
#include "libtorrent/config.hpp"
#ifdef TORRENT_WINDOWS
#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)));
#else
#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)));
#endif
#endif
<|endoftext|> |
<commit_before>//===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PathDiagnostic-related interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathDiagnostic.h"
#include "clang/AST/Expr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Casting.h"
#include <sstream>
using namespace clang;
using llvm::dyn_cast;
using llvm::isa;
bool PathDiagnosticMacroPiece::containsEvent() const {
for (const_iterator I = begin(), E = end(); I!=E; ++I) {
if (isa<PathDiagnosticEventPiece>(*I))
return true;
if (PathDiagnosticMacroPiece *MP = dyn_cast<PathDiagnosticMacroPiece>(*I))
if (MP->containsEvent())
return true;
}
return false;
}
static size_t GetNumCharsToLastNonPeriod(const char *s) {
const char *start = s;
const char *lastNonPeriod = 0;
for ( ; *s != '\0' ; ++s)
if (*s != '.') lastNonPeriod = s;
if (!lastNonPeriod)
return 0;
return (lastNonPeriod - start) + 1;
}
static inline size_t GetNumCharsToLastNonPeriod(const std::string &s) {
return s.empty () ? 0 : GetNumCharsToLastNonPeriod(&s[0]);
}
PathDiagnosticPiece::PathDiagnosticPiece(const std::string& s,
Kind k, DisplayHint hint)
: str(s, 0, GetNumCharsToLastNonPeriod(s)), kind(k), Hint(hint) {}
PathDiagnosticPiece::PathDiagnosticPiece(const char* s, Kind k,
DisplayHint hint)
: str(s, GetNumCharsToLastNonPeriod(s)), kind(k), Hint(hint) {}
PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
: kind(k), Hint(hint) {}
PathDiagnosticPiece::~PathDiagnosticPiece() {}
PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {
for (iterator I = begin(), E = end(); I != E; ++I) delete *I;
}
PathDiagnostic::PathDiagnostic() : Size(0) {}
PathDiagnostic::~PathDiagnostic() {
for (iterator I = begin(), E = end(); I != E; ++I) delete &*I;
}
void PathDiagnostic::resetPath(bool deletePieces) {
Size = 0;
if (deletePieces)
for (iterator I=begin(), E=end(); I!=E; ++I)
delete &*I;
path.clear();
}
PathDiagnostic::PathDiagnostic(const char* bugtype, const char* desc,
const char* category)
: Size(0),
BugType(bugtype, GetNumCharsToLastNonPeriod(bugtype)),
Desc(desc, GetNumCharsToLastNonPeriod(desc)),
Category(category, GetNumCharsToLastNonPeriod(category)) {}
PathDiagnostic::PathDiagnostic(const std::string& bugtype,
const std::string& desc,
const std::string& category)
: Size(0),
BugType(bugtype, 0, GetNumCharsToLastNonPeriod(bugtype)),
Desc(desc, 0, GetNumCharsToLastNonPeriod(desc)),
Category(category, 0, GetNumCharsToLastNonPeriod(category)) {}
void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info) {
// Create a PathDiagnostic with a single piece.
PathDiagnostic* D = new PathDiagnostic();
const char *LevelStr;
switch (DiagLevel) {
default:
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: LevelStr = "note: "; break;
case Diagnostic::Warning: LevelStr = "warning: "; break;
case Diagnostic::Error: LevelStr = "error: "; break;
case Diagnostic::Fatal: LevelStr = "fatal error: "; break;
}
llvm::SmallString<100> StrC;
StrC += LevelStr;
Info.FormatDiagnostic(StrC);
PathDiagnosticPiece *P =
new PathDiagnosticEventPiece(Info.getLocation(),
std::string(StrC.begin(), StrC.end()));
for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
P->addRange(Info.getRange(i));
for (unsigned i = 0, e = Info.getNumCodeModificationHints(); i != e; ++i)
P->addCodeModificationHint(Info.getCodeModificationHint(i));
D->push_front(P);
HandlePathDiagnostic(D);
}
//===----------------------------------------------------------------------===//
// PathDiagnosticLocation methods.
//===----------------------------------------------------------------------===//
FullSourceLoc PathDiagnosticLocation::asLocation() const {
switch (K) {
case SingleLoc:
case Range:
break;
case Statement:
return FullSourceLoc(S->getLocStart(), const_cast<SourceManager&>(SM));
}
return FullSourceLoc(R.getBegin(), const_cast<SourceManager&>(SM));
}
<commit_msg>Add comment.<commit_after>//===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PathDiagnostic-related interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathDiagnostic.h"
#include "clang/AST/Expr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Casting.h"
#include <sstream>
using namespace clang;
using llvm::dyn_cast;
using llvm::isa;
bool PathDiagnosticMacroPiece::containsEvent() const {
for (const_iterator I = begin(), E = end(); I!=E; ++I) {
if (isa<PathDiagnosticEventPiece>(*I))
return true;
if (PathDiagnosticMacroPiece *MP = dyn_cast<PathDiagnosticMacroPiece>(*I))
if (MP->containsEvent())
return true;
}
return false;
}
static size_t GetNumCharsToLastNonPeriod(const char *s) {
const char *start = s;
const char *lastNonPeriod = 0;
for ( ; *s != '\0' ; ++s)
if (*s != '.') lastNonPeriod = s;
if (!lastNonPeriod)
return 0;
return (lastNonPeriod - start) + 1;
}
static inline size_t GetNumCharsToLastNonPeriod(const std::string &s) {
return s.empty () ? 0 : GetNumCharsToLastNonPeriod(&s[0]);
}
PathDiagnosticPiece::PathDiagnosticPiece(const std::string& s,
Kind k, DisplayHint hint)
: str(s, 0, GetNumCharsToLastNonPeriod(s)), kind(k), Hint(hint) {}
PathDiagnosticPiece::PathDiagnosticPiece(const char* s, Kind k,
DisplayHint hint)
: str(s, GetNumCharsToLastNonPeriod(s)), kind(k), Hint(hint) {}
PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
: kind(k), Hint(hint) {}
PathDiagnosticPiece::~PathDiagnosticPiece() {}
PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {
for (iterator I = begin(), E = end(); I != E; ++I) delete *I;
}
PathDiagnostic::PathDiagnostic() : Size(0) {}
PathDiagnostic::~PathDiagnostic() {
for (iterator I = begin(), E = end(); I != E; ++I) delete &*I;
}
void PathDiagnostic::resetPath(bool deletePieces) {
Size = 0;
if (deletePieces)
for (iterator I=begin(), E=end(); I!=E; ++I)
delete &*I;
path.clear();
}
PathDiagnostic::PathDiagnostic(const char* bugtype, const char* desc,
const char* category)
: Size(0),
BugType(bugtype, GetNumCharsToLastNonPeriod(bugtype)),
Desc(desc, GetNumCharsToLastNonPeriod(desc)),
Category(category, GetNumCharsToLastNonPeriod(category)) {}
PathDiagnostic::PathDiagnostic(const std::string& bugtype,
const std::string& desc,
const std::string& category)
: Size(0),
BugType(bugtype, 0, GetNumCharsToLastNonPeriod(bugtype)),
Desc(desc, 0, GetNumCharsToLastNonPeriod(desc)),
Category(category, 0, GetNumCharsToLastNonPeriod(category)) {}
void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info) {
// Create a PathDiagnostic with a single piece.
PathDiagnostic* D = new PathDiagnostic();
const char *LevelStr;
switch (DiagLevel) {
default:
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: LevelStr = "note: "; break;
case Diagnostic::Warning: LevelStr = "warning: "; break;
case Diagnostic::Error: LevelStr = "error: "; break;
case Diagnostic::Fatal: LevelStr = "fatal error: "; break;
}
llvm::SmallString<100> StrC;
StrC += LevelStr;
Info.FormatDiagnostic(StrC);
PathDiagnosticPiece *P =
new PathDiagnosticEventPiece(Info.getLocation(),
std::string(StrC.begin(), StrC.end()));
for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
P->addRange(Info.getRange(i));
for (unsigned i = 0, e = Info.getNumCodeModificationHints(); i != e; ++i)
P->addCodeModificationHint(Info.getCodeModificationHint(i));
D->push_front(P);
HandlePathDiagnostic(D);
}
//===----------------------------------------------------------------------===//
// PathDiagnosticLocation methods.
//===----------------------------------------------------------------------===//
FullSourceLoc PathDiagnosticLocation::asLocation() const {
// Note that we want a 'switch' here so that the compiler can warn us in
// case we add more cases.
switch (K) {
case SingleLoc:
case Range:
break;
case Statement:
return FullSourceLoc(S->getLocStart(), const_cast<SourceManager&>(SM));
}
return FullSourceLoc(R.getBegin(), const_cast<SourceManager&>(SM));
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2005, 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.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATORS
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#define TORRENT_USE_ICONV 0
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#define TORRENT_USE_ICONV 0
#endif
#define TORRENT_HAS_FALLOCATE 0
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_ICONV 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif
#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif
#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>fixed typo in config relating to buffer debug builds<commit_after>/*
Copyright (c) 2005, 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.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
// ======= GCC =========
#if defined __GNUC__
# if __GNUC__ >= 3
# define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif
// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# endif
# endif
// ======= SUNPRO =========
#elif defined __SUNPRO_CC
# if __SUNPRO_CC >= 0x550
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __global
# endif
# endif
// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1
// ======= MSVC =========
#elif defined BOOST_MSVC
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)
#endif
// ======= PLATFORMS =========
// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#define TORRENT_USE_ICONV 0
// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#define TORRENT_USE_ICONV 0
#endif
#define TORRENT_HAS_FALLOCATE 0
// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0
// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0
// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_ICONV 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif
// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows
// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX
// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH
// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH
// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX
// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255
#endif
#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW
// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
#include <stdarg.h>
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
int ret = _vsnprintf(buf, len, fmt, lp);
va_end(lp);
if (ret < 0) { buf[len-1] = 0; ret = len-1; }
return ret;
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif
// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif
#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif
#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE
#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif
#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif
#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif
#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif
#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif
#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif
#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif
#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif
#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif
#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif
#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif
// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
&& !defined TORRENT_USE_CLOCK_GETTIME \
&& !defined TORRENT_USE_BOOST_DATE_TIME \
&& !defined TORRENT_USE_ECLOCK \
&& !defined TORRENT_USE_SYSTEM_TIME
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|> |
<commit_before>//===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PathDiagnostic-related interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathDiagnostic.h"
#include "llvm/ADT/SmallString.h"
#include <sstream>
using namespace clang;
PathDiagnostic::~PathDiagnostic() {
for (iterator I = begin(), E = end(); I != E; ++I) delete &*I;
}
void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info) {
// Create a PathDiagnostic with a single piece.
PathDiagnostic* D = new PathDiagnostic();
const char *LevelStr;
switch (DiagLevel) {
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: LevelStr = "note: "; break;
case Diagnostic::Warning: LevelStr = "warning: "; break;
case Diagnostic::Error: LevelStr = "error: "; break;
case Diagnostic::Fatal: LevelStr = "fatal error: "; break;
}
llvm::SmallString<100> StrC;
StrC += LevelStr;
Info.FormatDiagnostic(StrC);
PathDiagnosticPiece *P =
new PathDiagnosticPiece(Info.getLocation(),
std::string(StrC.begin(), StrC.end()));
for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
P->addRange(Info.getRange(i));
D->push_front(P);
HandlePathDiagnostic(D);
}
<commit_msg>Ensure that we assert if given an unhandled value.<commit_after>//===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PathDiagnostic-related interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathDiagnostic.h"
#include "llvm/ADT/SmallString.h"
#include <sstream>
using namespace clang;
PathDiagnostic::~PathDiagnostic() {
for (iterator I = begin(), E = end(); I != E; ++I) delete &*I;
}
void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info) {
// Create a PathDiagnostic with a single piece.
PathDiagnostic* D = new PathDiagnostic();
const char *LevelStr;
switch (DiagLevel) {
default:
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: LevelStr = "note: "; break;
case Diagnostic::Warning: LevelStr = "warning: "; break;
case Diagnostic::Error: LevelStr = "error: "; break;
case Diagnostic::Fatal: LevelStr = "fatal error: "; break;
}
llvm::SmallString<100> StrC;
StrC += LevelStr;
Info.FormatDiagnostic(StrC);
PathDiagnosticPiece *P =
new PathDiagnosticPiece(Info.getLocation(),
std::string(StrC.begin(), StrC.end()));
for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
P->addRange(Info.getRange(i));
D->push_front(P);
HandlePathDiagnostic(D);
}
<|endoftext|> |
<commit_before>#pragma once
#include <utility>
#include <type_traits>
#include "any.hpp"
#include <type_list.hpp>
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*generic_constructor_signature)(any*);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
}
namespace constructor_detail
{
template <class T, class... ParamTypes, std::size_t... Seq>
any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return constructor_dispatch<T, ParamTypes...>(argument_array,
param_sequence());
}
}
}
<commit_msg>Rename generic_constructor_signature to constructor_binding_signature. modified: include/reflection_binding.hpp<commit_after>#pragma once
#include <utility>
#include <type_traits>
#include "any.hpp"
#include <type_list.hpp>
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
}
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
}
namespace constructor_detail
{
template <class T, class... ParamTypes, std::size_t... Seq>
any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return constructor_dispatch<T, ParamTypes...>(argument_array,
param_sequence());
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <[email protected]>
//
// 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 <string>
#include <cmath>
#include <utils.hpp>
#include <Observation.hpp>
#ifndef SNR_HPP
#define SNR_HPP
namespace PulsarSearch {
class snrDedispersedConf {
public:
snrDedispersedConf();
~snrDedispersedConf();
// Get
unsigned int getNrDMsPerBlock() const;
unsigned int getNrDMsPerThread() const;
// Set
void setNrDMsPerBlock(unsigned int dms);
void setNrDMsPerThread(unsigned int dms);
// utils
std::string print() const;
private:
unsigned int nrDMsPerBlock;
unsigned int nrDMsPerThread;
};
class snrFoldedConf : public snrDedispersedConf {
public:
snrFoldedConf();
~snrFoldedConf();
// Get
unsigned int getNrPeriodsPerBlock() const;
unsigned int getNrPeriodsPerThread() const;
// Set
void setNrPeriodsPerBlock(unsigned int periods);
void setNrPeriodsPerThread(unsigned int periods);
// utils
std::string print() const;
private:
unsigned int nrPeriodsPerBlock;
unsigned int nrPeriodsPerThread;
};
// Sequential SNR
template< typename T > void snrDedispersed(const unsigned int second, const AstroData::Observation & observation, const std::vector< T > & dedispersed, std::vector< T > & maxS, std::vector< float > & meanS, std::vector< float > & rmsS);
template< typename T > void snrFolded(const AstroData::Observation & observation, const std::vector< T > & folded, std::vector< T > & snrs);
// OpenCL SNR
std::string * getSNRDedispersedOpenCL(const snrDedispersedConf & conf, const std::string & dataType, const AstroData::Observation & observation);
std::string * getSNRFoldedOpenCL(const snrFoldedConf & conf, const std::string & dataType, const AstroData::Observation & observation);
// Implementations
inline unsigned int snrDedispersedConf::getNrDMsPerBlock() const {
return nrDMsPerBlock;
}
inline unsigned int snrDedispersedConf::getNrDMsPerThread() const {
return nrDMsPerThread;
}
inline void snrDedispersedConf::setNrDMsPerBlock(unsigned int dms) {
nrDMsPerBlock = dms;
}
inline void snrDedispersedConf::setNrDMsPerThread(unsigned int dms) {
nrDMsPerThread = dms;
}
inline unsigned int snrFoldedConf::getNrPeriodsPerBlock() const {
return nrPeriodsPerBlock;
}
inline unsigned int snrFoldedConf::getNrPeriodsPerThread() const {
return nrPeriodsPerThread;
}
inline void snrFoldedConf::setNrPeriodsPerBlock(unsigned int periods) {
nrPeriodsPerBlock = periods;
}
inline void snrFoldedConf::setNrPeriodsPerThread(unsigned int periods) {
nrPeriodsPerThread = periods;
}
template< typename T > void snrDedispersed(const unsigned int second, const AstroData::Observation & observation, const std::vector< T > & dedispersed, std::vector< T > & maxS, std::vector< float > & meanS, std::vector< float > & rmsS) {
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
T max = 0;
float mean = 0.0f;
float rms = 0.0f;
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
T value = dedispersed[(dm * observation.getNrSamplesPerPaddedSecond()) + sample];
mean += value;
rms += (value * value);
if ( value > max ) {
max = value;
}
}
if ( max > maxS[dm] ) {
maxS[dm] = max;
}
meanS[dm] = ((meanS[dm] * observation.getNrSamplesPerSecond() * second) + mean) / (observation.getNrSamplesPerSecond() * (second + 1));
rmsS[dm] = ((rmsS[dm] * observation.getNrSamplesPerSecond() * second) + rms) / (observation.getNrSamplesPerSecond() * (second + 1));
}
}
template< typename T > void snrFolded(AstroData::Observation & observation, const std::vector< T > & folded, std::vector< T > & snrs) {
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
T max = 0;
float average = 0.0f;
float rms = 0.0f;
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
T value = folded[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm];
average += value;
rms += (value * value);
if ( value > max ) {
max = value;
}
}
average /= observation.getNrBins();
rms = std::sqrt(rms / observation.getNrBins());
snrs[(period * observation.getNrPaddedDMs()) + dm] = (max - average) / rms;
}
}
}
} // PulsarSearch
#endif // SNR_HPP
<commit_msg>Forgot one include.<commit_after>// Copyright 2014 Alessio Sclocco <[email protected]>
//
// 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 <vector>
#include <string>
#include <cmath>
#include <utils.hpp>
#include <Observation.hpp>
#ifndef SNR_HPP
#define SNR_HPP
namespace PulsarSearch {
class snrDedispersedConf {
public:
snrDedispersedConf();
~snrDedispersedConf();
// Get
unsigned int getNrDMsPerBlock() const;
unsigned int getNrDMsPerThread() const;
// Set
void setNrDMsPerBlock(unsigned int dms);
void setNrDMsPerThread(unsigned int dms);
// utils
std::string print() const;
private:
unsigned int nrDMsPerBlock;
unsigned int nrDMsPerThread;
};
class snrFoldedConf : public snrDedispersedConf {
public:
snrFoldedConf();
~snrFoldedConf();
// Get
unsigned int getNrPeriodsPerBlock() const;
unsigned int getNrPeriodsPerThread() const;
// Set
void setNrPeriodsPerBlock(unsigned int periods);
void setNrPeriodsPerThread(unsigned int periods);
// utils
std::string print() const;
private:
unsigned int nrPeriodsPerBlock;
unsigned int nrPeriodsPerThread;
};
// Sequential SNR
template< typename T > void snrDedispersed(const unsigned int second, const AstroData::Observation & observation, const std::vector< T > & dedispersed, std::vector< T > & maxS, std::vector< float > & meanS, std::vector< float > & rmsS);
template< typename T > void snrFolded(const AstroData::Observation & observation, const std::vector< T > & folded, std::vector< T > & snrs);
// OpenCL SNR
std::string * getSNRDedispersedOpenCL(const snrDedispersedConf & conf, const std::string & dataType, const AstroData::Observation & observation);
std::string * getSNRFoldedOpenCL(const snrFoldedConf & conf, const std::string & dataType, const AstroData::Observation & observation);
// Implementations
inline unsigned int snrDedispersedConf::getNrDMsPerBlock() const {
return nrDMsPerBlock;
}
inline unsigned int snrDedispersedConf::getNrDMsPerThread() const {
return nrDMsPerThread;
}
inline void snrDedispersedConf::setNrDMsPerBlock(unsigned int dms) {
nrDMsPerBlock = dms;
}
inline void snrDedispersedConf::setNrDMsPerThread(unsigned int dms) {
nrDMsPerThread = dms;
}
inline unsigned int snrFoldedConf::getNrPeriodsPerBlock() const {
return nrPeriodsPerBlock;
}
inline unsigned int snrFoldedConf::getNrPeriodsPerThread() const {
return nrPeriodsPerThread;
}
inline void snrFoldedConf::setNrPeriodsPerBlock(unsigned int periods) {
nrPeriodsPerBlock = periods;
}
inline void snrFoldedConf::setNrPeriodsPerThread(unsigned int periods) {
nrPeriodsPerThread = periods;
}
template< typename T > void snrDedispersed(const unsigned int second, const AstroData::Observation & observation, const std::vector< T > & dedispersed, std::vector< T > & maxS, std::vector< float > & meanS, std::vector< float > & rmsS) {
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
T max = 0;
float mean = 0.0f;
float rms = 0.0f;
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
T value = dedispersed[(dm * observation.getNrSamplesPerPaddedSecond()) + sample];
mean += value;
rms += (value * value);
if ( value > max ) {
max = value;
}
}
if ( max > maxS[dm] ) {
maxS[dm] = max;
}
meanS[dm] = ((meanS[dm] * observation.getNrSamplesPerSecond() * second) + mean) / (observation.getNrSamplesPerSecond() * (second + 1));
rmsS[dm] = ((rmsS[dm] * observation.getNrSamplesPerSecond() * second) + rms) / (observation.getNrSamplesPerSecond() * (second + 1));
}
}
template< typename T > void snrFolded(AstroData::Observation & observation, const std::vector< T > & folded, std::vector< T > & snrs) {
for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
T max = 0;
float average = 0.0f;
float rms = 0.0f;
for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
T value = folded[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + dm];
average += value;
rms += (value * value);
if ( value > max ) {
max = value;
}
}
average /= observation.getNrBins();
rms = std::sqrt(rms / observation.getNrBins());
snrs[(period * observation.getNrPaddedDMs()) + dm] = (max - average) / rms;
}
}
}
} // PulsarSearch
#endif // SNR_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <qt/askpassphrasedialog.h>
#include <qt/forms/ui_askpassphrasedialog.h>
#include <qt/guiconstants.h>
#include <qt/walletmodel.h>
#include <qt/styleSheet.h>
#include <wallet/wallet.h>
#include <support/allocators/secure.h>
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
AskPassphraseDialog::AskPassphraseDialog(Mode _mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(_mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
SetObjectStyleSheet(ui->buttonBox->button(QDialogButtonBox::Cancel), StyleSheetNames::ButtonWhite);
SetObjectStyleSheet(ui->buttonBox->button(QDialogButtonBox::Ok), StyleSheetNames::ButtonBlue);
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
ui->stakingCheckBox->hide();
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old passphrase and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->toggleShowPasswordButton, SIGNAL(toggled(bool)), this, SLOT(toggleShowPassword(bool)));
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *_model)
{
this->model = _model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR QTUMS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("%1 will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your qtums from being stolen by malware infecting your computer.").arg(tr(PACKAGE_NAME)) +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
model->setWalletUnlockStakingOnly(ui->stakingCheckBox->isChecked());
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
void AskPassphraseDialog::toggleShowPassword(bool show)
{
ui->toggleShowPasswordButton->setDown(show);
const auto mode = show ? QLineEdit::Normal : QLineEdit::Password;
ui->passEdit1->setEchoMode(mode);
ui->passEdit2->setEchoMode(mode);
ui->passEdit3->setEchoMode(mode);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
static void SecureClearQLineEdit(QLineEdit* edit)
{
// Attempt to overwrite text so that they do not linger around in memory
edit->setText(QString(" ").repeated(edit->text().size()));
edit->clear();
}
void AskPassphraseDialog::secureClearPassFields()
{
SecureClearQLineEdit(ui->passEdit1);
SecureClearQLineEdit(ui->passEdit2);
SecureClearQLineEdit(ui->passEdit3);
}
<commit_msg>Set the default value of the staking check box<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <qt/askpassphrasedialog.h>
#include <qt/forms/ui_askpassphrasedialog.h>
#include <qt/guiconstants.h>
#include <qt/walletmodel.h>
#include <qt/styleSheet.h>
#include <wallet/wallet.h>
#include <support/allocators/secure.h>
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
AskPassphraseDialog::AskPassphraseDialog(Mode _mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(_mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
SetObjectStyleSheet(ui->buttonBox->button(QDialogButtonBox::Cancel), StyleSheetNames::ButtonWhite);
SetObjectStyleSheet(ui->buttonBox->button(QDialogButtonBox::Ok), StyleSheetNames::ButtonBlue);
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
ui->stakingCheckBox->hide();
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old passphrase and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->toggleShowPasswordButton, SIGNAL(toggled(bool)), this, SLOT(toggleShowPassword(bool)));
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *_model)
{
this->model = _model;
if(model) ui->stakingCheckBox->setChecked(model->getWalletUnlockStakingOnly() || mode == UnlockStaking);
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR QTUMS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("%1 will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your qtums from being stolen by malware infecting your computer.").arg(tr(PACKAGE_NAME)) +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
model->setWalletUnlockStakingOnly(ui->stakingCheckBox->isChecked());
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
void AskPassphraseDialog::toggleShowPassword(bool show)
{
ui->toggleShowPasswordButton->setDown(show);
const auto mode = show ? QLineEdit::Normal : QLineEdit::Password;
ui->passEdit1->setEchoMode(mode);
ui->passEdit2->setEchoMode(mode);
ui->passEdit3->setEchoMode(mode);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
static void SecureClearQLineEdit(QLineEdit* edit)
{
// Attempt to overwrite text so that they do not linger around in memory
edit->setText(QString(" ").repeated(edit->text().size()));
edit->clear();
}
void AskPassphraseDialog::secureClearPassFields()
{
SecureClearQLineEdit(ui->passEdit1);
SecureClearQLineEdit(ui->passEdit2);
SecureClearQLineEdit(ui->passEdit3);
}
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <[email protected]>
//
// 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.
// TODO: add another dimension to the configuration: (device, DMs) -> (device, DMs, samples)
#include <vector>
#include <string>
#include <cmath>
#include <map>
#include <fstream>
#include <utils.hpp>
#ifndef SNR_HPP
#define SNR_HPP
namespace PulsarSearch {
class snrDMsSamplesConf {
public:
snrDMsSamplesConf();
~snrDMsSamplesConf();
// Get
unsigned int getNrSamplesPerBlock() const;
unsigned int getNrSamplesPerThread() const;
// Set
void setNrSamplesPerBlock(unsigned int samples);
void setNrSamplesPerThread(unsigned int samples);
// utils
std::string print() const;
private:
unsigned int nrSamplesPerBlock;
unsigned int nrSamplesPerThread;
};
typedef std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrDMsSamplesConf > > > tunedSNRDMsSamplesConf;
// OpenCL SNR
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrDMsSamplesConf & conf, const std::string & dataType, const unsigned int nrSamples, const unsigned int padding);
// Read configuration files
void readTunedSNRDMsSamplesConf(tunedSNRDMsSamplesConf & tunedSNR, const std::string & snrFilename);
// Implementations
inline unsigned int snrDMsSamplesConf::getNrSamplesPerBlock() const {
return nrSamplesPerBlock;
}
inline unsigned int snrDMsSamplesConf::getNrSamplesPerThread() const {
return nrSamplesPerThread;
}
inline void snrDMsSamplesConf::setNrSamplesPerBlock(unsigned int samples) {
nrSamplesPerBlock = samples;
}
inline void snrDMsSamplesConf::setNrSamplesPerThread(unsigned int samples) {
nrSamplesPerThread = samples;
}
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrDMsSamplesConf & conf, const std::string & dataType, const unsigned int nrSamples, const unsigned int padding) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void snrDMsSamples" + isa::utils::toString(nrSamples) + "(__global const " + dataType + " * const restrict dedispersedData, __global float * const restrict snrData) {\n"
"unsigned int dm = get_group_id(1);\n"
"float delta = 0.0f;\n"
"__local float reductionCOU[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"__local " + dataType + " reductionMAX[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"__local float reductionMEA[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"__local float reductionVAR[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"<%DEF%>"
"\n"
"// Compute phase\n"
"for ( unsigned int sample = get_local_id(0) + " + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + "; sample < " + isa::utils::toString(nrSamples) + "; sample += " + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + " ) {\n"
+ dataType + " item = 0;\n"
"<%COMPUTE%>"
"}\n"
"// In-thread reduce\n"
"<%REDUCE%>"
"// Local memory store\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"// Reduce phase\n"
"unsigned int threshold = " + isa::utils::toString(conf.getNrSamplesPerBlock() / 2) + ";\n"
"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold /= 2 ) {\n"
"if ( sample < threshold ) {\n"
"delta = reductionMEA[sample + threshold] - mean0;\n"
"counter0 += reductionCOU[sample + threshold];\n"
"max0 = fmax(max0, reductionMAX[sample + threshold]);\n"
"mean0 = ((reductionCOU[sample] * mean0) + (reductionCOU[sample + threshold] * reductionMEA[sample + threshold])) / counter0;\n"
"variance0 += reductionVAR[sample + threshold] + ((delta * delta) * ((reductionCOU[sample] * reductionCOU[sample + threshold]) / counter0));\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"}\n"
"// Store\n"
"if ( get_local_id(0) == 0 ) {\n"
"snrData[dm] = (max0 - mean0) / native_sqrt(variance0 * " + isa::utils::toString(1.0f / (nrSamples - 1)) + "f);\n"
"}\n"
"}\n";
std::string defTemplate = "float counter<%NUM%> = 1.0f;\n"
+ dataType + " max<%NUM%> = dedispersedData[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (get_local_id(0) + <%OFFSET%>)];\n"
"float variance<%NUM%> = 0.0f;\n"
"float mean<%NUM%> = max<%NUM%>;\n";
std::string computeTemplate = "item = dedispersedData[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (sample + <%OFFSET%>)];\n"
"counter<%NUM%> += 1.0f;\n"
"delta = item - mean<%NUM%>;\n"
"max<%NUM%> = fmax(max<%NUM%>, item);\n"
"mean<%NUM%> += delta / counter<%NUM%>;\n"
"variance<%NUM%> += delta * (item - mean<%NUM%>);\n";
std::string reduceTemplate = "delta = mean<%NUM%> - mean0;\n"
"counter0 += counter<%NUM%>;\n"
"max0 = fmax(max0, max<%NUM%>);\n"
"mean0 = (((counter0 - counter<%NUM%>) * mean0) + (counter<%NUM%> * mean<%NUM%>)) / counter0;\n"
"variance0 += variance<%NUM%> + ((delta * delta) * (((counter0 - counter<%NUM%>) * counter<%NUM%>) / counter0));\n";
// End kernel's template
std::string * def_s = new std::string();
std::string * compute_s = new std::string();
std::string * reduce_s = new std::string();
for ( unsigned int sample = 0; sample < conf.getNrSamplesPerThread(); sample++ ) {
std::string sample_s = isa::utils::toString(sample);
std::string offset_s = isa::utils::toString(conf.getNrSamplesPerBlock() * sample);
std::string * temp = 0;
temp = isa::utils::replace(&defTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
def_s->append(*temp);
delete temp;
temp = isa::utils::replace(&computeTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
compute_s->append(*temp);
delete temp;
if ( sample == 0 ) {
continue;
}
temp = isa::utils::replace(&reduceTemplate, "<%NUM%>", sample_s);
reduce_s->append(*temp);
delete temp;
}
code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
code = isa::utils::replace(code, "<%REDUCE%>", *reduce_s, true);
delete def_s;
delete compute_s;
delete reduce_s;
return code;
}
} // PulsarSearch
#endif // SNR_HPP
<commit_msg>TODO completed.<commit_after>// Copyright 2014 Alessio Sclocco <[email protected]>
//
// 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 <vector>
#include <string>
#include <cmath>
#include <map>
#include <fstream>
#include <utils.hpp>
#ifndef SNR_HPP
#define SNR_HPP
namespace PulsarSearch {
class snrDMsSamplesConf {
public:
snrDMsSamplesConf();
~snrDMsSamplesConf();
// Get
unsigned int getNrSamplesPerBlock() const;
unsigned int getNrSamplesPerThread() const;
// Set
void setNrSamplesPerBlock(unsigned int samples);
void setNrSamplesPerThread(unsigned int samples);
// utils
std::string print() const;
private:
unsigned int nrSamplesPerBlock;
unsigned int nrSamplesPerThread;
};
typedef std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrDMsSamplesConf > > > tunedSNRDMsSamplesConf;
// OpenCL SNR
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrDMsSamplesConf & conf, const std::string & dataType, const unsigned int nrSamples, const unsigned int padding);
// Read configuration files
void readTunedSNRDMsSamplesConf(tunedSNRDMsSamplesConf & tunedSNR, const std::string & snrFilename);
// Implementations
inline unsigned int snrDMsSamplesConf::getNrSamplesPerBlock() const {
return nrSamplesPerBlock;
}
inline unsigned int snrDMsSamplesConf::getNrSamplesPerThread() const {
return nrSamplesPerThread;
}
inline void snrDMsSamplesConf::setNrSamplesPerBlock(unsigned int samples) {
nrSamplesPerBlock = samples;
}
inline void snrDMsSamplesConf::setNrSamplesPerThread(unsigned int samples) {
nrSamplesPerThread = samples;
}
template< typename T > std::string * getSNRDMsSamplesOpenCL(const snrDMsSamplesConf & conf, const std::string & dataType, const unsigned int nrSamples, const unsigned int padding) {
std::string * code = new std::string();
// Begin kernel's template
*code = "__kernel void snrDMsSamples" + isa::utils::toString(nrSamples) + "(__global const " + dataType + " * const restrict dedispersedData, __global float * const restrict snrData) {\n"
"unsigned int dm = get_group_id(1);\n"
"float delta = 0.0f;\n"
"__local float reductionCOU[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"__local " + dataType + " reductionMAX[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"__local float reductionMEA[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"__local float reductionVAR[" + isa::utils::toString(isa::utils::pad(conf.getNrSamplesPerBlock(), padding / sizeof(T))) + "];\n"
"<%DEF%>"
"\n"
"// Compute phase\n"
"for ( unsigned int sample = get_local_id(0) + " + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + "; sample < " + isa::utils::toString(nrSamples) + "; sample += " + isa::utils::toString(conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) + " ) {\n"
+ dataType + " item = 0;\n"
"<%COMPUTE%>"
"}\n"
"// In-thread reduce\n"
"<%REDUCE%>"
"// Local memory store\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"// Reduce phase\n"
"unsigned int threshold = " + isa::utils::toString(conf.getNrSamplesPerBlock() / 2) + ";\n"
"for ( unsigned int sample = get_local_id(0); threshold > 0; threshold /= 2 ) {\n"
"if ( sample < threshold ) {\n"
"delta = reductionMEA[sample + threshold] - mean0;\n"
"counter0 += reductionCOU[sample + threshold];\n"
"max0 = fmax(max0, reductionMAX[sample + threshold]);\n"
"mean0 = ((reductionCOU[sample] * mean0) + (reductionCOU[sample + threshold] * reductionMEA[sample + threshold])) / counter0;\n"
"variance0 += reductionVAR[sample + threshold] + ((delta * delta) * ((reductionCOU[sample] * reductionCOU[sample + threshold]) / counter0));\n"
"reductionCOU[get_local_id(0)] = counter0;\n"
"reductionMAX[get_local_id(0)] = max0;\n"
"reductionMEA[get_local_id(0)] = mean0;\n"
"reductionVAR[get_local_id(0)] = variance0;\n"
"}\n"
"barrier(CLK_LOCAL_MEM_FENCE);\n"
"}\n"
"// Store\n"
"if ( get_local_id(0) == 0 ) {\n"
"snrData[dm] = (max0 - mean0) / native_sqrt(variance0 * " + isa::utils::toString(1.0f / (nrSamples - 1)) + "f);\n"
"}\n"
"}\n";
std::string defTemplate = "float counter<%NUM%> = 1.0f;\n"
+ dataType + " max<%NUM%> = dedispersedData[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (get_local_id(0) + <%OFFSET%>)];\n"
"float variance<%NUM%> = 0.0f;\n"
"float mean<%NUM%> = max<%NUM%>;\n";
std::string computeTemplate = "item = dedispersedData[(dm * " + isa::utils::toString(isa::utils::pad(nrSamples, padding / sizeof(T))) + ") + (sample + <%OFFSET%>)];\n"
"counter<%NUM%> += 1.0f;\n"
"delta = item - mean<%NUM%>;\n"
"max<%NUM%> = fmax(max<%NUM%>, item);\n"
"mean<%NUM%> += delta / counter<%NUM%>;\n"
"variance<%NUM%> += delta * (item - mean<%NUM%>);\n";
std::string reduceTemplate = "delta = mean<%NUM%> - mean0;\n"
"counter0 += counter<%NUM%>;\n"
"max0 = fmax(max0, max<%NUM%>);\n"
"mean0 = (((counter0 - counter<%NUM%>) * mean0) + (counter<%NUM%> * mean<%NUM%>)) / counter0;\n"
"variance0 += variance<%NUM%> + ((delta * delta) * (((counter0 - counter<%NUM%>) * counter<%NUM%>) / counter0));\n";
// End kernel's template
std::string * def_s = new std::string();
std::string * compute_s = new std::string();
std::string * reduce_s = new std::string();
for ( unsigned int sample = 0; sample < conf.getNrSamplesPerThread(); sample++ ) {
std::string sample_s = isa::utils::toString(sample);
std::string offset_s = isa::utils::toString(conf.getNrSamplesPerBlock() * sample);
std::string * temp = 0;
temp = isa::utils::replace(&defTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
def_s->append(*temp);
delete temp;
temp = isa::utils::replace(&computeTemplate, "<%NUM%>", sample_s);
if ( sample == 0 ) {
std::string empty_s("");
temp = isa::utils::replace(temp, " + <%OFFSET%>", empty_s, true);
} else {
temp = isa::utils::replace(temp, "<%OFFSET%>", offset_s, true);
}
compute_s->append(*temp);
delete temp;
if ( sample == 0 ) {
continue;
}
temp = isa::utils::replace(&reduceTemplate, "<%NUM%>", sample_s);
reduce_s->append(*temp);
delete temp;
}
code = isa::utils::replace(code, "<%DEF%>", *def_s, true);
code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);
code = isa::utils::replace(code, "<%REDUCE%>", *reduce_s, true);
delete def_s;
delete compute_s;
delete reduce_s;
return code;
}
} // PulsarSearch
#endif // SNR_HPP
<|endoftext|> |
<commit_before>#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0xFE };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x02 };
char data[255];
};
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<commit_msg>Fix message IDs.<commit_after>#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
char data[255];
};
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<|endoftext|> |
<commit_before>//===- include/seec/Clang/Compile.hpp -------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file SeeC Clang usage helpers.
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_CLANG_COMPILE_HPP
#define SEEC_CLANG_COMPILE_HPP
#include "seec/Util/Error.hpp"
#include "seec/Util/Maybe.hpp"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/CodeGen/BackendUtil.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace clang {
class ASTDeserializationListener;
class ASTMutationListener;
class CompilerInstance;
class CXXRecordDecl;
class Decl;
class FunctionDecl;
class Stmt;
class TagDecl;
}
namespace llvm {
class LLVMContext;
}
namespace seec {
namespace seec_clang {
class SeeCCodeGenAction : public clang::CodeGenAction {
char const * const *ArgBegin;
char const * const *ArgEnd;
clang::CompilerInstance *Compiler;
std::string File;
uint64_t NextDeclIndex;
uint64_t NextStmtIndex;
llvm::DenseMap<clang::Decl const *, uint64_t> DeclMap;
llvm::DenseMap<clang::Stmt const *, uint64_t> StmtMap;
public:
SeeCCodeGenAction(const char * const *WithArgBegin,
const char * const *WithArgEnd,
unsigned _Action,
llvm::LLVMContext *_VMContext = 0)
: CodeGenAction(_Action, _VMContext),
ArgBegin(WithArgBegin),
ArgEnd(WithArgEnd),
Compiler(nullptr),
NextDeclIndex(0),
NextStmtIndex(0),
DeclMap(),
StmtMap()
{}
virtual
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &CI, llvm::StringRef InFile);
virtual void ModuleComplete(llvm::Module *Mod);
void addDeclMap(clang::Decl const *D) {
if (!DeclMap.count(D))
DeclMap.insert(std::make_pair(D, NextDeclIndex++));
}
void addStmtMap(clang::Stmt const *S) {
if (!StmtMap.count(S))
StmtMap.insert(std::make_pair(S, NextStmtIndex++));
}
decltype(DeclMap) const &getDeclMap() { return DeclMap; }
decltype(StmtMap) const &getStmtMap() { return StmtMap; }
};
class SeeCEmitAssemblyAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitAssemblyAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitBCAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitBCAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitLLVMAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitLLVMAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitLLVMOnlyAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitLLVMOnlyAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitCodeGenOnlyAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitCodeGenOnlyAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitObjAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitObjAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCASTConsumer
: public clang::ASTConsumer,
public clang::RecursiveASTVisitor<SeeCASTConsumer>
{
SeeCCodeGenAction &Action;
std::unique_ptr<clang::ASTConsumer> Child;
std::vector<clang::VariableArrayType *> VATypes;
public:
SeeCASTConsumer(SeeCCodeGenAction &Action,
std::unique_ptr<clang::ASTConsumer> Child)
: Action(Action),
Child(std::move(Child)),
VATypes()
{}
virtual ~SeeCASTConsumer();
/// \name ASTConsumer Methods
/// \{
virtual void Initialize(clang::ASTContext &Context) {
Child->Initialize(Context);
}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef D);
virtual void HandleInterestingDecl(clang::DeclGroupRef D) {
HandleTopLevelDecl(D);
}
virtual void HandleTranslationUnit(clang::ASTContext &Ctx);
virtual void HandleTagDeclDefinition(clang::TagDecl *D) {
Child->HandleTagDeclDefinition(D);
}
virtual void HandleCXXImplicitFunctionInstantiation(clang::FunctionDecl *D){
Child->HandleCXXImplicitFunctionInstantiation(D);
}
virtual void HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef D) {
Child->HandleTopLevelDeclInObjCContainer(D);
}
virtual void CompleteTentativeDefinition(clang::VarDecl *D) {
Child->CompleteTentativeDefinition(D);
}
virtual void HandleVTable(clang::CXXRecordDecl *D, bool DefinitionRequired){
Child->HandleVTable(D, DefinitionRequired);
}
virtual clang::ASTMutationListener *GetASTMutationListener() {
return Child->GetASTMutationListener();
}
virtual clang::ASTDeserializationListener *GetASTDeserializationListener() {
return Child->GetASTDeserializationListener();
}
virtual void PrintStats() {
Child->PrintStats();
}
/// \}
/// RecursiveASTVisitor Methods
/// \{
bool VisitStmt(clang::Stmt *S);
bool VisitDecl(clang::Decl *D);
bool VisitVariableArrayType(::clang::VariableArrayType *T);
/// \}
};
/// \brief Find the resources directory.
///
std::string getResourcesDirectory(llvm::StringRef ExecutablePath);
/// \brief Find the runtime library directory.
///
std::string getRuntimeLibraryDirectory(llvm::StringRef ExecutablePath);
/// \brief Make all SeeC-Clang mapping information in Mod serializable.
///
void GenerateSerializableMappings(SeeCCodeGenAction &Action,
llvm::Module *Mod,
clang::SourceManager &SM,
llvm::StringRef MainFilename);
/// \brief Store all source files in SrcManager into the given llvm::Module.
///
void StoreCompileInformationInModule(llvm::Module *Mod,
clang::CompilerInstance &Compiler,
const char * const *ArgBegin,
const char * const *ArgEnd);
} // namespace clang (in seec)
} // namespace seec
#endif // SEEC_CLANG_COMPILE_HPP
<commit_msg>Update SeeCASTConsumer.<commit_after>//===- include/seec/Clang/Compile.hpp -------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file SeeC Clang usage helpers.
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_CLANG_COMPILE_HPP
#define SEEC_CLANG_COMPILE_HPP
#include "seec/Util/Error.hpp"
#include "seec/Util/Maybe.hpp"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/CodeGen/BackendUtil.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace clang {
class ASTDeserializationListener;
class ASTMutationListener;
class CompilerInstance;
class CXXRecordDecl;
class Decl;
class FunctionDecl;
class Stmt;
class TagDecl;
}
namespace llvm {
class LLVMContext;
}
namespace seec {
namespace seec_clang {
class SeeCCodeGenAction : public clang::CodeGenAction {
char const * const *ArgBegin;
char const * const *ArgEnd;
clang::CompilerInstance *Compiler;
std::string File;
uint64_t NextDeclIndex;
uint64_t NextStmtIndex;
llvm::DenseMap<clang::Decl const *, uint64_t> DeclMap;
llvm::DenseMap<clang::Stmt const *, uint64_t> StmtMap;
public:
SeeCCodeGenAction(const char * const *WithArgBegin,
const char * const *WithArgEnd,
unsigned _Action,
llvm::LLVMContext *_VMContext = 0)
: CodeGenAction(_Action, _VMContext),
ArgBegin(WithArgBegin),
ArgEnd(WithArgEnd),
Compiler(nullptr),
NextDeclIndex(0),
NextStmtIndex(0),
DeclMap(),
StmtMap()
{}
virtual
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &CI, llvm::StringRef InFile)
override;
virtual void ModuleComplete(llvm::Module *Mod) override;
void addDeclMap(clang::Decl const *D) {
if (!DeclMap.count(D))
DeclMap.insert(std::make_pair(D, NextDeclIndex++));
}
void addStmtMap(clang::Stmt const *S) {
if (!StmtMap.count(S))
StmtMap.insert(std::make_pair(S, NextStmtIndex++));
}
decltype(DeclMap) const &getDeclMap() { return DeclMap; }
decltype(StmtMap) const &getStmtMap() { return StmtMap; }
};
class SeeCEmitAssemblyAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitAssemblyAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitBCAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitBCAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitLLVMAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitLLVMAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitLLVMOnlyAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitLLVMOnlyAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitCodeGenOnlyAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitCodeGenOnlyAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCEmitObjAction : public SeeCCodeGenAction {
virtual void anchor();
public:
SeeCEmitObjAction(const char * const *ArgBegin,
const char * const *ArgEnd,
llvm::LLVMContext *_VMContext = 0);
};
class SeeCASTConsumer
: public clang::ASTConsumer,
public clang::RecursiveASTVisitor<SeeCASTConsumer>
{
SeeCCodeGenAction &Action;
std::unique_ptr<clang::ASTConsumer> Child;
std::vector<clang::VariableArrayType *> VATypes;
public:
SeeCASTConsumer(SeeCCodeGenAction &Action,
std::unique_ptr<clang::ASTConsumer> Child)
: Action(Action),
Child(std::move(Child)),
VATypes()
{}
virtual ~SeeCASTConsumer() override;
/// \name ASTConsumer Methods
/// \{
virtual void Initialize(clang::ASTContext &Context) override {
Child->Initialize(Context);
}
virtual bool HandleTopLevelDecl(clang::DeclGroupRef D) override;
virtual void HandleInlineMethodDefinition(clang::CXXMethodDecl *D) override {
Child->HandleInlineMethodDefinition(D);
}
virtual void HandleInterestingDecl(clang::DeclGroupRef D) override {
HandleTopLevelDecl(D);
}
virtual void HandleTranslationUnit(clang::ASTContext &Ctx) override;
virtual void HandleTagDeclDefinition(clang::TagDecl *D) override {
Child->HandleTagDeclDefinition(D);
}
virtual void HandleTagDeclRequiredDefinition(clang::TagDecl const *D) override
{
Child->HandleTagDeclRequiredDefinition(D);
}
virtual void HandleCXXImplicitFunctionInstantiation(clang::FunctionDecl *D)
override
{
Child->HandleCXXImplicitFunctionInstantiation(D);
}
virtual void HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef D) override
{
Child->HandleTopLevelDeclInObjCContainer(D);
}
virtual void HandleImplicitImportDecl(clang::ImportDecl *D) override {
Child->HandleImplicitImportDecl(D);
}
virtual void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
Child->HandleLinkerOptionPragma(Opts);
}
virtual void HandleDetectMismatch(llvm::StringRef Name,
llvm::StringRef Value) override {
Child->HandleDetectMismatch(Name, Value);
}
virtual void HandleDependentLibrary(llvm::StringRef Lib) override {
Child->HandleDependentLibrary(Lib);
}
virtual void CompleteTentativeDefinition(clang::VarDecl *D) {
Child->CompleteTentativeDefinition(D);
}
virtual void HandleCXXStaticMemberVarInstantiation(clang::VarDecl *D) override
{
Child->HandleCXXStaticMemberVarInstantiation(D);
}
virtual void HandleVTable(clang::CXXRecordDecl *D, bool DefinitionRequired){
Child->HandleVTable(D, DefinitionRequired);
}
virtual clang::ASTMutationListener *GetASTMutationListener() override {
return Child->GetASTMutationListener();
}
virtual clang::ASTDeserializationListener *GetASTDeserializationListener()
override
{
return Child->GetASTDeserializationListener();
}
virtual void PrintStats() override {
Child->PrintStats();
}
virtual bool shouldSkipFunctionBody(clang::Decl *D) override {
return Child->shouldSkipFunctionBody(D);
}
/// \}
/// RecursiveASTVisitor Methods
/// \{
bool VisitStmt(clang::Stmt *S);
bool VisitDecl(clang::Decl *D);
bool VisitVariableArrayType(::clang::VariableArrayType *T);
/// \}
};
/// \brief Find the resources directory.
///
std::string getResourcesDirectory(llvm::StringRef ExecutablePath);
/// \brief Find the runtime library directory.
///
std::string getRuntimeLibraryDirectory(llvm::StringRef ExecutablePath);
/// \brief Make all SeeC-Clang mapping information in Mod serializable.
///
void GenerateSerializableMappings(SeeCCodeGenAction &Action,
llvm::Module *Mod,
clang::SourceManager &SM,
llvm::StringRef MainFilename);
/// \brief Store all source files in SrcManager into the given llvm::Module.
///
void StoreCompileInformationInModule(llvm::Module *Mod,
clang::CompilerInstance &Compiler,
const char * const *ArgBegin,
const char * const *ArgEnd);
} // namespace clang (in seec)
} // namespace seec
#endif // SEEC_CLANG_COMPILE_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include <QGraphicsDropShadowEffect>
#include "guiconstants.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "qt/pivx/qtutils.h"
#include "qt/pivx/loadingdialog.h"
#include "qt/pivx/defaultdialog.h"
#include "qt/pivx/PIVXGUI.h"
#include <QDebug>
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
#include <QWidget>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(model),
context(context),
fCapsLock(false),
btnWatch(new QCheckBox())
{
ui->setupUi(this);
this->setStyleSheet(GUIUtil::loadStyleSheet());
ui->left->setProperty("cssClass", "container-dialog");
ui->labelTitle->setText("Change passphrase");
ui->labelTitle->setProperty("cssClass", "text-title-screen");
ui->warningLabel->setProperty("cssClass", "text-subtitle");
ui->btnEsc->setText("");
ui->btnEsc->setProperty("cssClass", "ic-close");
ui->pushButtonOk->setText("OK");
ui->pushButtonOk->setProperty("cssClass", "btn-primary");
initCssEditLine(ui->passEdit1);
initCssEditLine(ui->passEdit2);
initCssEditLine(ui->passEdit3);
ui->passLabel1->setText("Current passphrase");
ui->passLabel1->setProperty("cssClass", "text-title");
ui->passLabel2->setText("New passphrase");
ui->passLabel2->setProperty("cssClass", "text-title");
ui->passLabel3->setText("Repeat passphrase");
ui->passLabel3->setProperty("cssClass", "text-title");
ui->capsLabel->setVisible(false);
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
setShadow(ui->layoutEdit);
setShadow(ui->layoutEdit2);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
this->model = model;
QString title;
switch (mode) {
case Mode::Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->layoutEdit->hide();
title = tr("Encrypt wallet");
initWatch(ui->layoutEdit2);
break;
case Mode::UnlockAnonymize:
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->layoutEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
title = tr("Unlock wallet\nfor staking");
initWatch(ui->layoutEdit);
break;
case Mode::Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->layoutEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
title = tr("Unlock wallet");
initWatch(ui->layoutEdit);
break;
case Mode::Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->layoutEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
title = tr("Decrypt wallet");
initWatch(ui->layoutEdit);
break;
case Mode::ChangePass: // Ask old passphrase + new passphrase x2
title = tr("Change passphrase");
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
initWatch(ui->layoutEdit);
break;
}
ui->labelTitle->setText(title);
textChanged();
connect(btnWatch, SIGNAL(clicked()), this, SLOT(onWatchClicked()));
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->pushButtonOk, SIGNAL(clicked()), this, SLOT(accept()));
connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(close()));
}
void AskPassphraseDialog::onWatchClicked(){
int state = btnWatch->checkState();
ui->passEdit3->setEchoMode(state == Qt::Checked ? QLineEdit::Normal : QLineEdit::Password );
ui->passEdit2->setEchoMode(state== Qt::Checked ? QLineEdit::Normal : QLineEdit::Password );
ui->passEdit1->setEchoMode(state == Qt::Checked ? QLineEdit::Normal : QLineEdit::Password );
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if (!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch (mode) {
case Mode::Encrypt: {
if (newpass1.empty() || newpass2.empty()) {
// Cannot encrypt with empty passphrase
break;
}
hide();
bool ret = openStandardDialog(
tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR PIV</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
tr("ENCRYPT"), tr("CANCEL")
);
if (ret) {
if (newpass1 == newpass2) {
newpassCache = newpass1;
PIVXGUI* window = static_cast<PIVXGUI*>(parentWidget());
LoadingDialog *dialog = new LoadingDialog(window);
dialog->execute(this, 1);
openDialogWithOpaqueBackgroundFullScreen(dialog, window);
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
} else {
QDialog::reject(); // Cancelled
}
} break;
case Mode::UnlockAnonymize:
if (!model->setWalletLocked(false, oldpass, true)) {
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::Unlock:
if (!model->setWalletLocked(false, oldpass, false)) {
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::Decrypt:
if (!model->setWalletEncrypted(false, oldpass)) {
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::ChangePass:
if (newpass1 == newpass2) {
if (model->changePassphrase(oldpass, newpass1)) {
hide();
openStandardDialog(tr("Wallet encrypted"),tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch (mode) {
case Mode::Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Mode::UnlockAnonymize: // Old passphrase x1
case Mode::Unlock: // Old passphrase x1
case Mode::Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case Mode::ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->pushButtonOk->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent* event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
ui->capsLabel->setVisible(true);
} else {
ui->capsLabel->clear();
ui->capsLabel->setVisible(false);
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject* object, QEvent* event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar* psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
ui->capsLabel->setVisible(true);
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
ui->capsLabel->setVisible(false);
}
}
}
return QDialog::eventFilter(object, event);
}
bool AskPassphraseDialog::openStandardDialog(QString title, QString body, QString okBtn, QString cancelBtn){
PIVXGUI* gui = static_cast<PIVXGUI*>(parentWidget());
DefaultDialog *confirmDialog = new DefaultDialog(gui);
confirmDialog->setText(title, body, okBtn, cancelBtn);
confirmDialog->adjustSize();
openDialogWithOpaqueBackground(confirmDialog, gui);
bool ret = confirmDialog->isOk;
confirmDialog->deleteLater();
return ret;
}
void AskPassphraseDialog::warningMessage() {
hide();
openStandardDialog(
tr("Wallet encrypted"),
"<qt>" +
tr("PIVX will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your PIVs from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>",
tr("OK")
);
QApplication::quit();
}
void AskPassphraseDialog::errorEncryptingWallet() {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
void AskPassphraseDialog::run(int type){
if (type == 1) {
if (!newpassCache.empty()) {
QMetaObject::invokeMethod(this, "hide", Qt::QueuedConnection);
if (model->setWalletEncrypted(true, newpassCache)) {
QMetaObject::invokeMethod(this, "warningMessage", Qt::QueuedConnection);
} else {
QMetaObject::invokeMethod(this, "errorEncryptingWallet", Qt::QueuedConnection);
}
newpassCache.clear();
QDialog::accept(); // Success
}
}
}
void AskPassphraseDialog::onError(int type, QString error){
newpassCache = "";
}
void AskPassphraseDialog::initWatch(QWidget *parent) {
btnWatch = new QCheckBox(parent);
setCssProperty(btnWatch, "btn-watch-password");
btnWatch->setChecked(false);
QSize BUTTON_CONTACT_SIZE = QSize(24, 24);
btnWatch->setMinimumSize(BUTTON_CONTACT_SIZE);
btnWatch->setMaximumSize(BUTTON_CONTACT_SIZE);
btnWatch->show();
btnWatch->raise();
int posYY = 8;
btnWatch->move(450, posYY);
}<commit_msg>[GUI] AskPassphraseDialog, missing opaque background on dialog popup added.<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include <QGraphicsDropShadowEffect>
#include "guiconstants.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "qt/pivx/qtutils.h"
#include "qt/pivx/loadingdialog.h"
#include "qt/pivx/defaultdialog.h"
#include "qt/pivx/PIVXGUI.h"
#include <QDebug>
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
#include <QWidget>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(model),
context(context),
fCapsLock(false),
btnWatch(new QCheckBox())
{
ui->setupUi(this);
this->setStyleSheet(GUIUtil::loadStyleSheet());
ui->left->setProperty("cssClass", "container-dialog");
ui->labelTitle->setText("Change passphrase");
ui->labelTitle->setProperty("cssClass", "text-title-screen");
ui->warningLabel->setProperty("cssClass", "text-subtitle");
ui->btnEsc->setText("");
ui->btnEsc->setProperty("cssClass", "ic-close");
ui->pushButtonOk->setText("OK");
ui->pushButtonOk->setProperty("cssClass", "btn-primary");
initCssEditLine(ui->passEdit1);
initCssEditLine(ui->passEdit2);
initCssEditLine(ui->passEdit3);
ui->passLabel1->setText("Current passphrase");
ui->passLabel1->setProperty("cssClass", "text-title");
ui->passLabel2->setText("New passphrase");
ui->passLabel2->setProperty("cssClass", "text-title");
ui->passLabel3->setText("Repeat passphrase");
ui->passLabel3->setProperty("cssClass", "text-title");
ui->capsLabel->setVisible(false);
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
setShadow(ui->layoutEdit);
setShadow(ui->layoutEdit2);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
this->model = model;
QString title;
switch (mode) {
case Mode::Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->layoutEdit->hide();
title = tr("Encrypt wallet");
initWatch(ui->layoutEdit2);
break;
case Mode::UnlockAnonymize:
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->layoutEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
title = tr("Unlock wallet\nfor staking");
initWatch(ui->layoutEdit);
break;
case Mode::Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->layoutEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
title = tr("Unlock wallet");
initWatch(ui->layoutEdit);
break;
case Mode::Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->layoutEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
title = tr("Decrypt wallet");
initWatch(ui->layoutEdit);
break;
case Mode::ChangePass: // Ask old passphrase + new passphrase x2
title = tr("Change passphrase");
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
initWatch(ui->layoutEdit);
break;
}
ui->labelTitle->setText(title);
textChanged();
connect(btnWatch, SIGNAL(clicked()), this, SLOT(onWatchClicked()));
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->pushButtonOk, SIGNAL(clicked()), this, SLOT(accept()));
connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(close()));
}
void AskPassphraseDialog::onWatchClicked(){
int state = btnWatch->checkState();
ui->passEdit3->setEchoMode(state == Qt::Checked ? QLineEdit::Normal : QLineEdit::Password );
ui->passEdit2->setEchoMode(state== Qt::Checked ? QLineEdit::Normal : QLineEdit::Password );
ui->passEdit1->setEchoMode(state == Qt::Checked ? QLineEdit::Normal : QLineEdit::Password );
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if (!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch (mode) {
case Mode::Encrypt: {
if (newpass1.empty() || newpass2.empty()) {
// Cannot encrypt with empty passphrase
break;
}
hide();
bool ret = openStandardDialog(
tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR PIV</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
tr("ENCRYPT"), tr("CANCEL")
);
if (ret) {
if (newpass1 == newpass2) {
newpassCache = newpass1;
PIVXGUI* window = static_cast<PIVXGUI*>(parentWidget());
LoadingDialog *dialog = new LoadingDialog(window);
dialog->execute(this, 1);
openDialogWithOpaqueBackgroundFullScreen(dialog, window);
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
} else {
QDialog::reject(); // Cancelled
}
} break;
case Mode::UnlockAnonymize:
if (!model->setWalletLocked(false, oldpass, true)) {
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::Unlock:
if (!model->setWalletLocked(false, oldpass, false)) {
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::Decrypt:
if (!model->setWalletEncrypted(false, oldpass)) {
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::ChangePass:
if (newpass1 == newpass2) {
if (model->changePassphrase(oldpass, newpass1)) {
hide();
openStandardDialog(tr("Wallet encrypted"),tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch (mode) {
case Mode::Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Mode::UnlockAnonymize: // Old passphrase x1
case Mode::Unlock: // Old passphrase x1
case Mode::Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case Mode::ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->pushButtonOk->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent* event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
ui->capsLabel->setVisible(true);
} else {
ui->capsLabel->clear();
ui->capsLabel->setVisible(false);
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject* object, QEvent* event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar* psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
ui->capsLabel->setVisible(true);
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
ui->capsLabel->setVisible(false);
}
}
}
return QDialog::eventFilter(object, event);
}
bool AskPassphraseDialog::openStandardDialog(QString title, QString body, QString okBtn, QString cancelBtn){
PIVXGUI* gui = static_cast<PIVXGUI*>(parentWidget());
DefaultDialog *confirmDialog = new DefaultDialog(gui);
confirmDialog->setText(title, body, okBtn, cancelBtn);
confirmDialog->adjustSize();
openDialogWithOpaqueBackground(confirmDialog, gui);
bool ret = confirmDialog->isOk;
confirmDialog->deleteLater();
return ret;
}
void AskPassphraseDialog::warningMessage() {
hide();
static_cast<PIVXGUI*>(parentWidget())->showHide(true);
openStandardDialog(
tr("Wallet encrypted"),
"<qt>" +
tr("PIVX will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your PIVs from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>",
tr("OK")
);
QApplication::quit();
}
void AskPassphraseDialog::errorEncryptingWallet() {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
void AskPassphraseDialog::run(int type){
if (type == 1) {
if (!newpassCache.empty()) {
QMetaObject::invokeMethod(this, "hide", Qt::QueuedConnection);
if (model->setWalletEncrypted(true, newpassCache)) {
QMetaObject::invokeMethod(this, "warningMessage", Qt::QueuedConnection);
} else {
QMetaObject::invokeMethod(this, "errorEncryptingWallet", Qt::QueuedConnection);
}
newpassCache.clear();
QDialog::accept(); // Success
}
}
}
void AskPassphraseDialog::onError(int type, QString error){
newpassCache = "";
}
void AskPassphraseDialog::initWatch(QWidget *parent) {
btnWatch = new QCheckBox(parent);
setCssProperty(btnWatch, "btn-watch-password");
btnWatch->setChecked(false);
QSize BUTTON_CONTACT_SIZE = QSize(24, 24);
btnWatch->setMinimumSize(BUTTON_CONTACT_SIZE);
btnWatch->setMaximumSize(BUTTON_CONTACT_SIZE);
btnWatch->show();
btnWatch->raise();
int posYY = 8;
btnWatch->move(450, posYY);
}<|endoftext|> |
<commit_before>#include <qt/delegationitemmodel.h>
#include <qt/walletmodel.h>
#include <interfaces/wallet.h>
#include <validation.h>
#include <qt/bitcoinunits.h>
#include <interfaces/node.h>
#include <interfaces/handler.h>
#include <algorithm>
#include <QDateTime>
#include <QFont>
#include <QDebug>
#include <QThread>
class DelegationItemEntry
{
public:
DelegationItemEntry()
{}
DelegationItemEntry(const interfaces::DelegationInfo &delegationInfo)
{
hash = delegationInfo.hash;
createTime.setTime_t(delegationInfo.time);
delegateAddress = QString::fromStdString(delegationInfo.delegate_address);
stakerAddress = QString::fromStdString(delegationInfo.staker_address);
fee = delegationInfo.fee;
blockNumber = delegationInfo.block_number;
createTxHash = delegationInfo.create_tx_hash;
removeTxHash = delegationInfo.remove_tx_hash;
}
DelegationItemEntry( const DelegationItemEntry &obj)
{
hash = obj.hash;
createTime = obj.createTime;
delegateAddress = obj.delegateAddress;
stakerAddress = obj.stakerAddress;
fee = obj.fee;
blockNumber = obj.blockNumber;
createTxHash = obj.createTxHash;
removeTxHash = obj.removeTxHash;
}
~DelegationItemEntry()
{}
uint256 hash;
QDateTime createTime;
QString delegateAddress;
QString stakerAddress;
quint8 fee;
qint32 blockNumber;
uint256 createTxHash;
uint256 removeTxHash;
};
class DelegationWorker : public QObject
{
Q_OBJECT
public:
WalletModel *walletModel;
bool first;
DelegationWorker(WalletModel *_walletModel):
walletModel(_walletModel), first(true) {}
private Q_SLOTS:
void updateDelegationData(QString hash, QString delegateAddress, QString stakerAddress, quint8 fee, qint32 blockNumber)
{
// Find delegation details
std::string sHash = hash.toStdString();
std::string sDelegateAddress = delegateAddress.toStdString();
std::string sStakerAddress = stakerAddress.toStdString();
interfaces::DelegationDetails details = walletModel->wallet().getDelegationDetails(sDelegateAddress);
// Get delegation info
interfaces::DelegationInfo info = details.toInfo();
// No delegation contract, no update
if(!details.c_contract_return)
return;
if(details.w_hash.ToString() == sHash)
{
if(details.c_entry_exist)
{
// Update the entry when the delegation exist
if(details.c_delegate_address == sDelegateAddress && details.c_staker_address == sStakerAddress)
{
if(details.c_fee != fee || details.c_block_number != blockNumber)
{
info.fee = details.c_fee;
info.block_number = details.c_block_number;
walletModel->wallet().addDelegationEntry(info);
}
}
else
{
info.block_number = -1;
walletModel->wallet().addDelegationEntry(info);
}
}
else
{
// Update the entry when the delegation not exist
if(details.w_remove_exist)
{
// Remove the entry when marked for deletion
if(details.w_remove_in_main_chain)
{
// The entry is deleted
walletModel->wallet().removeDelegationEntry(sHash);
}
}
else
{
// Update the entry when not marked for deletion
info.block_number = -1;
walletModel->wallet().addDelegationEntry(info);
}
}
}
}
Q_SIGNALS:
};
#include <qt/delegationitemmodel.moc>
struct DelegationItemEntryLessThan
{
bool operator()(const DelegationItemEntry &a, const DelegationItemEntry &b) const
{
return a.hash < b.hash;
}
bool operator()(const DelegationItemEntry &a, const uint256 &b) const
{
return a.hash < b;
}
bool operator()(const uint256 &a, const DelegationItemEntry &b) const
{
return a < b.hash;
}
};
class DelegationItemPriv
{
public:
QList<DelegationItemEntry> cachedDelegationItem;
DelegationItemModel *parent;
DelegationItemPriv(DelegationItemModel *_parent):
parent(_parent) {}
void refreshDelegationItem(interfaces::Wallet& wallet)
{
cachedDelegationItem.clear();
{
for(interfaces::DelegationInfo delegation : wallet.getDelegations())
{
DelegationItemEntry delegationItem(delegation);
if(parent)
{
parent->updateDelegationData(delegationItem);
}
cachedDelegationItem.append(delegationItem);
}
}
std::sort(cachedDelegationItem.begin(), cachedDelegationItem.end(), DelegationItemEntryLessThan());
}
void updateEntry(const DelegationItemEntry &item, int status)
{
// Find delegation in model
QList<DelegationItemEntry>::iterator lower = qLowerBound(
cachedDelegationItem.begin(), cachedDelegationItem.end(), item, DelegationItemEntryLessThan());
QList<DelegationItemEntry>::iterator upper = qUpperBound(
cachedDelegationItem.begin(), cachedDelegationItem.end(), item, DelegationItemEntryLessThan());
int lowerIndex = (lower - cachedDelegationItem.begin());
int upperIndex = (upper - cachedDelegationItem.begin());
bool inModel = (lower != upper);
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "DelegationItemPriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedDelegationItem.insert(lowerIndex, item);
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "DelegationItemPriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
break;
}
cachedDelegationItem[lowerIndex] = item;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if(!inModel)
{
qWarning() << "DelegationItemPriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedDelegationItem.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedDelegationItem.size();
}
DelegationItemEntry *index(int idx)
{
if(idx >= 0 && idx < cachedDelegationItem.size())
{
return &cachedDelegationItem[idx];
}
else
{
return 0;
}
}
};
DelegationItemModel::DelegationItemModel(WalletModel *parent):
QAbstractItemModel(parent),
walletModel(parent),
priv(0),
worker(0)
{
columns << tr("Delegate") << tr("Staker") << tr("Fee") << tr("Height") << tr("Time");
priv = new DelegationItemPriv(this);
priv->refreshDelegationItem(walletModel->wallet());
worker = new DelegationWorker(walletModel);
worker->moveToThread(&(t));
t.start();
subscribeToCoreSignals();
}
DelegationItemModel::~DelegationItemModel()
{
unsubscribeFromCoreSignals();
t.quit();
t.wait();
if(priv)
{
delete priv;
priv = 0;
}
}
QModelIndex DelegationItemModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
DelegationItemEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
return QModelIndex();
}
QModelIndex DelegationItemModel::parent(const QModelIndex &child) const
{
Q_UNUSED(child);
return QModelIndex();
}
int DelegationItemModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int DelegationItemModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant DelegationItemModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
DelegationItemEntry *rec = static_cast<DelegationItemEntry*>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
switch(index.column())
{
case Address:
return rec->delegateAddress;
case Staker:
return rec->stakerAddress;
case Fee:
return rec->fee;
case Height:
return rec->blockNumber;
case Time:
return rec->createTime;
default:
break;
}
break;
case DelegationItemModel::HashRole:
return QString::fromStdString(rec->hash.ToString());
break;
case DelegationItemModel::AddressRole:
return rec->delegateAddress;
break;
case DelegationItemModel::StakerRole:
return rec->stakerAddress;
break;
case DelegationItemModel::FeeRole:
return rec->fee;
break;
case DelegationItemModel::BlockHeightRole:
return rec->blockNumber;
break;
case DelegationItemModel::CreateTxHashRole:
return QString::fromStdString(rec->createTxHash.ToString());
break;
case DelegationItemModel::RemoveTxHashRole:
return QString::fromStdString(rec->removeTxHash.ToString());
break;
default:
break;
}
return QVariant();
}
void DelegationItemModel::updateDelegationData(const QString &hash, int status, bool showDelegation)
{
// Find delegation in wallet
uint256 updated;
updated.SetHex(hash.toStdString());
interfaces::DelegationInfo delegation =walletModel->wallet().getDelegation(updated);
showDelegation &= delegation.hash == updated;
DelegationItemEntry delegationEntry;
if(showDelegation)
{
delegationEntry = DelegationItemEntry(delegation);
updateDelegationData(delegationEntry);
}
else
{
delegationEntry.hash = updated;
}
priv->updateEntry(delegationEntry, status);
}
void DelegationItemModel::checkDelegationChanged()
{
if(!priv)
return;
// Update delegation from contract
for(int i = 0; i < priv->cachedDelegationItem.size(); i++)
{
DelegationItemEntry delegationEntry = priv->cachedDelegationItem[i];
updateDelegationData(delegationEntry);
}
}
void DelegationItemModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
struct DelegationNotification
{
public:
DelegationNotification() {}
DelegationNotification(uint256 _hash, ChangeType _status, bool _showDelegation):
hash(_hash), status(_status), showDelegation(_showDelegation) {}
void invoke(QObject *tim)
{
QString strHash = QString::fromStdString(hash.GetHex());
qDebug() << "NotifyDelegationChanged: " + strHash + " status= " + QString::number(status);
QMetaObject::invokeMethod(tim, "updateDelegationData", Qt::QueuedConnection,
Q_ARG(QString, strHash),
Q_ARG(int, status),
Q_ARG(bool, showDelegation));
}
private:
uint256 hash;
ChangeType status;
bool showDelegation;
};
static void NotifyDelegationChanged(DelegationItemModel *tim, const uint256 &hash, ChangeType status)
{
DelegationNotification notification(hash, status, true);
notification.invoke(tim);
}
void DelegationItemModel::subscribeToCoreSignals()
{
// Connect signals to wallet
m_handler_delegation_changed = walletModel->wallet().handleDelegationChanged(boost::bind(NotifyDelegationChanged, this, _1, _2));
}
void DelegationItemModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
m_handler_delegation_changed->disconnect();
}
void DelegationItemModel::updateDelegationData(const DelegationItemEntry &entry)
{
QString hash = QString::fromStdString(entry.hash.ToString());
QMetaObject::invokeMethod(worker, "updateDelegationData", Qt::QueuedConnection,
Q_ARG(QString, hash),
Q_ARG(QString, entry.delegateAddress),
Q_ARG(QString, entry.stakerAddress),
Q_ARG(quint8, entry.fee),
Q_ARG(qint32, entry.blockNumber));
}
<commit_msg>Update the entry when staker changed<commit_after>#include <qt/delegationitemmodel.h>
#include <qt/walletmodel.h>
#include <interfaces/wallet.h>
#include <validation.h>
#include <qt/bitcoinunits.h>
#include <interfaces/node.h>
#include <interfaces/handler.h>
#include <algorithm>
#include <QDateTime>
#include <QFont>
#include <QDebug>
#include <QThread>
class DelegationItemEntry
{
public:
DelegationItemEntry()
{}
DelegationItemEntry(const interfaces::DelegationInfo &delegationInfo)
{
hash = delegationInfo.hash;
createTime.setTime_t(delegationInfo.time);
delegateAddress = QString::fromStdString(delegationInfo.delegate_address);
stakerAddress = QString::fromStdString(delegationInfo.staker_address);
fee = delegationInfo.fee;
blockNumber = delegationInfo.block_number;
createTxHash = delegationInfo.create_tx_hash;
removeTxHash = delegationInfo.remove_tx_hash;
}
DelegationItemEntry( const DelegationItemEntry &obj)
{
hash = obj.hash;
createTime = obj.createTime;
delegateAddress = obj.delegateAddress;
stakerAddress = obj.stakerAddress;
fee = obj.fee;
blockNumber = obj.blockNumber;
createTxHash = obj.createTxHash;
removeTxHash = obj.removeTxHash;
}
~DelegationItemEntry()
{}
uint256 hash;
QDateTime createTime;
QString delegateAddress;
QString stakerAddress;
quint8 fee;
qint32 blockNumber;
uint256 createTxHash;
uint256 removeTxHash;
};
class DelegationWorker : public QObject
{
Q_OBJECT
public:
WalletModel *walletModel;
bool first;
DelegationWorker(WalletModel *_walletModel):
walletModel(_walletModel), first(true) {}
private Q_SLOTS:
void updateDelegationData(QString hash, QString delegateAddress, QString stakerAddress, quint8 fee, qint32 blockNumber)
{
// Find delegation details
std::string sHash = hash.toStdString();
std::string sDelegateAddress = delegateAddress.toStdString();
std::string sStakerAddress = stakerAddress.toStdString();
interfaces::DelegationDetails details = walletModel->wallet().getDelegationDetails(sDelegateAddress);
// Get delegation info
interfaces::DelegationInfo info = details.toInfo();
// No delegation contract, no update
if(!details.c_contract_return)
return;
if(details.w_hash.ToString() == sHash)
{
if(details.c_entry_exist)
{
// Update the entry when the delegation exist
if(details.c_delegate_address == sDelegateAddress && details.c_staker_address == sStakerAddress)
{
if(details.c_fee != fee || details.c_block_number != blockNumber)
{
info.fee = details.c_fee;
info.block_number = details.c_block_number;
walletModel->wallet().addDelegationEntry(info);
}
}
// Update the entry when staker changed
else if(details.c_delegate_address == sDelegateAddress && details.c_staker_address != sStakerAddress)
{
walletModel->wallet().removeDelegationEntry(sHash);
info = details.toInfo(false);
walletModel->wallet().addDelegationEntry(info);
}
else
{
info.block_number = -1;
walletModel->wallet().addDelegationEntry(info);
}
}
else
{
// Update the entry when the delegation not exist
if(details.w_remove_exist)
{
// Remove the entry when marked for deletion
if(details.w_remove_in_main_chain)
{
// The entry is deleted
walletModel->wallet().removeDelegationEntry(sHash);
}
}
else
{
// Update the entry when not marked for deletion
info.block_number = -1;
walletModel->wallet().addDelegationEntry(info);
}
}
}
}
Q_SIGNALS:
};
#include <qt/delegationitemmodel.moc>
struct DelegationItemEntryLessThan
{
bool operator()(const DelegationItemEntry &a, const DelegationItemEntry &b) const
{
return a.hash < b.hash;
}
bool operator()(const DelegationItemEntry &a, const uint256 &b) const
{
return a.hash < b;
}
bool operator()(const uint256 &a, const DelegationItemEntry &b) const
{
return a < b.hash;
}
};
class DelegationItemPriv
{
public:
QList<DelegationItemEntry> cachedDelegationItem;
DelegationItemModel *parent;
DelegationItemPriv(DelegationItemModel *_parent):
parent(_parent) {}
void refreshDelegationItem(interfaces::Wallet& wallet)
{
cachedDelegationItem.clear();
{
for(interfaces::DelegationInfo delegation : wallet.getDelegations())
{
DelegationItemEntry delegationItem(delegation);
if(parent)
{
parent->updateDelegationData(delegationItem);
}
cachedDelegationItem.append(delegationItem);
}
}
std::sort(cachedDelegationItem.begin(), cachedDelegationItem.end(), DelegationItemEntryLessThan());
}
void updateEntry(const DelegationItemEntry &item, int status)
{
// Find delegation in model
QList<DelegationItemEntry>::iterator lower = qLowerBound(
cachedDelegationItem.begin(), cachedDelegationItem.end(), item, DelegationItemEntryLessThan());
QList<DelegationItemEntry>::iterator upper = qUpperBound(
cachedDelegationItem.begin(), cachedDelegationItem.end(), item, DelegationItemEntryLessThan());
int lowerIndex = (lower - cachedDelegationItem.begin());
int upperIndex = (upper - cachedDelegationItem.begin());
bool inModel = (lower != upper);
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "DelegationItemPriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedDelegationItem.insert(lowerIndex, item);
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "DelegationItemPriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
break;
}
cachedDelegationItem[lowerIndex] = item;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if(!inModel)
{
qWarning() << "DelegationItemPriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedDelegationItem.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedDelegationItem.size();
}
DelegationItemEntry *index(int idx)
{
if(idx >= 0 && idx < cachedDelegationItem.size())
{
return &cachedDelegationItem[idx];
}
else
{
return 0;
}
}
};
DelegationItemModel::DelegationItemModel(WalletModel *parent):
QAbstractItemModel(parent),
walletModel(parent),
priv(0),
worker(0)
{
columns << tr("Delegate") << tr("Staker") << tr("Fee") << tr("Height") << tr("Time");
priv = new DelegationItemPriv(this);
priv->refreshDelegationItem(walletModel->wallet());
worker = new DelegationWorker(walletModel);
worker->moveToThread(&(t));
t.start();
subscribeToCoreSignals();
}
DelegationItemModel::~DelegationItemModel()
{
unsubscribeFromCoreSignals();
t.quit();
t.wait();
if(priv)
{
delete priv;
priv = 0;
}
}
QModelIndex DelegationItemModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
DelegationItemEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
return QModelIndex();
}
QModelIndex DelegationItemModel::parent(const QModelIndex &child) const
{
Q_UNUSED(child);
return QModelIndex();
}
int DelegationItemModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int DelegationItemModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant DelegationItemModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
DelegationItemEntry *rec = static_cast<DelegationItemEntry*>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
switch(index.column())
{
case Address:
return rec->delegateAddress;
case Staker:
return rec->stakerAddress;
case Fee:
return rec->fee;
case Height:
return rec->blockNumber;
case Time:
return rec->createTime;
default:
break;
}
break;
case DelegationItemModel::HashRole:
return QString::fromStdString(rec->hash.ToString());
break;
case DelegationItemModel::AddressRole:
return rec->delegateAddress;
break;
case DelegationItemModel::StakerRole:
return rec->stakerAddress;
break;
case DelegationItemModel::FeeRole:
return rec->fee;
break;
case DelegationItemModel::BlockHeightRole:
return rec->blockNumber;
break;
case DelegationItemModel::CreateTxHashRole:
return QString::fromStdString(rec->createTxHash.ToString());
break;
case DelegationItemModel::RemoveTxHashRole:
return QString::fromStdString(rec->removeTxHash.ToString());
break;
default:
break;
}
return QVariant();
}
void DelegationItemModel::updateDelegationData(const QString &hash, int status, bool showDelegation)
{
// Find delegation in wallet
uint256 updated;
updated.SetHex(hash.toStdString());
interfaces::DelegationInfo delegation =walletModel->wallet().getDelegation(updated);
showDelegation &= delegation.hash == updated;
DelegationItemEntry delegationEntry;
if(showDelegation)
{
delegationEntry = DelegationItemEntry(delegation);
updateDelegationData(delegationEntry);
}
else
{
delegationEntry.hash = updated;
}
priv->updateEntry(delegationEntry, status);
}
void DelegationItemModel::checkDelegationChanged()
{
if(!priv)
return;
// Update delegation from contract
for(int i = 0; i < priv->cachedDelegationItem.size(); i++)
{
DelegationItemEntry delegationEntry = priv->cachedDelegationItem[i];
updateDelegationData(delegationEntry);
}
}
void DelegationItemModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
struct DelegationNotification
{
public:
DelegationNotification() {}
DelegationNotification(uint256 _hash, ChangeType _status, bool _showDelegation):
hash(_hash), status(_status), showDelegation(_showDelegation) {}
void invoke(QObject *tim)
{
QString strHash = QString::fromStdString(hash.GetHex());
qDebug() << "NotifyDelegationChanged: " + strHash + " status= " + QString::number(status);
QMetaObject::invokeMethod(tim, "updateDelegationData", Qt::QueuedConnection,
Q_ARG(QString, strHash),
Q_ARG(int, status),
Q_ARG(bool, showDelegation));
}
private:
uint256 hash;
ChangeType status;
bool showDelegation;
};
static void NotifyDelegationChanged(DelegationItemModel *tim, const uint256 &hash, ChangeType status)
{
DelegationNotification notification(hash, status, true);
notification.invoke(tim);
}
void DelegationItemModel::subscribeToCoreSignals()
{
// Connect signals to wallet
m_handler_delegation_changed = walletModel->wallet().handleDelegationChanged(boost::bind(NotifyDelegationChanged, this, _1, _2));
}
void DelegationItemModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
m_handler_delegation_changed->disconnect();
}
void DelegationItemModel::updateDelegationData(const DelegationItemEntry &entry)
{
QString hash = QString::fromStdString(entry.hash.ToString());
QMetaObject::invokeMethod(worker, "updateDelegationData", Qt::QueuedConnection,
Q_ARG(QString, hash),
Q_ARG(QString, entry.delegateAddress),
Q_ARG(QString, entry.stakerAddress),
Q_ARG(quint8, entry.fee),
Q_ARG(qint32, entry.blockNumber));
}
<|endoftext|> |
<commit_before>#include "Parallel.h"
#include <assert.h>
#include <unistd.h>
#include <future>
#include <iostream>
ParallelCompiler::ParallelCompiler(const vector<ConsUnit>& units, size_t buildCount):
m_Units(units),
m_BuildCount(buildCount)
{
}
int ParallelCompiler::Run(int jobs)
{
if (jobs == 0)
jobs = sysconf(_SC_NPROCESSORS_ONLN);
vector<future<int>> workers(jobs);
for (auto& worker: workers) {
worker = async( bind(&ParallelCompiler::Worker, ref(*this)) );
}
for (auto& worker: workers) {
int ret = 0;
if ( ( ret = worker.get() ) != 0)
return ret;
}
return 0;
}
string ParallelCompiler::Objects() const
{
return m_Objects;
}
int ParallelCompiler::Worker()
{
while (m_Ok) {
// Take unit.
int uidx;
int bidx = -1;
{
std::unique_lock<std::mutex> locker(m_IndexMutex);
if (m_UnitIndex >= m_Units.size()) {
return 0;
} else {
uidx = m_UnitIndex++;
if ( !m_Units[uidx].build.empty() ) {
bidx = ++m_BuildIndex;
}
}
}
// Try compile it.
const ConsUnit& unit = m_Units[uidx];
if ( bidx != -1 ) {
assert(m_BuildCount != 0);
char buf[] = "[ 100% ] ";
int percent = (double)bidx / m_BuildCount * 100;
::snprintf(buf, sizeof buf, "[ %3.d%% ] ", percent);
m_CoutMutex.lock();
cout << buf << unit.build << endl;
m_CoutMutex.unlock();
if (::system( unit.build.c_str() ) != 0) {
m_Ok = false;
return 1;
}
}
// Record all our objects.
std::lock_guard<std::mutex> locker(m_ObjectsMutex);
m_Objects += unit.out + " ";
}
return 0;
}
<commit_msg>~ use c++11 function to detect ncpus<commit_after>#include "Parallel.h"
#include <assert.h>
#include <future>
#include <thread>
#include <iostream>
ParallelCompiler::ParallelCompiler(const vector<ConsUnit>& units, size_t buildCount):
m_Units(units),
m_BuildCount(buildCount)
{
}
int ParallelCompiler::Run(int jobs)
{
if (jobs <= 0)
jobs = std::thread::hardware_concurrency();
vector<future<int>> workers(jobs);
for (auto& worker: workers) {
worker = async( bind(&ParallelCompiler::Worker, ref(*this)) );
}
for (auto& worker: workers) {
int ret = 0;
if ( ( ret = worker.get() ) != 0)
return ret;
}
return 0;
}
string ParallelCompiler::Objects() const
{
return m_Objects;
}
int ParallelCompiler::Worker()
{
while (m_Ok) {
// Take unit.
int uidx;
int bidx = -1;
{
std::unique_lock<std::mutex> locker(m_IndexMutex);
if (m_UnitIndex >= m_Units.size()) {
return 0;
} else {
uidx = m_UnitIndex++;
if ( !m_Units[uidx].build.empty() ) {
bidx = ++m_BuildIndex;
}
}
}
// Try compile it.
const ConsUnit& unit = m_Units[uidx];
if ( bidx != -1 ) {
assert(m_BuildCount != 0);
char buf[] = "[ 100% ] ";
int percent = (double)bidx / m_BuildCount * 100;
::snprintf(buf, sizeof buf, "[ %3.d%% ] ", percent);
m_CoutMutex.lock();
cout << buf << unit.build << endl;
m_CoutMutex.unlock();
if (::system( unit.build.c_str() ) != 0) {
m_Ok = false;
return 1;
}
}
// Record all our objects.
std::lock_guard<std::mutex> locker(m_ObjectsMutex);
m_Objects += unit.out + " ";
}
return 0;
}
<|endoftext|> |
<commit_before>#include "radial_por_lotes.cpp"
#include <gnuplot-iostream.h>
#include "../config.hpp"
int main()
{
arma_rng::set_seed_random();
mat datos;
datos.load(config::sourceDir + "/guia2/datos/XOR_trn.csv");
ic::ParametrosRBF parametros;
ifstream ifs{config::sourceDir + "/guia2/parametrosRbfXor.txt"};
if (!ifs)
throw runtime_error("No se pudo abrir el archivo");
if (!(ifs >> parametros))
throw runtime_error("Se leyeron mal los parametros del RBF para el XOR");
const mat patrones = datos.head_cols(2);
const vec salidaDeseada = datos.tail_cols(1);
vector<rowvec> centroides;
vec sigmas;
tie(centroides, sigmas) = ic::entrenarRadialPorLotes(patrones,
parametros.estructuraRed(0),
ic::tipoInicializacion::valoresAlAzar);
mat matrizCentroides;
for (const rowvec& centroide : centroides) {
matrizCentroides.insert_rows(matrizCentroides.n_rows, centroide);
}
const mat verdaderos = patrones.rows(find(salidaDeseada == 1));
const mat falsos = patrones.rows(find(salidaDeseada == -1));
Gnuplot gp;
gp << "set title 'XOR base radial' font ',13'" << endl
<< "set xlabel 'x_1'" << endl
<< "set ylabel 'x_2'" << endl
<< "set grid" << endl
<< "plot " << gp.file1d(verdaderos) << "title 'Verdaderos' with points lt rgb 'blue', "
<< gp.file1d(falsos) << "title 'Falsos' with points lt rgb 'red', "
<< gp.file1d(matrizCentroides) << "title 'Centroides' with points pt 5 ps 2 lt rgb 'green'" << endl;
return 0;
}
<commit_msg>Guia 1 - Ejercicio 1: Mejorar colores del gráfico<commit_after>#include "radial_por_lotes.cpp"
#include <gnuplot-iostream.h>
#include "../config.hpp"
int main()
{
arma_rng::set_seed_random();
mat datos;
datos.load(config::sourceDir + "/guia2/datos/XOR_trn.csv");
ic::ParametrosRBF parametros;
ifstream ifs{config::sourceDir + "/guia2/parametrosRbfXor.txt"};
if (!ifs)
throw runtime_error("No se pudo abrir el archivo");
if (!(ifs >> parametros))
throw runtime_error("Se leyeron mal los parametros del RBF para el XOR");
const mat patrones = datos.head_cols(2);
const vec salidaDeseada = datos.tail_cols(1);
vector<rowvec> centroides;
vec sigmas;
tie(centroides, sigmas) = ic::entrenarRadialPorLotes(patrones,
parametros.estructuraRed(0),
ic::tipoInicializacion::valoresAlAzar);
mat matrizCentroides;
for (const rowvec& centroide : centroides) {
matrizCentroides.insert_rows(matrizCentroides.n_rows, centroide);
}
const mat verdaderos = patrones.rows(find(salidaDeseada == 1));
const mat falsos = patrones.rows(find(salidaDeseada == -1));
Gnuplot gp;
gp << "set title 'XOR base radial' font ',13'" << endl
<< "set xlabel 'x_1'" << endl
<< "set ylabel 'x_2'" << endl
<< "set grid" << endl
<< "plot " << gp.file1d(verdaderos) << "title 'Verdaderos' with points lt rgb 'cyan', "
<< gp.file1d(falsos) << "title 'Falsos' with points lt rgb 'green', "
<< gp.file1d(matrizCentroides) << "title 'Centroides' with points pt 6 ps 2 lw 3 lt rgb 'black'" << endl;
return 0;
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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 "flusspferd/xml/xml.hpp"
#include "flusspferd/xml/document.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
using namespace flusspferd;
using namespace flusspferd::xml;
object flusspferd::xml::load_xml(object container) {
local_root_scope scope;
value previous = container.get_property("XML");
if (previous.is_object())
return previous.to_object();
object XML = flusspferd::create_object();
load_class<document>(XML);
container.define_property(
"XML",
XML,
object::read_only_property | object::dont_enumerate);
return XML;
}
<commit_msg>add libxml version check<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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 "flusspferd/xml/xml.hpp"
#include "flusspferd/xml/document.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
using namespace flusspferd;
using namespace flusspferd::xml;
object flusspferd::xml::load_xml(object container) {
LIBXML_TEST_VERSION
local_root_scope scope;
value previous = container.get_property("XML");
if (previous.is_object())
return previous.to_object();
object XML = flusspferd::create_object();
load_class<document>(XML);
container.define_property(
"XML",
XML,
object::read_only_property | object::dont_enumerate);
return XML;
}
<|endoftext|> |
<commit_before><commit_msg>[VecOps] Spell out the constructor with default element initialization<commit_after><|endoftext|> |
<commit_before>#include "bfs/BFSImageStream.hpp"
#include "bfs/DetailBFS.hpp"
#include "bfs/DetailFileBlock.hpp"
#include "bfs/FileBlock.hpp"
#include "bfs/FileBlockException.hpp"
#include "bfs/MakeBFS.hpp"
#include "bfs/OpenDisposition.hpp"
#include "test/TestHelpers.hpp"
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/stream.hpp>
#include <cassert>
#include <sstream>
class FileBlockTest
{
public:
FileBlockTest() : m_uniquePath(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path())
{
boost::filesystem::create_directories(m_uniquePath);
blockWriteAndReadTest();
testWritingToNonWritableThrows();
testReadingFromNonReadableThrows();
}
~FileBlockTest()
{
boost::filesystem::remove_all(m_uniquePath);
}
private:
boost::filesystem::path m_uniquePath;
void blockWriteAndReadTest()
{
long const blocks = 2048;
boost::filesystem::path testPath = buildImage(m_uniquePath, blocks);
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0), uint64_t(0),
bfs::OpenDisposition::buildAppendDisposition());
std::string testData("Hello, world!Hello, world!");
std::vector<uint8_t> vec(testData.begin(), testData.end());
block.write((char*)&vec.front(), testData.length());
// test that actual written correct
assert(block.getDataBytesWritten() == 26);
bfs::BFSImageStream stream(testPath.string(), std::ios::in | std::ios::out | std::ios::binary);
uint64_t size = bfs::detail::getNumberOfDataBytesWrittenToFileBlockN(stream, 0, blocks);
ASSERT_EQUAL(size, 26, "FileBlockTest::blockWriteAndReadTest(): correctly returned block size");
// test that reported next index correct
assert(block.getNextIndex() == 0);
uint64_t next = bfs::detail::getIndexOfNextFileBlockFromFileBlockN(stream, 0, blocks);
stream.close();
ASSERT_EQUAL(next, 0, "FileBlockTest::blockWriteAndReadTest(): correct block index");
// test that data can be read correctly
std::vector<uint8_t> dat;
dat.resize(size);
block.seek(0);
std::streamsize bytesRead = block.read((char*)&dat.front(), size);
ASSERT_EQUAL(bytesRead, size, "FileBlockTest::blockWriteAndReadTest(): data read bytes read check");
std::string str(dat.begin(), dat.end());
ASSERT_EQUAL(str, testData, "FileBlockTest::blockWriteAndReadTest(): data read content check");
}
void testWritingToNonWritableThrows()
{
long const blocks = 2048;
boost::filesystem::path testPath = buildImage(m_uniquePath, blocks);
{
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0), uint64_t(0),
bfs::OpenDisposition::buildReadOnlyDisposition());
std::string testData("Hello, world!Hello, world!");
std::vector<uint8_t> vec(testData.begin(), testData.end());
bool pass = false;
// assert correct exception was thrown
try {
block.write((char*)&vec.front(), testData.length());
} catch (bfs::FileBlockException const &e) {
ASSERT_EQUAL(e, bfs::FileBlockException(bfs::FileBlockError::NotWritable), "FileBlockTest::testWritingToNonWritableThrows() A");
pass = true;
}
// assert that any exception was thrown
ASSERT_EQUAL(pass, true, "FileBlockTest::testWritingToNonWritableThrows() B");
}
}
void testReadingFromNonReadableThrows()
{
long const blocks = 2048;
boost::filesystem::path testPath = buildImage(m_uniquePath, blocks);
{
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0), uint64_t(0),
bfs::OpenDisposition::buildWriteOnlyDisposition());
std::string testData("Hello, world!Hello, world!");
std::vector<uint8_t> vec(testData.begin(), testData.end());
block.write((char*)&vec.front(), testData.length());
}
{
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0),
bfs::OpenDisposition::buildWriteOnlyDisposition());
std::vector<uint8_t> vec(block.getInitialDataBytesWritten());
// assert correct exception was thrown
bool pass = false;
try {
block.read((char*)&vec.front(), block.getInitialDataBytesWritten());
} catch (bfs::FileBlockException const &e) {
ASSERT_EQUAL(e, bfs::FileBlockException(bfs::FileBlockError::NotReadable), "FileBlockTest::testReadingFromNonReadableThrows() A");
pass = true;
}
// assert that any exception was thrown
ASSERT_EQUAL(pass, true, "FileBlockTest::testReadingFromNonReadableThrows() B");
}
}
};
<commit_msg>Exception handling added to FileBlock<commit_after>#include "bfs/BFSImageStream.hpp"
#include "bfs/DetailBFS.hpp"
#include "bfs/DetailFileBlock.hpp"
#include "bfs/FileBlock.hpp"
#include "bfs/FileBlockException.hpp"
#include "bfs/MakeBFS.hpp"
#include "bfs/OpenDisposition.hpp"
#include "test/TestHelpers.hpp"
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/stream.hpp>
#include <cassert>
#include <sstream>
class FileBlockTest
{
public:
FileBlockTest() : m_uniquePath(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path())
{
boost::filesystem::create_directories(m_uniquePath);
blockWriteAndReadTest();
testWritingToNonWritableThrows();
testReadingFromNonReadableThrows();
}
~FileBlockTest()
{
boost::filesystem::remove_all(m_uniquePath);
}
private:
boost::filesystem::path m_uniquePath;
void blockWriteAndReadTest()
{
long const blocks = 2048;
boost::filesystem::path testPath = buildImage(m_uniquePath, blocks);
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0), uint64_t(0),
bfs::OpenDisposition::buildAppendDisposition());
std::string testData("Hello, world!Hello, world!");
std::vector<uint8_t> vec(testData.begin(), testData.end());
block.write((char*)&vec.front(), testData.length());
// test that actual written correct
assert(block.getDataBytesWritten() == 26);
bfs::BFSImageStream stream(testPath.string(), std::ios::in | std::ios::out | std::ios::binary);
uint64_t size = bfs::detail::getNumberOfDataBytesWrittenToFileBlockN(stream, 0, blocks);
ASSERT_EQUAL(size, 26, "FileBlockTest::blockWriteAndReadTest(): correctly returned block size");
// test that reported next index correct
assert(block.getNextIndex() == 0);
uint64_t next = bfs::detail::getIndexOfNextFileBlockFromFileBlockN(stream, 0, blocks);
stream.close();
ASSERT_EQUAL(next, 0, "FileBlockTest::blockWriteAndReadTest(): correct block index");
// test that data can be read correctly
std::vector<uint8_t> dat;
dat.resize(size);
block.seek(0);
std::streamsize bytesRead = block.read((char*)&dat.front(), size);
ASSERT_EQUAL(bytesRead, size, "FileBlockTest::blockWriteAndReadTest(): data read bytes read check");
std::string str(dat.begin(), dat.end());
ASSERT_EQUAL(str, testData, "FileBlockTest::blockWriteAndReadTest(): data read content check");
}
void testWritingToNonWritableThrows()
{
long const blocks = 2048;
boost::filesystem::path testPath = buildImage(m_uniquePath, blocks);
{
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0), uint64_t(0),
bfs::OpenDisposition::buildReadOnlyDisposition());
std::string testData("Hello, world!Hello, world!");
std::vector<uint8_t> vec(testData.begin(), testData.end());
bool pass = false;
// assert correct exception was thrown
try {
block.write((char*)&vec.front(), testData.length());
} catch (bfs::FileBlockException const &e) {
ASSERT_EQUAL(e, bfs::FileBlockException(bfs::FileBlockError::NotWritable), "FileBlockTest::testWritingToNonWritableThrows() A");
pass = true;
}
// assert that any exception was thrown
ASSERT_EQUAL(pass, true, "FileBlockTest::testWritingToNonWritableThrows() B");
}
}
void testReadingFromNonReadableThrows()
{
long const blocks = 2048;
boost::filesystem::path testPath = buildImage(m_uniquePath, blocks);
{
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0), uint64_t(0),
bfs::OpenDisposition::buildWriteOnlyDisposition());
std::string testData("Hello, world!Hello, world!");
std::vector<uint8_t> vec(testData.begin(), testData.end());
block.write((char*)&vec.front(), testData.length());
}
{
bfs::FileBlock block(testPath.string(), blocks, uint64_t(0),
bfs::OpenDisposition::buildWriteOnlyDisposition());
std::vector<uint8_t> vec(block.getInitialDataBytesWritten());
// assert correct exception was thrown
bool pass = false;
try {
block.read((char*)&vec.front(), block.getInitialDataBytesWritten());
} catch (bfs::FileBlockException const &e) {
ASSERT_EQUAL(e, bfs::FileBlockException(bfs::FileBlockError::NotReadable), "FileBlockTest::testReadingFromNonReadableThrows() A");
pass = true;
}
// assert that any exception was thrown
ASSERT_EQUAL(pass, true, "FileBlockTest::testReadingFromNonReadableThrows() B");
}
}
};
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <iomanip>
#include <cstring>
#include <glog/logging.h>
#include <tudocomp/def.hpp>
namespace tdc {
/// A view into a slice of memory.
///
/// This is an abstraction around a `const uint8_t*` pointer and a `size_t` size,
/// and represents N bytes of memory starting at that pointer.
///
/// Creating/Copying/Modifying a View will not copy any of the data it points at.
class View {
const uliteral_t* m_data;
size_t m_size;
inline void bound_check(size_t pos) const {
if (pos >= m_size) {
std::stringstream ss;
ss << "accessing view with bounds [0, ";
ss << m_size;
ss << ") at out-of-bounds index ";
ss << pos;
throw std::out_of_range(ss.str());
}
}
public:
// Type members
using value_type = uliteral_t;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using const_reference = const value_type&;
using const_pointer = const value_type*;
using const_iterator = const_pointer;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// static value members
static const size_type npos = -1;
// Constructors
/// Construct a empty View
inline View(): View("") {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const uint8_t* data, size_t len): m_data(data), m_size(len) {}
/// Construct a View as a copy of `other`
inline View(const View& other): View(other.m_data, other.m_size) {}
/// Construct a View pointing at the contents of a vector
inline View(const std::vector<uint8_t>& other):
View(other.data(), other.size()) {}
/// Construct a View pointing at the contents of a string
inline View(const std::string& other):
View((const uint8_t*) other.data(), other.size()) {}
/// Construct a View equal to the (offset)-th suffix of other
inline View(const View& other, size_t offset):
View((const uint8_t*) other.data()+offset, other.size()-offset) { DCHECK_LE(offset, other.size()); }
/// Construct a View pointing at a C-style null terminated string.
///
/// Can be used to construct from a string literal
inline View(const char* other):
View((const uint8_t*) other, strlen(other)) {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const char* data, size_t len):
View((const uint8_t*) data, len) {}
// Conversion
/// Construct a string with the contents of this View
inline operator std::string() const {
return std::string(cbegin(), cend());
}
/// Construct a vector with the contents of this View
inline operator std::vector<uint8_t>() const {
return std::vector<uint8_t>(cbegin(), cend());
}
// Element access
/// Access the element at `pos`
///
/// This method is always bounds checked
inline const_reference at(size_type pos) const {
bound_check(pos);
return m_data[pos];
}
/// Access the element at `pos`
///
/// This method is bounds checked in debug builds
inline const_reference operator[](size_type pos) const {
#ifdef DEBUG
bound_check(pos);
#endif
return m_data[pos];
}
/// Access the first element
inline const_reference front() const {
return (*this)[0];
}
/// Access the last element
inline const_reference back() const {
return (*this)[m_size - 1];
}
/// The backing memory location
inline const uint8_t* data() const {
return &front();
}
// Iterators
/// Begin of iterator
inline const_iterator begin() const {
return &(*this)[0];
}
/// Begin of const iterator
inline const_iterator cbegin() const {
return begin();
}
/// End of iterator
inline const_iterator end() const {
return m_data + m_size;
}
/// End of const iterator
inline const_iterator cend() const {
return end();
}
/// Begin of reverse iterator
inline const_reverse_iterator rbegin() const {
return std::reverse_iterator<const_iterator>(end());
}
/// Begin of const reverse iterator
inline const_reverse_iterator crbegin() const {
return rbegin();
}
/// End of reverse iterator
inline const_reverse_iterator rend() const {
return std::reverse_iterator<const_iterator>(begin());
}
/// End of const reverse iterator
inline const_reverse_iterator crend() const {
return rend();
}
// Capacity
/// Returns `true` if empty
inline bool empty() const {
return m_size == 0;
}
/// Returns size of the View
inline size_type size() const {
return m_size;
}
/// Returns max size of the View. Always the same as `size()`
inline size_type max_size() const {
return size();
}
// Slicing
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "from-to" slice,
/// and cover the bytes starting at `from` and ending at `to`.
///
/// Passing `npos` to `to` will create a slice until the end of the View
///
/// # Example
///
/// `View("abcd").slice(1, 3) == View("bc")`
inline View slice(size_type from, size_type to = npos) const {
if (to == npos) {
to = m_size;
}
DCHECK_LE(from, to);
DCHECK_LE(from, size());
DCHECK_LE(to, size());
return View(m_data + from, to - from);
}
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "position-length" slice,
/// and cover the bytes starting at `pos` and ending at `pos + len`.
///
/// Passing `npos` to `len` will create a slice until the end of the View
///
/// This method covers the same basic operation as `slice()`, but
/// mirrors the semantic of `std::string::substr`.
///
/// # Example
///
/// `View("abcd").substr(1, 2) == View("bc")`
inline View substr(size_type pos, size_type len = npos) const {
if (len == npos) {
len = m_size - pos;
}
return slice(pos, pos + len);
}
// Modifiers
/// Swap two Views
inline void swap(View& other) {
using std::swap;
swap(m_data, other.m_data);
swap(m_size, other.m_size);
}
/// Swap two Views
inline friend void swap(View& a, View& b) {
a.swap(b);
}
/// Sets the size to 0
inline void clear() {
m_size = 0;
}
/// Removes the first `n` elements from the View
inline void remove_prefix(size_type n) {
*this = slice(n);
}
/// Removes the last `n` elements from the View
inline void remove_suffix(size_type n) {
*this = slice(0, m_size - n);
}
// string predicates
/// Returns `true` if the View starts with `c`
inline bool starts_with(uint8_t c) const {
return !empty() && (front() == c);
}
/// Returns `true` if the View starts with `c`
inline bool starts_with(char c) const {
return starts_with(uint8_t(c));
}
/// Returns `true` if the View starts with `x`
inline bool starts_with(const View& x) const;
/// Returns `true` if the View ends with `c`
inline bool ends_with(uint8_t c) const {
return !empty() && (back() == c);
}
/// Returns `true` if the View ends with `c`
inline bool ends_with(char c) const {
return ends_with(uint8_t(c));
}
/// Returns `true` if the View ends with `x`
inline bool ends_with(const View& x) const;
};
inline bool operator==(const View& lhs, const View& rhs) {
// TODO: memcmp!
return (lhs.size() == rhs.size())
&& (std::memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
}
inline bool operator!=(const View& lhs, const View& rhs) {
return !(lhs == rhs);
}
inline bool operator<(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend());
}
inline bool operator>(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend(),
[](const uint8_t& l, const uint8_t& r){
return l > r;
});
}
inline bool operator<=(const View& lhs, const View& rhs) {
return !(lhs > rhs);
}
inline bool operator>=(const View& lhs, const View& rhs) {
return !(lhs < rhs);
}
inline std::ostream& operator<<(std::ostream& os, const View& v) {
os.write((const char*) v.data(), v.size());
return os;
}
inline bool View::starts_with(const View& x) const {
return (x.size() <= size())
&& (slice(0, x.size()) == x);
}
inline bool View::ends_with(const View& x) const {
return (x.size() <= size())
&& (slice(size() - x.size()) == x);
}
inline View operator "" _v(const char* str, size_t n)
{
return View(str, n);
}
using string_ref = View;
}
<commit_msg>Move #ifdef in View up to a common location<commit_after>#pragma once
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <iomanip>
#include <cstring>
#include <glog/logging.h>
#include <tudocomp/def.hpp>
namespace tdc {
/// A view into a slice of memory.
///
/// This is an abstraction around a `const uint8_t*` pointer and a `size_t` size,
/// and represents N bytes of memory starting at that pointer.
///
/// Creating/Copying/Modifying a View will not copy any of the data it points at.
class View {
const uliteral_t* m_data;
size_t m_size;
inline void bound_check(size_t pos) const {
if (pos >= m_size) {
std::stringstream ss;
ss << "accessing view with bounds [0, ";
ss << m_size;
ss << ") at out-of-bounds index ";
ss << pos;
throw std::out_of_range(ss.str());
}
}
inline void debug_bound_check(size_t pos) const {
#ifdef DEBUG
bound_check(pos);
#endif
}
public:
// Type members
using value_type = uliteral_t;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using const_reference = const value_type&;
using const_pointer = const value_type*;
using const_iterator = const_pointer;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// static value members
static const size_type npos = -1;
// Constructors
/// Construct a empty View
inline View(): View("") {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const uint8_t* data, size_t len): m_data(data), m_size(len) {}
/// Construct a View as a copy of `other`
inline View(const View& other): View(other.m_data, other.m_size) {}
/// Construct a View pointing at the contents of a vector
inline View(const std::vector<uint8_t>& other):
View(other.data(), other.size()) {}
/// Construct a View pointing at the contents of a string
inline View(const std::string& other):
View((const uint8_t*) other.data(), other.size()) {}
/// Construct a View equal to the (offset)-th suffix of other
inline View(const View& other, size_t offset):
View((const uint8_t*) other.data()+offset, other.size()-offset) { DCHECK_LE(offset, other.size()); }
/// Construct a View pointing at a C-style null terminated string.
///
/// Can be used to construct from a string literal
inline View(const char* other):
View((const uint8_t*) other, strlen(other)) {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const char* data, size_t len):
View((const uint8_t*) data, len) {}
// Conversion
/// Construct a string with the contents of this View
inline operator std::string() const {
return std::string(cbegin(), cend());
}
/// Construct a vector with the contents of this View
inline operator std::vector<uint8_t>() const {
return std::vector<uint8_t>(cbegin(), cend());
}
// Element access
/// Access the element at `pos`
///
/// This method is always bounds checked
inline const_reference at(size_type pos) const {
bound_check(pos);
return m_data[pos];
}
/// Access the element at `pos`
///
/// This method is bounds checked in debug builds
inline const_reference operator[](size_type pos) const {
debug_bound_check(pos);
return m_data[pos];
}
/// Access the first element
inline const_reference front() const {
return (*this)[0];
}
/// Access the last element
inline const_reference back() const {
return (*this)[m_size - 1];
}
/// The backing memory location
inline const uint8_t* data() const {
return &front();
}
// Iterators
/// Begin of iterator
inline const_iterator begin() const {
return &(*this)[0];
}
/// Begin of const iterator
inline const_iterator cbegin() const {
return begin();
}
/// End of iterator
inline const_iterator end() const {
return m_data + m_size;
}
/// End of const iterator
inline const_iterator cend() const {
return end();
}
/// Begin of reverse iterator
inline const_reverse_iterator rbegin() const {
return std::reverse_iterator<const_iterator>(end());
}
/// Begin of const reverse iterator
inline const_reverse_iterator crbegin() const {
return rbegin();
}
/// End of reverse iterator
inline const_reverse_iterator rend() const {
return std::reverse_iterator<const_iterator>(begin());
}
/// End of const reverse iterator
inline const_reverse_iterator crend() const {
return rend();
}
// Capacity
/// Returns `true` if empty
inline bool empty() const {
return m_size == 0;
}
/// Returns size of the View
inline size_type size() const {
return m_size;
}
/// Returns max size of the View. Always the same as `size()`
inline size_type max_size() const {
return size();
}
// Slicing
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "from-to" slice,
/// and cover the bytes starting at `from` and ending at `to`.
///
/// Passing `npos` to `to` will create a slice until the end of the View
///
/// # Example
///
/// `View("abcd").slice(1, 3) == View("bc")`
inline View slice(size_type from, size_type to = npos) const {
if (to == npos) {
to = m_size;
}
DCHECK_LE(from, to);
DCHECK_LE(from, size());
DCHECK_LE(to, size());
return View(m_data + from, to - from);
}
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "position-length" slice,
/// and cover the bytes starting at `pos` and ending at `pos + len`.
///
/// Passing `npos` to `len` will create a slice until the end of the View
///
/// This method covers the same basic operation as `slice()`, but
/// mirrors the semantic of `std::string::substr`.
///
/// # Example
///
/// `View("abcd").substr(1, 2) == View("bc")`
inline View substr(size_type pos, size_type len = npos) const {
if (len == npos) {
len = m_size - pos;
}
return slice(pos, pos + len);
}
// Modifiers
/// Swap two Views
inline void swap(View& other) {
using std::swap;
swap(m_data, other.m_data);
swap(m_size, other.m_size);
}
/// Swap two Views
inline friend void swap(View& a, View& b) {
a.swap(b);
}
/// Sets the size to 0
inline void clear() {
m_size = 0;
}
/// Removes the first `n` elements from the View
inline void remove_prefix(size_type n) {
*this = slice(n);
}
/// Removes the last `n` elements from the View
inline void remove_suffix(size_type n) {
*this = slice(0, m_size - n);
}
// string predicates
/// Returns `true` if the View starts with `c`
inline bool starts_with(uint8_t c) const {
return !empty() && (front() == c);
}
/// Returns `true` if the View starts with `c`
inline bool starts_with(char c) const {
return starts_with(uint8_t(c));
}
/// Returns `true` if the View starts with `x`
inline bool starts_with(const View& x) const;
/// Returns `true` if the View ends with `c`
inline bool ends_with(uint8_t c) const {
return !empty() && (back() == c);
}
/// Returns `true` if the View ends with `c`
inline bool ends_with(char c) const {
return ends_with(uint8_t(c));
}
/// Returns `true` if the View ends with `x`
inline bool ends_with(const View& x) const;
};
inline bool operator==(const View& lhs, const View& rhs) {
// TODO: memcmp!
return (lhs.size() == rhs.size())
&& (std::memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
}
inline bool operator!=(const View& lhs, const View& rhs) {
return !(lhs == rhs);
}
inline bool operator<(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend());
}
inline bool operator>(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend(),
[](const uint8_t& l, const uint8_t& r){
return l > r;
});
}
inline bool operator<=(const View& lhs, const View& rhs) {
return !(lhs > rhs);
}
inline bool operator>=(const View& lhs, const View& rhs) {
return !(lhs < rhs);
}
inline std::ostream& operator<<(std::ostream& os, const View& v) {
os.write((const char*) v.data(), v.size());
return os;
}
inline bool View::starts_with(const View& x) const {
return (x.size() <= size())
&& (slice(0, x.size()) == x);
}
inline bool View::ends_with(const View& x) const {
return (x.size() <= size())
&& (slice(size() - x.size()) == x);
}
inline View operator "" _v(const char* str, size_t n)
{
return View(str, n);
}
using string_ref = View;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2009-2011 qiuu
Copyright (C) 2016 Clownacy
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <cstring>
#include <fstream>
#include <unistd.h>
#include "Common.h"
#include "PrjHndl.h"
#include "TxtRead.h"
#include "Resource.h"
#include "WinAPI.h"
ProjectData::ProjectData(const char* const prjtxt) {
tileOffset = 0;
letterOffset = numberOffset = 0;
// Make working directory from project path
char prjdir[strlen(prjtxt)+1];
strcpy(prjdir, prjtxt);
// Find last path separator
char* posix_seperator = strrchr(prjdir, '/'); // First, POSIX
char* windows_seperator = strrchr(prjdir, '\\'); // Then whatever Windows uses
if (posix_seperator != NULL || windows_seperator != NULL)
{
if (posix_seperator != NULL)
(*posix_seperator) = '\0';
else if (windows_seperator != NULL)
(*windows_seperator) = '\0';
chdir(prjdir);
}
std::ifstream prjfile(prjtxt, std::ios::in);
while (!prjfile.eof()) {
char line[256];
prjfile.getline(line, 256);
infoType info_type = readInfoType(line);
AssignInfo(info_type, line+strcspn(line, ":")+1);
}
}
void ProjectData::AssignInfo(const infoType type, char* content) {
switch(type) {
case infoType::PALETTE_FILE:
strcpy(pal.name, trimString(content));
break;
case infoType::MAPPING_FILE:
strcpy(map.name, trimString(content));
break;
case infoType::ART_FILE:
strcpy(art.name, trimString(content));
break;
case infoType::PALETTE_OFFSET:
pal.offset = strtol(content, NULL, 0);
break;
case infoType::MAPPING_OFFSET:
map.offset = strtol(content, NULL, 0);
break;
case infoType::ART_OFFSET:
art.offset = strtol(content, NULL, 0);
break;
case infoType::PALETTE_LENGTH:
pal.length = strtol(content, NULL, 0);
break;
case infoType::MAPPING_LENGTH:
map.length = strtol(content, NULL, 0);
break;
case infoType::ART_LENGTH:
art.length = strtol(content, NULL, 0);
break;
case infoType::PALETTE_COMPRESSION:
pal.compression = readComprType(trimString(content));
break;
case infoType::MAPPING_COMPRESSION:
map.compression = readComprType(trimString(content));
break;
case infoType::ART_COMPRESSION:
art.compression = readComprType(trimString(content));
break;
case infoType::PALETTE_DESTINATION_OFFSET:
pal.destination_offset = strtol(content, NULL, 0);
if (pal.destination_offset >= 0x80)
MainScreen->Error("Palette Destination Offset cannot be higher than 0x7F (16th entry of 4th palette line; the last palette entry)");
break;
case infoType::X_SIZE:
map.xSize = strtol(content, NULL, 0);
break;
case infoType::Y_SIZE:
map.ySize = strtol(content, NULL, 0);
break;
case infoType::TILE_OFFSET:
tileOffset = strtol(content, NULL, 0);
break;
case infoType::LETTER_OFFSET:
letterOffset = strtol(content, NULL, 0);
break;
case infoType::NUMBER_OFFSET:
numberOffset = strtol(content, NULL, 0);
break;
case infoType::SAVE_FILE:
strcpy(map.saveName, trimString(content));
break;
case infoType::KOSINSKI_MODULE_SIZE:
art.kosinski_module_size = strtol(content, NULL, 0);
break;
}
}
<commit_msg>Missed a windows.h include<commit_after>/*
Copyright (C) 2009-2011 qiuu
Copyright (C) 2016 Clownacy
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
*/
#include <cstring>
#include <fstream>
#include <unistd.h>
#include "Common.h"
#include "PrjHndl.h"
#include "TxtRead.h"
#include "Resource.h"
#ifdef _WIN32
#include "WinAPI.h"
#endif
ProjectData::ProjectData(const char* const prjtxt) {
tileOffset = 0;
letterOffset = numberOffset = 0;
// Make working directory from project path
char prjdir[strlen(prjtxt)+1];
strcpy(prjdir, prjtxt);
// Find last path separator
char* posix_seperator = strrchr(prjdir, '/'); // First, POSIX
char* windows_seperator = strrchr(prjdir, '\\'); // Then whatever Windows uses
if (posix_seperator != NULL || windows_seperator != NULL)
{
if (posix_seperator != NULL)
(*posix_seperator) = '\0';
else if (windows_seperator != NULL)
(*windows_seperator) = '\0';
chdir(prjdir);
}
std::ifstream prjfile(prjtxt, std::ios::in);
while (!prjfile.eof()) {
char line[256];
prjfile.getline(line, 256);
infoType info_type = readInfoType(line);
AssignInfo(info_type, line+strcspn(line, ":")+1);
}
}
void ProjectData::AssignInfo(const infoType type, char* content) {
switch(type) {
case infoType::PALETTE_FILE:
strcpy(pal.name, trimString(content));
break;
case infoType::MAPPING_FILE:
strcpy(map.name, trimString(content));
break;
case infoType::ART_FILE:
strcpy(art.name, trimString(content));
break;
case infoType::PALETTE_OFFSET:
pal.offset = strtol(content, NULL, 0);
break;
case infoType::MAPPING_OFFSET:
map.offset = strtol(content, NULL, 0);
break;
case infoType::ART_OFFSET:
art.offset = strtol(content, NULL, 0);
break;
case infoType::PALETTE_LENGTH:
pal.length = strtol(content, NULL, 0);
break;
case infoType::MAPPING_LENGTH:
map.length = strtol(content, NULL, 0);
break;
case infoType::ART_LENGTH:
art.length = strtol(content, NULL, 0);
break;
case infoType::PALETTE_COMPRESSION:
pal.compression = readComprType(trimString(content));
break;
case infoType::MAPPING_COMPRESSION:
map.compression = readComprType(trimString(content));
break;
case infoType::ART_COMPRESSION:
art.compression = readComprType(trimString(content));
break;
case infoType::PALETTE_DESTINATION_OFFSET:
pal.destination_offset = strtol(content, NULL, 0);
if (pal.destination_offset >= 0x80)
MainScreen->Error("Palette Destination Offset cannot be higher than 0x7F (16th entry of 4th palette line; the last palette entry)");
break;
case infoType::X_SIZE:
map.xSize = strtol(content, NULL, 0);
break;
case infoType::Y_SIZE:
map.ySize = strtol(content, NULL, 0);
break;
case infoType::TILE_OFFSET:
tileOffset = strtol(content, NULL, 0);
break;
case infoType::LETTER_OFFSET:
letterOffset = strtol(content, NULL, 0);
break;
case infoType::NUMBER_OFFSET:
numberOffset = strtol(content, NULL, 0);
break;
case infoType::SAVE_FILE:
strcpy(map.saveName, trimString(content));
break;
case infoType::KOSINSKI_MODULE_SIZE:
art.kosinski_module_size = strtol(content, NULL, 0);
break;
}
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2015 Danny "Rapptz" Y.
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef HYPEST_ELO_HPP
#define HYPEST_ELO_HPP
#include <cmath>
#include <cstddef>
#include <numeric>
namespace hypest {
constexpr double initial_rating = 1200.0;
struct elo {
public:
elo() noexcept = default;
elo(double r): r(r) {}
int rating() const noexcept {
return static_cast<int>(std::round(r + participation_bonus()));
}
void rating(double d) noexcept {
r = d - participation_bonus();
}
int tournament_miss_streak() const noexcept {
return t;
}
void tournament_miss_streak(int arg) noexcept {
t = arg;
}
template<typename Matches>
void update(const Matches& matches) noexcept {
if(matches.empty()) {
++t;
return;
}
t = 1;
for(auto&& m : matches) {
r += k_factor() * (m.score() - expected_win_rate(m.opponent.r));
}
}
private:
// the decay constant specifies how much decay occurs if missing a rating period
static constexpr double decay = 15.0;
int k_factor() const noexcept {
auto floored_rating = static_cast<int>(r);
if(floored_rating < 2100) {
return 32;
}
else if(floored_rating >= 2100 && floored_rating <= 2400) {
return 24;
}
else {
return 16;
}
}
double participation_bonus() const noexcept {
return t == 1 ? decay : - t * decay;
}
double expected_win_rate(double opponent_rating) const noexcept {
return 1 / (1 + std::pow(10, (opponent_rating - r) / 400.0));
}
double r = initial_rating;
int t = 1;
bool participating = false;
};
struct match {
enum : int {
win, loss, tie
};
elo opponent;
int result;
match(elo opponent, int result) noexcept: opponent(opponent), result(result) {}
double score() const noexcept {
switch(result) {
case match::win:
return 1.0;
default:
return 0.0;
}
}
};
} // hypest
#endif // HYPEST_ELO_HPP
<commit_msg>Fix decay formula.<commit_after>// The MIT License (MIT)
// Copyright (c) 2015 Danny "Rapptz" Y.
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef HYPEST_ELO_HPP
#define HYPEST_ELO_HPP
#include <cmath>
#include <cstddef>
#include <numeric>
namespace hypest {
constexpr double initial_rating = 1200.0;
struct elo {
public:
elo() noexcept = default;
elo(double r): r(r) {}
int rating() const noexcept {
return static_cast<int>(std::round(r + participation_bonus()));
}
void rating(double d) noexcept {
r = d - participation_bonus();
}
int tournament_miss_streak() const noexcept {
return t;
}
void tournament_miss_streak(int arg) noexcept {
t = arg;
}
template<typename Matches>
void update(const Matches& matches) noexcept {
if(matches.empty()) {
++t;
return;
}
t = 1;
for(auto&& m : matches) {
r += k_factor() * (m.score() - expected_win_rate(m.opponent.r));
}
}
private:
// the decay constant specifies how much decay occurs if missing a rating period
static constexpr double decay = 15.0;
int k_factor() const noexcept {
auto floored_rating = static_cast<int>(r);
if(floored_rating < 2100) {
return 32;
}
else if(floored_rating >= 2100 && floored_rating <= 2400) {
return 24;
}
else {
return 16;
}
}
double participation_bonus() const noexcept {
return t == 1 ? 0.0 : - (t - 1) * decay;
}
double expected_win_rate(double opponent_rating) const noexcept {
return 1 / (1 + std::pow(10, (opponent_rating - r) / 400.0));
}
double r = initial_rating;
int t = 1;
bool participating = false;
};
struct match {
enum : int {
win, loss, tie
};
elo opponent;
int result;
match(elo opponent, int result) noexcept: opponent(opponent), result(result) {}
double score() const noexcept {
switch(result) {
case match::win:
return 1.0;
default:
return 0.0;
}
}
};
} // hypest
#endif // HYPEST_ELO_HPP
<|endoftext|> |
<commit_before>#include "rdb_protocol/terms/terms.hpp"
#include <string>
#include <utility>
#include "rdb_protocol/datum_stream.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/op.hpp"
#include "rdb_protocol/pb_utils.hpp"
namespace ql {
// NOTE: `asc` and `desc` don't fit into our type system (they're a hack for
// orderby to avoid string parsing), so we instead literally examine the
// protobuf to determine whether they're present. This is a hack. (This is
// implemented internally in terms of string concatenation because that's what
// the old string-parsing solution was, and this was a quick way to get the new
// behavior that also avoided dumping already-tested code paths. I'm probably
// going to hell for it though.)
class asc_term_t : public op_term_t {
public:
asc_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1)) { }
private:
virtual counted_t<val_t> eval_impl() {
return new_val(make_counted<const datum_t>("+" + arg(0)->as_str()));
}
virtual const char *name() const { return "asc"; }
};
class desc_term_t : public op_term_t {
public:
desc_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1)) { }
private:
virtual counted_t<val_t> eval_impl() {
return new_val(make_counted<const datum_t>("-" + arg(0)->as_str()));
}
virtual const char *name() const { return "desc"; }
};
class orderby_term_t : public op_term_t {
public:
orderby_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1, -1)), src_term(term) { }
private:
class lt_cmp_t {
public:
explicit lt_cmp_t(counted_t<const datum_t> _attrs) : attrs(_attrs) { }
bool operator()(counted_t<const datum_t> l, counted_t<const datum_t> r) {
for (size_t i = 0; i < attrs->size(); ++i) {
std::string attrname = attrs->get(i)->as_str();
bool invert = (attrname[0] == '-');
r_sanity_check(attrname[0] == '-' || attrname[0] == '+');
attrname.erase(0, 1);
counted_t<const datum_t> lattr = l->get(attrname, NOTHROW);
counted_t<const datum_t> rattr = r->get(attrname, NOTHROW);
if (!lattr.has() && !rattr.has()) {
continue;
}
if (!lattr.has()) {
return static_cast<bool>(true ^ invert);
}
if (!rattr.has()) {
return static_cast<bool>(false ^ invert);
}
// TODO: use datum_t::cmp instead to be faster
if (*lattr == *rattr) {
continue;
}
return static_cast<bool>((*lattr < *rattr) ^ invert);
}
return false;
}
private:
counted_t<const datum_t> attrs;
};
virtual counted_t<val_t> eval_impl() {
scoped_ptr_t<datum_t> arr(new datum_t(datum_t::R_ARRAY));
for (size_t i = 1; i < num_args(); ++i) {
Term::TermType type = src_term->args(i).type();
if (type != Term::ASC && type != Term::DESC) {
auto datum = make_counted<const datum_t>("+" + arg(i)->as_str());
arr->add(new_val(datum)->as_datum());
} else {
arr->add(arg(i)->as_datum());
}
}
lt_cmp_t lt_cmp(counted_t<const datum_t>(arr.release()));
// We can't have datum_stream_t::sort because templates suck.
counted_t<table_t> tbl;
counted_t<datum_stream_t> seq;
counted_t<val_t> v0 = arg(0);
if (v0->get_type().is_convertible(val_t::type_t::SELECTION)) {
std::pair<counted_t<table_t>, counted_t<datum_stream_t> > ts
= v0->as_selection();
tbl = ts.first;
seq = ts.second;
} else {
seq = v0->as_seq();
}
counted_t<datum_stream_t> s
= make_counted<sort_datum_stream_t<lt_cmp_t> >(env, lt_cmp, seq, backtrace());
return tbl.has() ? new_val(s, tbl) : new_val(s);
}
virtual const char *name() const { return "orderby"; }
private:
protob_t<const Term> src_term;
};
class distinct_term_t : public op_term_t {
public:
distinct_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1)) { }
private:
static bool lt_cmp(counted_t<const datum_t> l, counted_t<const datum_t> r) { return *l < *r; }
virtual counted_t<val_t> eval_impl() {
scoped_ptr_t<datum_stream_t> s(new sort_datum_stream_t<bool (*)(counted_t<const datum_t>, counted_t<const datum_t>)>(env, lt_cmp, arg(0)->as_seq(), backtrace()));
scoped_ptr_t<datum_t> arr(new datum_t(datum_t::R_ARRAY));
counted_t<const datum_t> last;
while (counted_t<const datum_t> d = s->next()) {
if (last.has() && *last == *d) {
continue;
}
last = d;
arr->add(last);
}
counted_t<datum_stream_t> out
= make_counted<array_datum_stream_t>(env,
counted_t<const datum_t>(arr.release()),
backtrace());
return new_val(out);
}
virtual const char *name() const { return "distinct"; }
};
counted_t<term_t> make_orderby_term(env_t *env, protob_t<const Term> term) {
return make_counted<orderby_term_t>(env, term);
}
counted_t<term_t> make_distinct_term(env_t *env, protob_t<const Term> term) {
return make_counted<distinct_term_t>(env, term);
}
counted_t<term_t> make_asc_term(env_t *env, protob_t<const Term> term) {
return make_counted<asc_term_t>(env, term);
}
counted_t<term_t> make_desc_term(env_t *env, protob_t<const Term> term) {
return make_counted<desc_term_t>(env, term);
}
} // namespace ql
<commit_msg>Adds functions to order_by.<commit_after>#include "rdb_protocol/terms/terms.hpp"
#include <string>
#include <utility>
#include "rdb_protocol/datum_stream.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/op.hpp"
#include "rdb_protocol/pb_utils.hpp"
namespace ql {
// NOTE: `asc` and `desc` don't fit into our type system (they're a hack for
// orderby to avoid string parsing), so we instead literally examine the
// protobuf to determine whether they're present. This is a hack. (This is
// implemented internally in terms of string concatenation because that's what
// the old string-parsing solution was, and this was a quick way to get the new
// behavior that also avoided dumping already-tested code paths. I'm probably
// going to hell for it though.)
class asc_term_t : public op_term_t {
public:
asc_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1)) { }
private:
virtual counted_t<val_t> eval_impl() {
return new_val(make_counted<const datum_t>("+" + arg(0)->as_str()));
}
virtual const char *name() const { return "asc"; }
};
class desc_term_t : public op_term_t {
public:
desc_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1)) { }
private:
virtual counted_t<val_t> eval_impl() {
return new_val(make_counted<const datum_t>("-" + arg(0)->as_str()));
}
virtual const char *name() const { return "desc"; }
};
class orderby_term_t : public op_term_t {
public:
orderby_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1, -1)), src_term(term) { }
private:
class lt_cmp_t {
public:
lt_cmp_t(std::vector<counted_t<val_t> > _comparisons,
term_t *_creator)
: comparisons(_comparisons), creator(_creator) { }
bool operator()(counted_t<const datum_t> l, counted_t<const datum_t> r) {
for (auto it = comparisons.begin(); it != comparisons.end(); ++it) {
counted_t<const datum_t> lval;
counted_t<const datum_t> rval;
if ((*it)->get_type().is_convertible(val_t::type_t::DATUM)) {
std::string attrname = (*it)->as_str();
lval = l->get(attrname, NOTHROW);
rval = r->get(attrname, NOTHROW);
} else if ((*it)->get_type().is_convertible(val_t::type_t::FUNC)) {
lval = (*it)->as_func()->call(l)->as_datum();
rval = (*it)->as_func()->call(r)->as_datum();
} else {
rfail_target(creator, base_exc_t::GENERIC,
"Must pass either DATUM or FUNCTION to %s\n", creator->name());
}
if (!lval.has() && !rval.has()) {
continue;
}
if (!lval.has()) {
return static_cast<bool>(true);
}
if (!rval.has()) {
return static_cast<bool>(false);
}
// TODO: use datum_t::cmp instead to be faster
if (*lval == *rval) {
continue;
}
return static_cast<bool>((*lval < *rval));
}
return false;
}
private:
std::vector<counted_t<val_t> > comparisons;
term_t *creator;
};
virtual counted_t<val_t> eval_impl() {
std::vector<counted_t<val_t> > comparisons;
scoped_ptr_t<datum_t> arr(new datum_t(datum_t::R_ARRAY));
for (size_t i = 1; i < num_args(); ++i) {
comparisons.push_back(arg(i));
}
lt_cmp_t lt_cmp(comparisons, this);
// We can't have datum_stream_t::sort because templates suck.
counted_t<table_t> tbl;
counted_t<datum_stream_t> seq;
counted_t<val_t> v0 = arg(0);
if (v0->get_type().is_convertible(val_t::type_t::SELECTION)) {
std::pair<counted_t<table_t>, counted_t<datum_stream_t> > ts
= v0->as_selection();
tbl = ts.first;
seq = ts.second;
} else {
seq = v0->as_seq();
}
counted_t<datum_stream_t> s
= make_counted<sort_datum_stream_t<lt_cmp_t> >(env, lt_cmp, seq, backtrace());
return tbl.has() ? new_val(s, tbl) : new_val(s);
}
virtual const char *name() const { return "orderby"; }
private:
protob_t<const Term> src_term;
};
class distinct_term_t : public op_term_t {
public:
distinct_term_t(env_t *env, protob_t<const Term> term)
: op_term_t(env, term, argspec_t(1)) { }
private:
static bool lt_cmp(counted_t<const datum_t> l, counted_t<const datum_t> r) { return *l < *r; }
virtual counted_t<val_t> eval_impl() {
scoped_ptr_t<datum_stream_t> s(new sort_datum_stream_t<bool (*)(counted_t<const datum_t>, counted_t<const datum_t>)>(env, lt_cmp, arg(0)->as_seq(), backtrace()));
scoped_ptr_t<datum_t> arr(new datum_t(datum_t::R_ARRAY));
counted_t<const datum_t> last;
while (counted_t<const datum_t> d = s->next()) {
if (last.has() && *last == *d) {
continue;
}
last = d;
arr->add(last);
}
counted_t<datum_stream_t> out
= make_counted<array_datum_stream_t>(env,
counted_t<const datum_t>(arr.release()),
backtrace());
return new_val(out);
}
virtual const char *name() const { return "distinct"; }
};
counted_t<term_t> make_orderby_term(env_t *env, protob_t<const Term> term) {
return make_counted<orderby_term_t>(env, term);
}
counted_t<term_t> make_distinct_term(env_t *env, protob_t<const Term> term) {
return make_counted<distinct_term_t>(env, term);
}
counted_t<term_t> make_asc_term(env_t *env, protob_t<const Term> term) {
return make_counted<asc_term_t>(env, term);
}
counted_t<term_t> make_desc_term(env_t *env, protob_t<const Term> term) {
return make_counted<desc_term_t>(env, term);
}
} // namespace ql
<|endoftext|> |
<commit_before>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <strings.h>
#include <string>
#include <sstream>
#include <signal.h>
#include "config/cmd_args.hpp"
#include "config/code.hpp"
#include "utils.hpp"
#include "worker_pool.hpp"
#include "buffer_cache/mirrored.hpp"
#include "buffer_cache/page_map/array.hpp"
#include "buffer_cache/page_repl/page_repl_random.hpp"
#include "buffer_cache/writeback/writeback.hpp"
#include "buffer_cache/concurrency/rwi_conc.hpp"
#include "serializer/in_place.hpp"
#include "conn_fsm.hpp"
#include "buffer_cache/concurrency/rwi_conc.hpp"
#include "btree/get_fsm.hpp"
#include "btree/set_fsm.hpp"
#include "btree/incr_decr_fsm.hpp"
#include "btree/append_prepend_fsm.hpp"
#include "btree/delete_fsm.hpp"
worker_t::worker_t(int _workerid, int _nqueues,
worker_pool_t *parent_pool, cmd_config_t *cmd_config) {
ref_count = 0;
event_queue = gnew<event_queue_t>(_workerid, _nqueues, parent_pool, this, cmd_config);
total_connections = 0;
curr_connections = 0;
perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "total_connections", (void*)&total_connections));
perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "curr_connections", (void*)&curr_connections));
// Init the slices
nworkers = _nqueues;
workerid = _workerid;
nslices = cmd_config->n_slices;
mkdir(DATA_DIRECTORY, 0777);
for (int i = 0; i < nslices; i++) {
typedef std::basic_string<char, std::char_traits<char>, gnew_alloc<char> > rdbstring_t;
typedef std::basic_stringstream<char, std::char_traits<char>, gnew_alloc<char> > rdbstringstream_t;
rdbstringstream_t out;
rdbstring_t str((char*)cmd_config->db_file_name);
out << workerid << "_" << i;
str += out.str();
slices[i] = gnew<cache_t>(
(char*)str.c_str(),
BTREE_BLOCK_SIZE,
cmd_config->max_cache_size / nworkers,
cmd_config->wait_for_flush,
cmd_config->flush_timer_ms,
cmd_config->flush_threshold_percent);
}
active_slices = true;
}
worker_t::~worker_t() {
check("Error in ~worker_t, cannot delete a worker_t without first deleting its slices", active_slices == true);
delete event_queue;
}
void worker_t::start_worker() {
event_queue->start_queue(this);
}
void worker_t::start_slices() {
for (int i = 0; i < nslices; i++)
slices[i]->start();
}
void worker_t::shutdown() {
shutting_down = true;
for (int i = 0; i < nslices; i++) {
ref_count++;
slices[i]->shutdown(this);
}
}
void worker_t::delete_slices() {
for (int i = 0; i < nslices; i++)
gdelete(slices[i]);
active_slices = false;
}
void worker_t::new_fsm(int data, int &resource, void **source) {
worker_t::conn_fsm_t *fsm =
new worker_t::conn_fsm_t(data, event_queue);
live_fsms.push_back(fsm);
resource = fsm->get_source();
*source = fsm;
printf("Opened socket %d\n", resource);
curr_connections++;
total_connections++;
}
void worker_t::deregister_fsm(void *fsm, int &resource) {
worker_t::conn_fsm_t *cfsm = (worker_t::conn_fsm_t *) fsm;
printf("Closing socket %d\n", cfsm->get_source());
resource = cfsm->get_source();
live_fsms.remove(cfsm);
shutdown_fsms.push_back(cfsm);
curr_connections--;
// TODO: there might be outstanding btrees that we're missing (if
// we're quitting before the the operation completes). We need to
// free the btree structure in this case (more likely the request
// and all the btrees associated with it).
}
bool worker_t::deregister_fsm(int &resource) {
if (live_fsms.empty()) {
return false;
} else {
worker_t::conn_fsm_t *cfsm = live_fsms.head();
deregister_fsm(cfsm, resource);
return true;
}
}
void worker_t::clean_fsms() {
shutdown_fsms.clear();
}
void worker_t::initiate_conn_fsm_transition(event_t *event) {
code_config_t::conn_fsm_t *fsm = (code_config_t::conn_fsm_t*)event->state;
int res = fsm->do_transition(event);
if(res == worker_t::conn_fsm_t::fsm_transition_ok || res == worker_t::conn_fsm_t::fsm_no_data_in_socket) {
// Nothing todo
} else if(res == worker_t::conn_fsm_t::fsm_shutdown_server) {
int res = pthread_kill(event_queue->parent_pool->main_thread, SIGINT);
check("Could not send kill signal to main thread", res != 0);
} else if(res == worker_t::conn_fsm_t::fsm_quit_connection) {
int source;
deregister_fsm(fsm, source);
event_queue->forget_resource(source);
delete fsm;
} else {
check("Unhandled fsm transition result", 1);
}
}
void worker_t::on_btree_completed(code_config_t::btree_fsm_t *btree_fsm) {
// We received a completed btree that belongs to another
// core. Send it off and be merry!
get_cpu_context()->worker->event_queue->message_hub.store_message(btree_fsm->return_cpu, btree_fsm);
}
void worker_t::process_btree_msg(code_config_t::btree_fsm_t *btree_fsm) {
worker_t *worker = get_cpu_context()->worker;
if(btree_fsm->is_finished()) {
// We received a completed btree that belongs to us
btree_fsm->request->on_request_part_completed();
} else {
// We received a new btree that we need to process
// The btree is constructed with no cache; here we must assign it its proper cache
assert(!btree_fsm->cache);
btree_fsm->cache = worker->slice(&btree_fsm->key);
btree_fsm->on_complete = worker_t::on_btree_completed;
code_config_t::btree_fsm_t::transition_result_t btree_res = btree_fsm->do_transition(NULL);
if(btree_res == code_config_t::btree_fsm_t::transition_complete) {
worker_t::on_btree_completed(btree_fsm);
}
}
}
void worker_t::process_perfmon_msg(perfmon_msg_t *msg)
{
worker_t *worker = get_cpu_context()->worker;
event_queue_t *queue = worker->event_queue;
int this_cpu = get_cpu_context()->worker->workerid;
int return_cpu = msg->return_cpu;
switch(msg->state) {
case perfmon_msg_t::sm_request:
// Copy our statistics into the perfmon message and send a response
msg->perfmon = new perfmon_t();
msg->perfmon->copy_from(worker->perfmon);
msg->state = perfmon_msg_t::sm_response;
break;
case perfmon_msg_t::sm_response:
msg->request->on_request_part_completed();
return;
case perfmon_msg_t::sm_copy_cleanup:
// Response has been sent to the client, time to delete the
// copy
delete msg->perfmon;
msg->state = perfmon_msg_t::sm_msg_cleanup;
break;
case perfmon_msg_t::sm_msg_cleanup:
// Copy has been deleted, delete the final message and return
delete msg;
return;
}
msg->return_cpu = this_cpu;
queue->message_hub.store_message(return_cpu, msg);
}
void worker_t::process_lock_msg(event_t *event, rwi_lock_t::lock_request_t *lr) {
lr->callback->on_lock_available();
delete lr;
}
void worker_t::process_log_msg(log_msg_t *msg) {
if (msg->del) {
ref_count--;
delete msg;
} else {
assert(workerid == LOG_WORKER);
log_writer.writef("(%s)Q%d:%s:%d:", msg->level_str(), msg->return_cpu, msg->src_file, msg->src_line);
log_writer.write(msg->str);
msg->del = true;
// No need to change return_cpu because the message will be deleted immediately.
event_queue->message_hub.store_message(msg->return_cpu, msg);
}
}
// Handle events coming from the event queue
void worker_t::event_handler(event_t *event) {
if(event->event_type == et_sock) {
// Got some socket action, let the connection fsm know
initiate_conn_fsm_transition(event);
} else if(event->event_type == et_cpu_event) {
cpu_message_t *msg = (cpu_message_t*)event->state;
switch(msg->type) {
case cpu_message_t::mt_btree:
process_btree_msg((code_config_t::btree_fsm_t*)msg);
break;
case cpu_message_t::mt_lock:
process_lock_msg(event, (rwi_lock_t::lock_request_t*)msg);
break;
case cpu_message_t::mt_perfmon:
process_perfmon_msg((perfmon_msg_t*)msg);
break;
case cpu_message_t::mt_log:
process_log_msg((log_msg_t *) msg);
break;
}
} else {
check("Unknown event in event_handler", 1);
}
}
void worker_t::incr_ref_count() {
ref_count++;
}
void worker_t::decr_ref_count() {
ref_count--;
if (ref_count == 0 && shutting_down) {
event_queue->send_shutdown();
}
}
void worker_t::on_sync() {
decr_ref_count();
}
void worker_pool_t::create_worker_pool(pthread_t main_thread,
int _nworkers, int _nslices)
{
this->main_thread = main_thread;
// Create the workers
if (_nworkers != 0)
nworkers = std::min(_nworkers, MAX_CPUS);
else
nworkers = get_cpu_count();
if (_nslices != 0)
nslices = std::min(_nslices, MAX_SLICES);
else
nslices = DEFAULT_SLICES;
cmd_config->n_workers = nworkers;
cmd_config->n_slices = nslices;
for(int i = 0; i < nworkers; i++) {
workers[i] = gnew<worker_t>(i, nworkers, this, cmd_config);
}
active_worker = 0;
for(int i = 0; i < nworkers; i++) {
workers[i]->event_queue->message_hub.init(i, nworkers, workers);
}
// Start the actual queue
for(int i = 0; i < nworkers; i++) {
workers[i]->start_worker();
}
// TODO: can we move the printing out of here?
printf("Physical cores: %d\n", get_cpu_count());
printf("Using cores: %d\n", nworkers);
printf("Slices per core: %d\n", nslices);
printf("Total RAM: %ldMB\n", get_total_ram() / 1024 / 1024);
printf("Free RAM: %ldMB (%.2f%%)\n",
get_available_ram() / 1024 / 1024,
(double)get_available_ram() / (double)get_total_ram() * 100.0f);
printf("Max cache size: %ldMB\n",
cmd_config->max_cache_size / 1024 / 1024);
// TODO: this whole queue creation business is a mess, refactor
// the way it works.
}
worker_pool_t::worker_pool_t(pthread_t main_thread,
cmd_config_t *_cmd_config)
: cmd_config(_cmd_config)
{
create_worker_pool(main_thread, cmd_config->n_workers, cmd_config->n_slices);
}
worker_pool_t::worker_pool_t(pthread_t main_thread,
int _nworkers, int _nslices, cmd_config_t *_cmd_config)
: cmd_config(_cmd_config)
{
create_worker_pool(main_thread, _nworkers, _nslices);
}
worker_pool_t::~worker_pool_t() {
// Start stopping each event queue
for(int i = 0; i < nworkers; i++) {
workers[i]->event_queue->begin_stopping_queue();
}
// Wait for all of the event queues to finish stopping before destroying any of them
for (int i = 0; i < nworkers; i++) {
workers[i]->event_queue->finish_stopping_queue();
}
// Free the event queues
for(int i = 0; i < nworkers; i++) {
gdelete(workers[i]);
}
nworkers = 0;
// Delete all the custom allocators in the system
for(size_t i = 0; i < all_allocs.size(); i++) {
tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t *allocs
= (tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t*)(all_allocs[i]);
if(allocs) {
for(size_t j = 0; j < allocs->size(); j++) {
gdelete(allocs->operator[](j));
}
}
delete allocs;
}
}
worker_t* worker_pool_t::next_active_worker() {
int worker = active_worker++;
if(active_worker >= nworkers)
active_worker = 0;
return workers[worker];
// TODO: consider introducing randomness to avoid potential
// (intentional and unintentional) attacks on memory allocation
// and CPU utilization.
}
<commit_msg>Moves the conn_fsms out of the event_queue and into the worker. Introduces a bug where the txt_memcached_handler is deleted from the wrong core.<commit_after>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <strings.h>
#include <string>
#include <sstream>
#include <signal.h>
#include "config/cmd_args.hpp"
#include "config/code.hpp"
#include "utils.hpp"
#include "worker_pool.hpp"
#include "buffer_cache/mirrored.hpp"
#include "buffer_cache/page_map/array.hpp"
#include "buffer_cache/page_repl/page_repl_random.hpp"
#include "buffer_cache/writeback/writeback.hpp"
#include "buffer_cache/concurrency/rwi_conc.hpp"
#include "serializer/in_place.hpp"
#include "conn_fsm.hpp"
#include "buffer_cache/concurrency/rwi_conc.hpp"
#include "btree/get_fsm.hpp"
#include "btree/set_fsm.hpp"
#include "btree/incr_decr_fsm.hpp"
#include "btree/append_prepend_fsm.hpp"
#include "btree/delete_fsm.hpp"
worker_t::worker_t(int _workerid, int _nqueues,
worker_pool_t *parent_pool, cmd_config_t *cmd_config) {
ref_count = 0;
event_queue = gnew<event_queue_t>(_workerid, _nqueues, parent_pool, this, cmd_config);
total_connections = 0;
curr_connections = 0;
perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "total_connections", (void*)&total_connections));
perfmon.monitor(var_monitor_t(var_monitor_t::vt_int, "curr_connections", (void*)&curr_connections));
// Init the slices
nworkers = _nqueues;
workerid = _workerid;
nslices = cmd_config->n_slices;
mkdir(DATA_DIRECTORY, 0777);
for (int i = 0; i < nslices; i++) {
typedef std::basic_string<char, std::char_traits<char>, gnew_alloc<char> > rdbstring_t;
typedef std::basic_stringstream<char, std::char_traits<char>, gnew_alloc<char> > rdbstringstream_t;
rdbstringstream_t out;
rdbstring_t str((char*)cmd_config->db_file_name);
out << workerid << "_" << i;
str += out.str();
slices[i] = gnew<cache_t>(
(char*)str.c_str(),
BTREE_BLOCK_SIZE,
cmd_config->max_cache_size / nworkers,
cmd_config->wait_for_flush,
cmd_config->flush_timer_ms,
cmd_config->flush_threshold_percent);
}
active_slices = true;
}
worker_t::~worker_t() {
check("Error in ~worker_t, cannot delete a worker_t without first deleting its slices", active_slices == true);
for (shutdown_fsms_t::iterator it = shutdown_fsms.begin(); it != shutdown_fsms.end(); ++it)
delete *it;
delete event_queue;
}
void worker_t::start_worker() {
event_queue->start_queue(this);
}
void worker_t::start_slices() {
for (int i = 0; i < nslices; i++)
slices[i]->start();
}
void worker_t::shutdown() {
shutting_down = true;
for (int i = 0; i < nslices; i++) {
ref_count++;
slices[i]->shutdown(this);
}
}
void worker_t::delete_slices() {
for (int i = 0; i < nslices; i++)
gdelete(slices[i]);
active_slices = false;
}
void worker_t::new_fsm(int data, int &resource, void **source) {
worker_t::conn_fsm_t *fsm =
new worker_t::conn_fsm_t(data, event_queue);
live_fsms.push_back(fsm);
resource = fsm->get_source();
*source = fsm;
printf("Opened socket %d\n", resource);
curr_connections++;
total_connections++;
}
void worker_t::deregister_fsm(void *fsm, int &resource) {
worker_t::conn_fsm_t *cfsm = (worker_t::conn_fsm_t *) fsm;
printf("Closing socket %d\n", cfsm->get_source());
resource = cfsm->get_source();
live_fsms.remove(cfsm);
shutdown_fsms.push_back(cfsm);
curr_connections--;
// TODO: there might be outstanding btrees that we're missing (if
// we're quitting before the the operation completes). We need to
// free the btree structure in this case (more likely the request
// and all the btrees associated with it).
}
bool worker_t::deregister_fsm(int &resource) {
if (live_fsms.empty()) {
return false;
} else {
worker_t::conn_fsm_t *cfsm = live_fsms.head();
deregister_fsm(cfsm, resource);
return true;
}
}
void worker_t::clean_fsms() {
shutdown_fsms.clear();
}
void worker_t::initiate_conn_fsm_transition(event_t *event) {
code_config_t::conn_fsm_t *fsm = (code_config_t::conn_fsm_t*)event->state;
int res = fsm->do_transition(event);
void worker_t::on_sync() {
decr_ref_count();
}
void worker_pool_t::create_worker_pool(pthread_t main_thread,
int _nworkers, int _nslices)
{
this->main_thread = main_thread;
// Create the workers
if (_nworkers != 0)
nworkers = std::min(_nworkers, MAX_CPUS);
else
nworkers = get_cpu_count();
if (_nslices != 0)
nslices = std::min(_nslices, MAX_SLICES);
else
nslices = DEFAULT_SLICES;
cmd_config->n_workers = nworkers;
cmd_config->n_slices = nslices;
for(int i = 0; i < nworkers; i++) {
workers[i] = gnew<worker_t>(i, nworkers, this, cmd_config);
}
active_worker = 0;
for(int i = 0; i < nworkers; i++) {
workers[i]->event_queue->message_hub.init(i, nworkers, workers);
}
// Start the actual queue
for(int i = 0; i < nworkers; i++) {
workers[i]->start_worker();
}
// TODO: can we move the printing out of here?
printf("Physical cores: %d\n", get_cpu_count());
printf("Using cores: %d\n", nworkers);
printf("Slices per core: %d\n", nslices);
printf("Total RAM: %ldMB\n", get_total_ram() / 1024 / 1024);
printf("Free RAM: %ldMB (%.2f%%)\n",
get_available_ram() / 1024 / 1024,
(double)get_available_ram() / (double)get_total_ram() * 100.0f);
printf("Max cache size: %ldMB\n",
cmd_config->max_cache_size / 1024 / 1024);
// TODO: this whole queue creation business is a mess, refactor
// the way it works.
}
worker_pool_t::worker_pool_t(pthread_t main_thread,
cmd_config_t *_cmd_config)
: cmd_config(_cmd_config)
{
create_worker_pool(main_thread, cmd_config->n_workers, cmd_config->n_slices);
}
worker_pool_t::worker_pool_t(pthread_t main_thread,
int _nworkers, int _nslices, cmd_config_t *_cmd_config)
: cmd_config(_cmd_config)
{
create_worker_pool(main_thread, _nworkers, _nslices);
}
worker_pool_t::~worker_pool_t() {
// Start stopping each event queue
for(int i = 0; i < nworkers; i++) {
workers[i]->event_queue->begin_stopping_queue();
}
// Wait for all of the event queues to finish stopping before destroying any of them
for (int i = 0; i < nworkers; i++) {
workers[i]->event_queue->finish_stopping_queue();
}
// Free the event queues
for(int i = 0; i < nworkers; i++) {
gdelete(workers[i]);
}
nworkers = 0;
// Delete all the custom allocators in the system
for(size_t i = 0; i < all_allocs.size(); i++) {
tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t *allocs
= (tls_small_obj_alloc_accessor<alloc_t>::alloc_vector_t*)(all_allocs[i]);
if(allocs) {
for(size_t j = 0; j < allocs->size(); j++) {
gdelete(allocs->operator[](j));
}
}
delete allocs;
}
}
worker_t* worker_pool_t::next_active_worker() {
int worker = active_worker++;
if(active_worker >= nworkers)
active_worker = 0;
return workers[worker];
// TODO: consider introducing randomness to avoid potential
// (intentional and unintentional) attacks on memory allocation
// and CPU utilization.
}
<|endoftext|> |
<commit_before>/**
* @file llpopupview.cpp
* @brief Holds transient popups
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2010, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llpopupview.h"
static LLRegisterPanelClassWrapper<LLPopupView> r("popup_holder");
bool view_visible_and_enabled(LLView* viewp)
{
return viewp->getVisible() && viewp->getEnabled();
}
bool view_visible(LLView* viewp)
{
return viewp->getVisible();
}
LLPopupView::LLPopupView()
{
// register ourself as handler of UI popups
LLUI::setPopupFuncs(boost::bind(&LLPopupView::addPopup, this, _1), boost::bind(&LLPopupView::removePopup, this, _1), boost::bind(&LLPopupView::clearPopups, this));
}
LLPopupView::~LLPopupView()
{
// set empty callback function so we can't handle popups anymore
LLUI::setPopupFuncs(LLUI::add_popup_t(), LLUI::remove_popup_t(), LLUI::clear_popups_t());
}
void LLPopupView::draw()
{
S32 screen_x, screen_y;
// remove dead popups
for (popup_list_t::iterator popup_it = mPopups.begin();
popup_it != mPopups.end();)
{
if (!popup_it->get())
{
mPopups.erase(popup_it++);
}
else
{
popup_it++;
}
}
// draw in reverse order (most recent is on top)
for (popup_list_t::reverse_iterator popup_it = mPopups.rbegin();
popup_it != mPopups.rend();)
{
LLView* popup = popup_it->get();
if (popup->getVisible())
{
popup->localPointToScreen(0, 0, &screen_x, &screen_y);
LLUI::pushMatrix();
{
LLUI::translate( (F32) screen_x, (F32) screen_y, 0.f);
popup->draw();
}
LLUI::popMatrix();
}
++popup_it;
}
LLPanel::draw();
}
BOOL LLPopupView::handleMouseEvent(boost::function<BOOL(LLView*, S32, S32)> func,
boost::function<bool(LLView*)> predicate,
S32 x, S32 y,
bool close_popups)
{
for (popup_list_t::iterator popup_it = mPopups.begin();
popup_it != mPopups.end();)
{
LLView* popup = popup_it->get();
if (!popup
|| !predicate(popup))
{
++popup_it;
continue;
}
S32 popup_x, popup_y;
if (localPointToOtherView(x, y, &popup_x, &popup_y, popup)
&& popup->pointInView(popup_x, popup_y))
{
if (func(popup, popup_x, popup_y))
{
return TRUE;
}
}
if (close_popups)
{
popup_list_t::iterator cur_popup_it = popup_it++;
mPopups.erase(cur_popup_it);
popup->onTopLost();
}
else
{
++popup_it;
}
}
return FALSE;
}
BOOL LLPopupView::handleMouseDown(S32 x, S32 y, MASK mask)
{
if (!handleMouseEvent(boost::bind(&LLMouseHandler::handleMouseDown, _1, _2, _3, mask), view_visible_and_enabled, x, y, true))
{
return FALSE;
}
return TRUE;
}
BOOL LLPopupView::handleMouseUp(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleMouseUp, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleMiddleMouseDown(S32 x, S32 y, MASK mask)
{
if (!handleMouseEvent(boost::bind(&LLMouseHandler::handleMiddleMouseDown, _1, _2, _3, mask), view_visible_and_enabled, x, y, true))
{
return FALSE;
}
return TRUE;
}
BOOL LLPopupView::handleMiddleMouseUp(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleMiddleMouseUp, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
if (!handleMouseEvent(boost::bind(&LLMouseHandler::handleRightMouseDown, _1, _2, _3, mask), view_visible_and_enabled, x, y, true))
{
return FALSE;
}
return TRUE;
}
BOOL LLPopupView::handleRightMouseUp(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleRightMouseUp, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleDoubleClick(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleDoubleClick, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleHover(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleHover, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleScrollWheel(S32 x, S32 y, S32 clicks)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleScrollWheel, _1, _2, _3, clicks), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleToolTip(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleToolTip, _1, _2, _3, mask), view_visible, x, y, false);
}
void LLPopupView::addPopup(LLView* popup)
{
if (popup)
{
popup_list_t::iterator iter = std::find(mPopups.begin(), mPopups.end(), popup->getHandle());
if(iter != mPopups.end())
{
mPopups.erase(iter);
}
mPopups.push_front(popup->getHandle());
}
}
void LLPopupView::removePopup(LLView* popup)
{
if (popup)
{
if (gFocusMgr.childHasKeyboardFocus(popup))
{
gFocusMgr.setKeyboardFocus(NULL);
}
popup_list_t::iterator iter = std::find(mPopups.begin(), mPopups.end(), popup->getHandle());
if(iter != mPopups.end())
{
mPopups.erase(iter);
}
popup->onTopLost();
}
}
void LLPopupView::clearPopups()
{
for (popup_list_t::iterator popup_it = mPopups.begin();
popup_it != mPopups.end();)
{
LLView* popup = popup_it->get();
popup_list_t::iterator cur_popup_it = popup_it;
++popup_it;
mPopups.erase(cur_popup_it);
popup->onTopLost();
}
}
<commit_msg>duplicating fix for EXT-6256 Viewer 2 - Search field set the focus out of the field when user type 'ne' or 'na' or some other letters combinations<commit_after>/**
* @file llpopupview.cpp
* @brief Holds transient popups
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2010, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llpopupview.h"
static LLRegisterPanelClassWrapper<LLPopupView> r("popup_holder");
bool view_visible_and_enabled(LLView* viewp)
{
return viewp->getVisible() && viewp->getEnabled();
}
bool view_visible(LLView* viewp)
{
return viewp->getVisible();
}
LLPopupView::LLPopupView()
{
// register ourself as handler of UI popups
LLUI::setPopupFuncs(boost::bind(&LLPopupView::addPopup, this, _1), boost::bind(&LLPopupView::removePopup, this, _1), boost::bind(&LLPopupView::clearPopups, this));
}
LLPopupView::~LLPopupView()
{
// set empty callback function so we can't handle popups anymore
LLUI::setPopupFuncs(LLUI::add_popup_t(), LLUI::remove_popup_t(), LLUI::clear_popups_t());
}
void LLPopupView::draw()
{
S32 screen_x, screen_y;
// remove dead popups
for (popup_list_t::iterator popup_it = mPopups.begin();
popup_it != mPopups.end();)
{
if (!popup_it->get())
{
mPopups.erase(popup_it++);
}
else
{
popup_it++;
}
}
// draw in reverse order (most recent is on top)
for (popup_list_t::reverse_iterator popup_it = mPopups.rbegin();
popup_it != mPopups.rend();)
{
LLView* popup = popup_it->get();
if (popup->getVisible())
{
popup->localPointToScreen(0, 0, &screen_x, &screen_y);
LLUI::pushMatrix();
{
LLUI::translate( (F32) screen_x, (F32) screen_y, 0.f);
popup->draw();
}
LLUI::popMatrix();
}
++popup_it;
}
LLPanel::draw();
}
BOOL LLPopupView::handleMouseEvent(boost::function<BOOL(LLView*, S32, S32)> func,
boost::function<bool(LLView*)> predicate,
S32 x, S32 y,
bool close_popups)
{
for (popup_list_t::iterator popup_it = mPopups.begin();
popup_it != mPopups.end();)
{
LLView* popup = popup_it->get();
if (!popup
|| !predicate(popup))
{
++popup_it;
continue;
}
S32 popup_x, popup_y;
if (localPointToOtherView(x, y, &popup_x, &popup_y, popup)
&& popup->pointInView(popup_x, popup_y))
{
if (func(popup, popup_x, popup_y))
{
return TRUE;
}
}
if (close_popups)
{
popup_list_t::iterator cur_popup_it = popup_it++;
mPopups.erase(cur_popup_it);
popup->onTopLost();
}
else
{
++popup_it;
}
}
return FALSE;
}
BOOL LLPopupView::handleMouseDown(S32 x, S32 y, MASK mask)
{
if (!handleMouseEvent(boost::bind(&LLMouseHandler::handleMouseDown, _1, _2, _3, mask), view_visible_and_enabled, x, y, true))
{
return FALSE;
}
return TRUE;
}
BOOL LLPopupView::handleMouseUp(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleMouseUp, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleMiddleMouseDown(S32 x, S32 y, MASK mask)
{
if (!handleMouseEvent(boost::bind(&LLMouseHandler::handleMiddleMouseDown, _1, _2, _3, mask), view_visible_and_enabled, x, y, true))
{
return FALSE;
}
return TRUE;
}
BOOL LLPopupView::handleMiddleMouseUp(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleMiddleMouseUp, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
if (!handleMouseEvent(boost::bind(&LLMouseHandler::handleRightMouseDown, _1, _2, _3, mask), view_visible_and_enabled, x, y, true))
{
return FALSE;
}
return TRUE;
}
BOOL LLPopupView::handleRightMouseUp(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleRightMouseUp, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleDoubleClick(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleDoubleClick, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleHover(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleHover, _1, _2, _3, mask), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleScrollWheel(S32 x, S32 y, S32 clicks)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleScrollWheel, _1, _2, _3, clicks), view_visible_and_enabled, x, y, false);
}
BOOL LLPopupView::handleToolTip(S32 x, S32 y, MASK mask)
{
return handleMouseEvent(boost::bind(&LLMouseHandler::handleToolTip, _1, _2, _3, mask), view_visible, x, y, false);
}
void LLPopupView::addPopup(LLView* popup)
{
if (popup)
{
popup_list_t::iterator iter = std::find(mPopups.begin(), mPopups.end(), popup->getHandle());
if(iter != mPopups.end())
{
mPopups.erase(iter);
}
mPopups.push_front(popup->getHandle());
}
}
void LLPopupView::removePopup(LLView* popup)
{
if (popup)
{
popup_list_t::iterator iter = std::find(mPopups.begin(), mPopups.end(), popup->getHandle());
if(iter != mPopups.end())
{
mPopups.erase(iter);
}
popup->onTopLost();
}
}
void LLPopupView::clearPopups()
{
for (popup_list_t::iterator popup_it = mPopups.begin();
popup_it != mPopups.end();)
{
LLView* popup = popup_it->get();
popup_list_t::iterator cur_popup_it = popup_it;
++popup_it;
mPopups.erase(cur_popup_it);
popup->onTopLost();
}
}
<|endoftext|> |
<commit_before>#ifndef HASH_ID_HPP_
#define HASH_ID_HPP_
#include <chrono>
#include <cstring>
#include <functional>
#include <iomanip>
#include <sstream>
namespace sm {
/**
* 128 bit hash. Can be used as key to unordered containers.
*/
class HashId {
public:
/**
* Initializes to an invalid Hash
*/
inline HashId() {
setInvalid();
}
/**
* Copy constructor
*/
inline HashId(const HashId& other){
*this = other;
}
/**
* Generates a random Hash ID seeded from the nanosecond time of the first
* call of this function
*/
inline static HashId random() {
HashId generated;
generated.randomize();
return generated;
}
/**
* Returns hexadecimal string for debugging or serialization
*/
inline const std::string hexString() const {
std::ostringstream ss;
for (size_t i = 0; i < sizeof(val_); ++i){
ss << std::hex << std::setfill('0') << std::setw(2) <<
static_cast<int>(val_.c[i]);
}
return ss.str();
}
/**
* Deserialize from hexadecimal string. Serialization and Deserialization
* could be made more performant by using blobs.
*/
inline bool fromHexString(const std::string& hexString) {
// hexadecimal string takes 2 characters per byte
if (hexString.size() != 2*sizeof(val_)){
return false;
}
for (size_t i = 0; i < sizeof(val_); ++i){
unsigned int integerValue;
std::istringstream ss(std::string(hexString, 2*i, 2));
ss >> std::hex >> integerValue;
val_.c[i] = static_cast<unsigned char>(integerValue);
}
return true;
}
/**
* Randomizes to ID seeded from the nanosecond time of the first
* call of this function
*/
inline void randomize(){
static std::mt19937_64 rng(time64());
val_.u64[0] = rng();
val_.u64[1] = rng();
}
inline void operator =(const HashId& other) {
memcpy(&val_, &other.val_, sizeof(val_));
}
inline bool operator <(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] < other.val_.u64[1];
}
return val_.u64[0] < other.val_.u64[0];
}
inline bool operator >(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] > other.val_.u64[1];
}
return val_.u64[0] > other.val_.u64[0];
}
inline bool operator ==(const HashId& other) const {
return val_.u64[0] == other.val_.u64[0] && val_.u64[1] == other.val_.u64[1];
}
inline bool operator !=(const HashId& other) const{
return !(*this == other);
}
/**
* Invalidation mechanism
*/
inline void setInvalid() {
memset(&val_, 0, sizeof(val_));
}
inline bool isValid() const {
return val_.u64[0] != 0 || val_.u64[1] != 0;
}
private:
/**
* Time seed from nanoseconds. Covers 584 years if we assume no two agents
* initialize in the same nanosecond.
*/
inline static int64_t time64() {
std::chrono::system_clock::duration current =
std::chrono::high_resolution_clock::now().time_since_epoch();
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
// count() specified to return at least 64 bits
return duration_cast<nanoseconds>(current).count();
}
/**
* Internal representation
*/
union HashVal {
unsigned char c[16];
uint_fast64_t u64[2];
};
HashVal val_;
};
} // namespace sm
namespace std{
template<>
struct hash<sm::HashId>{
typedef sm::HashId argument_type;
typedef std::size_t value_type;
value_type operator()(const argument_type& hashId) const {
return std::hash<std::string>()(hashId.hexString());
}
};
} // namespace std
#endif /* HASH_ID_HPP_ */
<commit_msg>Another include that was missing but didn't surface in tests.<commit_after>#ifndef HASH_ID_HPP_
#define HASH_ID_HPP_
#include <chrono>
#include <cstring>
#include <functional>
#include <iomanip>
#include <random>
#include <sstream>
namespace sm {
/**
* 128 bit hash. Can be used as key to unordered containers.
*/
class HashId {
public:
/**
* Initializes to an invalid Hash
*/
inline HashId() {
setInvalid();
}
/**
* Copy constructor
*/
inline HashId(const HashId& other){
*this = other;
}
/**
* Generates a random Hash ID seeded from the nanosecond time of the first
* call of this function
*/
inline static HashId random() {
HashId generated;
generated.randomize();
return generated;
}
/**
* Returns hexadecimal string for debugging or serialization
*/
inline const std::string hexString() const {
std::ostringstream ss;
for (size_t i = 0; i < sizeof(val_); ++i){
ss << std::hex << std::setfill('0') << std::setw(2) <<
static_cast<int>(val_.c[i]);
}
return ss.str();
}
/**
* Deserialize from hexadecimal string. Serialization and Deserialization
* could be made more performant by using blobs.
*/
inline bool fromHexString(const std::string& hexString) {
// hexadecimal string takes 2 characters per byte
if (hexString.size() != 2*sizeof(val_)){
return false;
}
for (size_t i = 0; i < sizeof(val_); ++i){
unsigned int integerValue;
std::istringstream ss(std::string(hexString, 2*i, 2));
ss >> std::hex >> integerValue;
val_.c[i] = static_cast<unsigned char>(integerValue);
}
return true;
}
/**
* Randomizes to ID seeded from the nanosecond time of the first
* call of this function
*/
inline void randomize(){
static std::mt19937_64 rng(time64());
val_.u64[0] = rng();
val_.u64[1] = rng();
}
inline void operator =(const HashId& other) {
memcpy(&val_, &other.val_, sizeof(val_));
}
inline bool operator <(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] < other.val_.u64[1];
}
return val_.u64[0] < other.val_.u64[0];
}
inline bool operator >(const HashId& other) const {
if (val_.u64[0] == other.val_.u64[0]){
return val_.u64[1] > other.val_.u64[1];
}
return val_.u64[0] > other.val_.u64[0];
}
inline bool operator ==(const HashId& other) const {
return val_.u64[0] == other.val_.u64[0] && val_.u64[1] == other.val_.u64[1];
}
inline bool operator !=(const HashId& other) const{
return !(*this == other);
}
/**
* Invalidation mechanism
*/
inline void setInvalid() {
memset(&val_, 0, sizeof(val_));
}
inline bool isValid() const {
return val_.u64[0] != 0 || val_.u64[1] != 0;
}
private:
/**
* Time seed from nanoseconds. Covers 584 years if we assume no two agents
* initialize in the same nanosecond.
*/
inline static int64_t time64() {
std::chrono::system_clock::duration current =
std::chrono::high_resolution_clock::now().time_since_epoch();
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
// count() specified to return at least 64 bits
return duration_cast<nanoseconds>(current).count();
}
/**
* Internal representation
*/
union HashVal {
unsigned char c[16];
uint_fast64_t u64[2];
};
HashVal val_;
};
} // namespace sm
namespace std{
template<>
struct hash<sm::HashId>{
typedef sm::HashId argument_type;
typedef std::size_t value_type;
value_type operator()(const argument_type& hashId) const {
return std::hash<std::string>()(hashId.hexString());
}
};
} // namespace std
#endif /* HASH_ID_HPP_ */
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Gael Guennebaud <[email protected]>
//
// 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 "main.h"
#include <Eigen/LU>
#include <Eigen/Cholesky>
#include <Eigen/QR>
// This file test inplace decomposition through Ref<>, as supported by Cholesky, LU, and QR decompositions.
template<typename DecType,typename MatrixType> void inplace(bool square = false, bool SPD = false)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> RhsType;
typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> ResType;
Index rows = MatrixType::RowsAtCompileTime==Dynamic ? internal::random<Index>(2,EIGEN_TEST_MAX_SIZE/2) : MatrixType::RowsAtCompileTime;
Index cols = MatrixType::ColsAtCompileTime==Dynamic ? (square?rows:internal::random<Index>(2,rows)) : MatrixType::ColsAtCompileTime;
MatrixType A = MatrixType::Random(rows,cols);
RhsType b = RhsType::Random(rows);
ResType x(cols);
if(SPD)
{
assert(square);
A.topRows(cols) = A.topRows(cols).adjoint() * A.topRows(cols);
A.diagonal().array() += 1e-3;
}
MatrixType A0 = A;
MatrixType A1 = A;
DecType dec(A);
// Check that the content of A has been modified
VERIFY_IS_NOT_APPROX( A, A0 );
// Check that the decomposition is correct:
if(rows==cols)
{
VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
// Check that modifying A breaks the current dec:
A.setRandom();
if(rows==cols)
{
VERIFY_IS_NOT_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_NOT_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
// Check that calling compute(A1) does not modify A1:
A = A0;
dec.compute(A1);
VERIFY_IS_EQUAL(A0,A1);
VERIFY_IS_NOT_APPROX( A, A0 );
if(rows==cols)
{
VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
}
void test_inplace_decomposition()
{
EIGEN_UNUSED typedef Matrix<double,4,3> Matrix43d;
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1(( inplace<LLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));
CALL_SUBTEST_1(( inplace<LLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));
CALL_SUBTEST_2(( inplace<LDLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));
CALL_SUBTEST_2(( inplace<LDLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));
CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));
CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));
CALL_SUBTEST_4(( inplace<FullPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));
CALL_SUBTEST_4(( inplace<FullPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));
CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<Matrix43d> >, Matrix43d>(false,false) ));
}
}
<commit_msg>Fix warning.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Gael Guennebaud <[email protected]>
//
// 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 "main.h"
#include <Eigen/LU>
#include <Eigen/Cholesky>
#include <Eigen/QR>
// This file test inplace decomposition through Ref<>, as supported by Cholesky, LU, and QR decompositions.
template<typename DecType,typename MatrixType> void inplace(bool square = false, bool SPD = false)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> RhsType;
typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> ResType;
Index rows = MatrixType::RowsAtCompileTime==Dynamic ? internal::random<Index>(2,EIGEN_TEST_MAX_SIZE/2) : Index(MatrixType::RowsAtCompileTime);
Index cols = MatrixType::ColsAtCompileTime==Dynamic ? (square?rows:internal::random<Index>(2,rows)) : Index(MatrixType::ColsAtCompileTime);
MatrixType A = MatrixType::Random(rows,cols);
RhsType b = RhsType::Random(rows);
ResType x(cols);
if(SPD)
{
assert(square);
A.topRows(cols) = A.topRows(cols).adjoint() * A.topRows(cols);
A.diagonal().array() += 1e-3;
}
MatrixType A0 = A;
MatrixType A1 = A;
DecType dec(A);
// Check that the content of A has been modified
VERIFY_IS_NOT_APPROX( A, A0 );
// Check that the decomposition is correct:
if(rows==cols)
{
VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
// Check that modifying A breaks the current dec:
A.setRandom();
if(rows==cols)
{
VERIFY_IS_NOT_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_NOT_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
// Check that calling compute(A1) does not modify A1:
A = A0;
dec.compute(A1);
VERIFY_IS_EQUAL(A0,A1);
VERIFY_IS_NOT_APPROX( A, A0 );
if(rows==cols)
{
VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
}
void test_inplace_decomposition()
{
EIGEN_UNUSED typedef Matrix<double,4,3> Matrix43d;
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1(( inplace<LLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));
CALL_SUBTEST_1(( inplace<LLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));
CALL_SUBTEST_2(( inplace<LDLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));
CALL_SUBTEST_2(( inplace<LDLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));
CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));
CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));
CALL_SUBTEST_4(( inplace<FullPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));
CALL_SUBTEST_4(( inplace<FullPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));
CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<Matrix43d> >, Matrix43d>(false,false) ));
}
}
<|endoftext|> |
<commit_before>/*
*
* Author: Jeffrey Leung
* Last edited: 2015-09-19
*
* This C++ file tests the Labyrinth class implementation.
*
*/
#include <exception>
#include <iostream>
#include <stdexcept>
#include "../include/room_properties.hpp"
#include "../include/coordinate.hpp"
#include "../include/labyrinth.hpp"
int main()
{
std::cout << std::endl
<< "TESTING LABYRINTH.CPP IMPLEMENTATION" << std::endl
<< "________________________________________________" << std::endl
<< std::endl;
std::cout << "Creating a basic, empty Labyrinth with:" << std::endl
<< " x size = 3" << std::endl
<< " y size = 5" << std::endl;
Labyrinth l1( 3, 5 );
std::cout << "Completed." << std::endl;
std::cout << std::endl;
std::cout << "Type 1 to attempt to create a Labyrinth with x size = 0."
<< std::endl
<< "Type 2 to attempt to create a Labyrinth with y size = 0."
<< std::endl
<< "Type 3 to attempt to create a Labyrinth with x size = "
<< "y size = 0."
<< std::endl
<< "Type 0 to continue."
<< std::endl
<< "> ";
char c = ' ';
while ( c < '0' || c > '3' )
{
std::cin >> c;
switch( c )
{
case( '1' ):
try
{
Labyrinth l_empty( 0, 10 );
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
}
break;
case( '2' ):
try
{
Labyrinth l_empty( 10, 0 );
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
}
break;
case( '3' ):
try
{
Labyrinth l_empty( 0, 0 );
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
}
break;
case( '0' ):
break;
default:
std::cout << std::endl
<< "Error: That was not a valid input; please try again: ";
break;
}
}
std::cout << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "All tests completed." << std::endl;
std::cout << std::endl;
std::cout << "Press enter to exit.";
getchar();
std::cout << std::endl;
return 0;
}
<commit_msg>Laby testing: Adding tests for ConnectRooms().<commit_after>/*
*
* Author: Jeffrey Leung
* Last edited: 2016-01-15
*
* This C++ file tests the Labyrinth class implementation.
*
*/
#include <exception>
#include <iostream>
#include <stdexcept>
#include "../include/room_properties.hpp"
#include "../include/coordinate.hpp"
#include "../include/labyrinth.hpp"
int main()
{
std::cout << std::endl
<< "TESTING LABYRINTH.CPP IMPLEMENTATION" << std::endl
<< "________________________________________________" << std::endl
<< std::endl;
std::cout << "Creating a basic, empty Labyrinth with:" << std::endl
<< " x size = 3" << std::endl
<< " y size = 5" << std::endl;
Labyrinth l1( 3, 5 );
std::cout << "Completed." << std::endl;
std::cout << std::endl;
std::cout << "Type 1 to attempt to create a Labyrinth with x size = 0."
<< std::endl
<< "Type 2 to attempt to create a Labyrinth with y size = 0."
<< std::endl
<< "Type 3 to attempt to create a Labyrinth with x size = "
<< "y size = 0."
<< std::endl
<< "Type 0 to continue."
<< std::endl
<< "> ";
char c = ' ';
while ( c < '0' || c > '3' )
{
std::cin >> c;
switch( c )
{
case( '1' ):
try
{
Labyrinth l_empty( 0, 10 );
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
}
break;
case( '2' ):
try
{
Labyrinth l_empty( 10, 0 );
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
}
break;
case( '3' ):
try
{
Labyrinth l_empty( 0, 0 );
}
catch( std::exception& e )
{
std::cout << e.what() << std::endl;
}
break;
case( '0' ):
break;
default:
std::cout << std::endl
<< "Error: That was not a valid input; please try again: ";
break;
}
}
std::cout << std::endl;
std::cout << "________________________________________________"
<< std::endl << std::endl
<< "TESTING CONNECTROOMS():"
<< std::endl << std::endl;
Coordinate c_0_0(0, 0);
Coordinate c_0_1(0, 1);
Coordinate c_1_0(1, 0);
Coordinate c_1_1(1, 1);
Coordinate c_2_1(2, 1);
std::cout << "Connecting horizontally adjacent rooms (0, 0) and (1, 0):"
<< std::endl;
try
{
l1.ConnectRooms( c_0_0, c_1_0 );
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "Connecting horizontally adjacent rooms (1, 1) and (0, 1):"
<< std::endl;
try
{
l1.ConnectRooms( c_1_1, c_0_1 );
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "Connecting vertically adjacent rooms (0, 0) and (0, 1):"
<< std::endl;
try
{
l1.ConnectRooms(c_0_0, c_0_1);
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "Connecting vertically adjacent rooms (1, 1) and (1, 0):"
<< std::endl;
try
{
l1.ConnectRooms(c_1_1, c_1_0);
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "Connecting diagonally adjacent rooms (0, 0) and (1, 1) "
<< "(An error should be thrown):"
<< std::endl;
try
{
l1.ConnectRooms(c_0_0, c_1_1);
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "Connecting diagonally adjacent rooms (0, 1) and (1, 0) "
<< "(An error should be thrown):"
<< std::endl;
try
{
l1.ConnectRooms(c_0_1, c_1_0);
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "Connecting diagonally adjacent rooms (0, 1) and (1, 0) "
<< "(An error should be thrown):"
<< std::endl;
try
{
l1.ConnectRooms(c_0_1, c_1_0);
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "Connecting non-adjacent rooms (0, 0) and (2, 1) "
<< "(An error should be thrown):"
<< std::endl;
try
{
l1.ConnectRooms(c_0_0, c_2_1);
}
catch (const std::exception& e)
{
std::cout << e.what();
}
std::cout << "Done." << std::endl << std::endl;
std::cout << "________________________________________________" << std::endl;
std::cout << std::endl;
std::cout << "All tests completed." << std::endl;
std::cout << std::endl;
std::cout << "Press enter to exit.";
getchar();getchar();
std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>//===-- main.c --------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
template <typename T>
class Foo
{
public:
Foo () : object() {}
Foo (T x) : object(x) {}
T getObject() { return object; }
private:
T object;
};
int main (int argc, char const *argv[])
{
Foo<int> foo_x('a');
Foo<wchar_t> foo_y(L'a');
const wchar_t *mazeltov = L"מזל טוב";
wchar_t *ws_NULL = nullptr;
wchar_t *ws_empty = L"";
wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž";
memcpy(array, array_source, 39 * sizeof(wchar_t));
return 0; // Set break point at this line.
}
<commit_msg>Fix compile error in TestCxxWCharT on Linux<commit_after>//===-- main.c --------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <cstring>
template <typename T>
class Foo
{
public:
Foo () : object() {}
Foo (T x) : object(x) {}
T getObject() { return object; }
private:
T object;
};
int main (int argc, char const *argv[])
{
Foo<int> foo_x('a');
Foo<wchar_t> foo_y(L'a');
const wchar_t *mazeltov = L"מזל טוב";
wchar_t *ws_NULL = nullptr;
wchar_t *ws_empty = L"";
wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž";
memcpy(array, array_source, 39 * sizeof(wchar_t));
return 0; // Set break point at this line.
}
<|endoftext|> |
<commit_before>//===- X86InstrInfo.cpp - X86 Instruction Information -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the X86 implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//
#include "X86InstrInfo.h"
#include "X86.h"
#include "X86InstrBuilder.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "X86GenInstrInfo.inc"
using namespace llvm;
X86InstrInfo::X86InstrInfo()
: TargetInstrInfo(X86Insts, sizeof(X86Insts)/sizeof(X86Insts[0])) {
}
bool X86InstrInfo::isMoveInstr(const MachineInstr& MI,
unsigned& sourceReg,
unsigned& destReg) const {
MachineOpCode oc = MI.getOpcode();
if (oc == X86::MOV8rr || oc == X86::MOV16rr || oc == X86::MOV32rr ||
oc == X86::MOV16to16_ || oc == X86::MOV32to32_ ||
oc == X86::FpMOV || oc == X86::MOVSSrr || oc == X86::MOVSDrr ||
oc == X86::FsMOVAPSrr || oc == X86::FsMOVAPDrr ||
oc == X86::MOVAPSrr || oc == X86::MOVAPDrr ||
oc == X86::MOVSS2PSrr || oc == X86::MOVSD2PDrr ||
oc == X86::MOVPS2SSrr || oc == X86::MOVPD2SDrr ||
oc == X86::MOVDI2PDIrr || oc == X86::MOVQI2PQIrr ||
oc == X86::MOVPDI2DIrr) {
assert(MI.getNumOperands() == 2 &&
MI.getOperand(0).isRegister() &&
MI.getOperand(1).isRegister() &&
"invalid register-register move instruction");
sourceReg = MI.getOperand(1).getReg();
destReg = MI.getOperand(0).getReg();
return true;
}
return false;
}
unsigned X86InstrInfo::isLoadFromStackSlot(MachineInstr *MI,
int &FrameIndex) const {
switch (MI->getOpcode()) {
default: break;
case X86::MOV8rm:
case X86::MOV16rm:
case X86::MOV16_rm:
case X86::MOV32rm:
case X86::MOV32_rm:
case X86::FpLD64m:
case X86::MOVSSrm:
case X86::MOVSDrm:
case X86::MOVAPSrm:
case X86::MOVAPDrm:
if (MI->getOperand(1).isFrameIndex() && MI->getOperand(2).isImmediate() &&
MI->getOperand(3).isRegister() && MI->getOperand(4).isImmediate() &&
MI->getOperand(2).getImmedValue() == 1 &&
MI->getOperand(3).getReg() == 0 &&
MI->getOperand(4).getImmedValue() == 0) {
FrameIndex = MI->getOperand(1).getFrameIndex();
return MI->getOperand(0).getReg();
}
break;
}
return 0;
}
unsigned X86InstrInfo::isStoreToStackSlot(MachineInstr *MI,
int &FrameIndex) const {
switch (MI->getOpcode()) {
default: break;
case X86::MOV8mr:
case X86::MOV16mr:
case X86::MOV16_mr:
case X86::MOV32mr:
case X86::MOV32_mr:
case X86::FpSTP64m:
case X86::MOVSSmr:
case X86::MOVSDmr:
case X86::MOVAPSmr:
case X86::MOVAPDmr:
if (MI->getOperand(0).isFrameIndex() && MI->getOperand(1).isImmediate() &&
MI->getOperand(2).isRegister() && MI->getOperand(3).isImmediate() &&
MI->getOperand(1).getImmedValue() == 1 &&
MI->getOperand(2).getReg() == 0 &&
MI->getOperand(3).getImmedValue() == 0) {
FrameIndex = MI->getOperand(0).getFrameIndex();
return MI->getOperand(4).getReg();
}
break;
}
return 0;
}
/// convertToThreeAddress - This method must be implemented by targets that
/// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
/// may be able to convert a two-address instruction into a true
/// three-address instruction on demand. This allows the X86 target (for
/// example) to convert ADD and SHL instructions into LEA instructions if they
/// would require register copies due to two-addressness.
///
/// This method returns a null pointer if the transformation cannot be
/// performed, otherwise it returns the new instruction.
///
MachineInstr *X86InstrInfo::convertToThreeAddress(MachineInstr *MI) const {
// All instructions input are two-addr instructions. Get the known operands.
unsigned Dest = MI->getOperand(0).getReg();
unsigned Src = MI->getOperand(1).getReg();
// FIXME: None of these instructions are promotable to LEAs without
// additional information. In particular, LEA doesn't set the flags that
// add and inc do. :(
return 0;
// FIXME: 16-bit LEA's are really slow on Athlons, but not bad on P4's. When
// we have subtarget support, enable the 16-bit LEA generation here.
bool DisableLEA16 = true;
switch (MI->getOpcode()) {
case X86::INC32r:
assert(MI->getNumOperands() == 2 && "Unknown inc instruction!");
return addRegOffset(BuildMI(X86::LEA32r, 5, Dest), Src, 1);
case X86::INC16r:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 2 && "Unknown inc instruction!");
return addRegOffset(BuildMI(X86::LEA16r, 5, Dest), Src, 1);
case X86::DEC32r:
assert(MI->getNumOperands() == 2 && "Unknown dec instruction!");
return addRegOffset(BuildMI(X86::LEA32r, 5, Dest), Src, -1);
case X86::DEC16r:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 2 && "Unknown dec instruction!");
return addRegOffset(BuildMI(X86::LEA16r, 5, Dest), Src, -1);
case X86::ADD32rr:
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
return addRegReg(BuildMI(X86::LEA32r, 5, Dest), Src,
MI->getOperand(2).getReg());
case X86::ADD16rr:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
return addRegReg(BuildMI(X86::LEA16r, 5, Dest), Src,
MI->getOperand(2).getReg());
case X86::ADD32ri:
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
if (MI->getOperand(2).isImmediate())
return addRegOffset(BuildMI(X86::LEA32r, 5, Dest), Src,
MI->getOperand(2).getImmedValue());
return 0;
case X86::ADD16ri:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
if (MI->getOperand(2).isImmediate())
return addRegOffset(BuildMI(X86::LEA16r, 5, Dest), Src,
MI->getOperand(2).getImmedValue());
break;
case X86::SHL16ri:
if (DisableLEA16) return 0;
case X86::SHL32ri:
assert(MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate() &&
"Unknown shl instruction!");
unsigned ShAmt = MI->getOperand(2).getImmedValue();
if (ShAmt == 1 || ShAmt == 2 || ShAmt == 3) {
X86AddressMode AM;
AM.Scale = 1 << ShAmt;
AM.IndexReg = Src;
unsigned Opc = MI->getOpcode() == X86::SHL32ri ? X86::LEA32r :X86::LEA16r;
return addFullAddress(BuildMI(Opc, 5, Dest), AM);
}
break;
}
return 0;
}
/// commuteInstruction - We have a few instructions that must be hacked on to
/// commute them.
///
MachineInstr *X86InstrInfo::commuteInstruction(MachineInstr *MI) const {
switch (MI->getOpcode()) {
case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
case X86::SHLD32rri8:{// A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
unsigned Opc;
unsigned Size;
switch (MI->getOpcode()) {
default: assert(0 && "Unreachable!");
case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
}
unsigned Amt = MI->getOperand(3).getImmedValue();
unsigned A = MI->getOperand(0).getReg();
unsigned B = MI->getOperand(1).getReg();
unsigned C = MI->getOperand(2).getReg();
return BuildMI(Opc, 3, A).addReg(C).addReg(B).addImm(Size-Amt);
}
default:
return TargetInstrInfo::commuteInstruction(MI);
}
}
void X86InstrInfo::insertGoto(MachineBasicBlock& MBB,
MachineBasicBlock& TMBB) const {
BuildMI(MBB, MBB.end(), X86::JMP, 1).addMBB(&TMBB);
}
MachineBasicBlock::iterator
X86InstrInfo::reverseBranchCondition(MachineBasicBlock::iterator MI) const {
unsigned Opcode = MI->getOpcode();
assert(isBranch(Opcode) && "MachineInstr must be a branch");
unsigned ROpcode;
switch (Opcode) {
default: assert(0 && "Cannot reverse unconditional branches!");
case X86::JB: ROpcode = X86::JAE; break;
case X86::JAE: ROpcode = X86::JB; break;
case X86::JE: ROpcode = X86::JNE; break;
case X86::JNE: ROpcode = X86::JE; break;
case X86::JBE: ROpcode = X86::JA; break;
case X86::JA: ROpcode = X86::JBE; break;
case X86::JS: ROpcode = X86::JNS; break;
case X86::JNS: ROpcode = X86::JS; break;
case X86::JP: ROpcode = X86::JNP; break;
case X86::JNP: ROpcode = X86::JP; break;
case X86::JL: ROpcode = X86::JGE; break;
case X86::JGE: ROpcode = X86::JL; break;
case X86::JLE: ROpcode = X86::JG; break;
case X86::JG: ROpcode = X86::JLE; break;
}
MachineBasicBlock* MBB = MI->getParent();
MachineBasicBlock* TMBB = MI->getOperand(0).getMachineBasicBlock();
return BuildMI(*MBB, MBB->erase(MI), ROpcode, 1).addMBB(TMBB);
}
<commit_msg>These can be transformed into lea as well. Not that we use this feature currently...<commit_after>//===- X86InstrInfo.cpp - X86 Instruction Information -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the X86 implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//
#include "X86InstrInfo.h"
#include "X86.h"
#include "X86InstrBuilder.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "X86GenInstrInfo.inc"
using namespace llvm;
X86InstrInfo::X86InstrInfo()
: TargetInstrInfo(X86Insts, sizeof(X86Insts)/sizeof(X86Insts[0])) {
}
bool X86InstrInfo::isMoveInstr(const MachineInstr& MI,
unsigned& sourceReg,
unsigned& destReg) const {
MachineOpCode oc = MI.getOpcode();
if (oc == X86::MOV8rr || oc == X86::MOV16rr || oc == X86::MOV32rr ||
oc == X86::MOV16to16_ || oc == X86::MOV32to32_ ||
oc == X86::FpMOV || oc == X86::MOVSSrr || oc == X86::MOVSDrr ||
oc == X86::FsMOVAPSrr || oc == X86::FsMOVAPDrr ||
oc == X86::MOVAPSrr || oc == X86::MOVAPDrr ||
oc == X86::MOVSS2PSrr || oc == X86::MOVSD2PDrr ||
oc == X86::MOVPS2SSrr || oc == X86::MOVPD2SDrr ||
oc == X86::MOVDI2PDIrr || oc == X86::MOVQI2PQIrr ||
oc == X86::MOVPDI2DIrr) {
assert(MI.getNumOperands() == 2 &&
MI.getOperand(0).isRegister() &&
MI.getOperand(1).isRegister() &&
"invalid register-register move instruction");
sourceReg = MI.getOperand(1).getReg();
destReg = MI.getOperand(0).getReg();
return true;
}
return false;
}
unsigned X86InstrInfo::isLoadFromStackSlot(MachineInstr *MI,
int &FrameIndex) const {
switch (MI->getOpcode()) {
default: break;
case X86::MOV8rm:
case X86::MOV16rm:
case X86::MOV16_rm:
case X86::MOV32rm:
case X86::MOV32_rm:
case X86::FpLD64m:
case X86::MOVSSrm:
case X86::MOVSDrm:
case X86::MOVAPSrm:
case X86::MOVAPDrm:
if (MI->getOperand(1).isFrameIndex() && MI->getOperand(2).isImmediate() &&
MI->getOperand(3).isRegister() && MI->getOperand(4).isImmediate() &&
MI->getOperand(2).getImmedValue() == 1 &&
MI->getOperand(3).getReg() == 0 &&
MI->getOperand(4).getImmedValue() == 0) {
FrameIndex = MI->getOperand(1).getFrameIndex();
return MI->getOperand(0).getReg();
}
break;
}
return 0;
}
unsigned X86InstrInfo::isStoreToStackSlot(MachineInstr *MI,
int &FrameIndex) const {
switch (MI->getOpcode()) {
default: break;
case X86::MOV8mr:
case X86::MOV16mr:
case X86::MOV16_mr:
case X86::MOV32mr:
case X86::MOV32_mr:
case X86::FpSTP64m:
case X86::MOVSSmr:
case X86::MOVSDmr:
case X86::MOVAPSmr:
case X86::MOVAPDmr:
if (MI->getOperand(0).isFrameIndex() && MI->getOperand(1).isImmediate() &&
MI->getOperand(2).isRegister() && MI->getOperand(3).isImmediate() &&
MI->getOperand(1).getImmedValue() == 1 &&
MI->getOperand(2).getReg() == 0 &&
MI->getOperand(3).getImmedValue() == 0) {
FrameIndex = MI->getOperand(0).getFrameIndex();
return MI->getOperand(4).getReg();
}
break;
}
return 0;
}
/// convertToThreeAddress - This method must be implemented by targets that
/// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
/// may be able to convert a two-address instruction into a true
/// three-address instruction on demand. This allows the X86 target (for
/// example) to convert ADD and SHL instructions into LEA instructions if they
/// would require register copies due to two-addressness.
///
/// This method returns a null pointer if the transformation cannot be
/// performed, otherwise it returns the new instruction.
///
MachineInstr *X86InstrInfo::convertToThreeAddress(MachineInstr *MI) const {
// All instructions input are two-addr instructions. Get the known operands.
unsigned Dest = MI->getOperand(0).getReg();
unsigned Src = MI->getOperand(1).getReg();
// FIXME: None of these instructions are promotable to LEAs without
// additional information. In particular, LEA doesn't set the flags that
// add and inc do. :(
return 0;
// FIXME: 16-bit LEA's are really slow on Athlons, but not bad on P4's. When
// we have subtarget support, enable the 16-bit LEA generation here.
bool DisableLEA16 = true;
switch (MI->getOpcode()) {
case X86::INC32r:
assert(MI->getNumOperands() == 2 && "Unknown inc instruction!");
return addRegOffset(BuildMI(X86::LEA32r, 5, Dest), Src, 1);
case X86::INC16r:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 2 && "Unknown inc instruction!");
return addRegOffset(BuildMI(X86::LEA16r, 5, Dest), Src, 1);
case X86::DEC32r:
assert(MI->getNumOperands() == 2 && "Unknown dec instruction!");
return addRegOffset(BuildMI(X86::LEA32r, 5, Dest), Src, -1);
case X86::DEC16r:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 2 && "Unknown dec instruction!");
return addRegOffset(BuildMI(X86::LEA16r, 5, Dest), Src, -1);
case X86::ADD32rr:
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
return addRegReg(BuildMI(X86::LEA32r, 5, Dest), Src,
MI->getOperand(2).getReg());
case X86::ADD16rr:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
return addRegReg(BuildMI(X86::LEA16r, 5, Dest), Src,
MI->getOperand(2).getReg());
case X86::ADD32ri:
case X86::ADD32ri8:
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
if (MI->getOperand(2).isImmediate())
return addRegOffset(BuildMI(X86::LEA32r, 5, Dest), Src,
MI->getOperand(2).getImmedValue());
return 0;
case X86::ADD16ri:
case X86::ADD16ri8:
if (DisableLEA16) return 0;
assert(MI->getNumOperands() == 3 && "Unknown add instruction!");
if (MI->getOperand(2).isImmediate())
return addRegOffset(BuildMI(X86::LEA16r, 5, Dest), Src,
MI->getOperand(2).getImmedValue());
break;
case X86::SHL16ri:
if (DisableLEA16) return 0;
case X86::SHL32ri:
assert(MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate() &&
"Unknown shl instruction!");
unsigned ShAmt = MI->getOperand(2).getImmedValue();
if (ShAmt == 1 || ShAmt == 2 || ShAmt == 3) {
X86AddressMode AM;
AM.Scale = 1 << ShAmt;
AM.IndexReg = Src;
unsigned Opc = MI->getOpcode() == X86::SHL32ri ? X86::LEA32r :X86::LEA16r;
return addFullAddress(BuildMI(Opc, 5, Dest), AM);
}
break;
}
return 0;
}
/// commuteInstruction - We have a few instructions that must be hacked on to
/// commute them.
///
MachineInstr *X86InstrInfo::commuteInstruction(MachineInstr *MI) const {
switch (MI->getOpcode()) {
case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
case X86::SHLD32rri8:{// A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
unsigned Opc;
unsigned Size;
switch (MI->getOpcode()) {
default: assert(0 && "Unreachable!");
case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
}
unsigned Amt = MI->getOperand(3).getImmedValue();
unsigned A = MI->getOperand(0).getReg();
unsigned B = MI->getOperand(1).getReg();
unsigned C = MI->getOperand(2).getReg();
return BuildMI(Opc, 3, A).addReg(C).addReg(B).addImm(Size-Amt);
}
default:
return TargetInstrInfo::commuteInstruction(MI);
}
}
void X86InstrInfo::insertGoto(MachineBasicBlock& MBB,
MachineBasicBlock& TMBB) const {
BuildMI(MBB, MBB.end(), X86::JMP, 1).addMBB(&TMBB);
}
MachineBasicBlock::iterator
X86InstrInfo::reverseBranchCondition(MachineBasicBlock::iterator MI) const {
unsigned Opcode = MI->getOpcode();
assert(isBranch(Opcode) && "MachineInstr must be a branch");
unsigned ROpcode;
switch (Opcode) {
default: assert(0 && "Cannot reverse unconditional branches!");
case X86::JB: ROpcode = X86::JAE; break;
case X86::JAE: ROpcode = X86::JB; break;
case X86::JE: ROpcode = X86::JNE; break;
case X86::JNE: ROpcode = X86::JE; break;
case X86::JBE: ROpcode = X86::JA; break;
case X86::JA: ROpcode = X86::JBE; break;
case X86::JS: ROpcode = X86::JNS; break;
case X86::JNS: ROpcode = X86::JS; break;
case X86::JP: ROpcode = X86::JNP; break;
case X86::JNP: ROpcode = X86::JP; break;
case X86::JL: ROpcode = X86::JGE; break;
case X86::JGE: ROpcode = X86::JL; break;
case X86::JLE: ROpcode = X86::JG; break;
case X86::JG: ROpcode = X86::JLE; break;
}
MachineBasicBlock* MBB = MI->getParent();
MachineBasicBlock* TMBB = MI->getOperand(0).getMachineBasicBlock();
return BuildMI(*MBB, MBB->erase(MI), ROpcode, 1).addMBB(TMBB);
}
<|endoftext|> |
<commit_before>//===-- TCPSocket.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#endif
#include "lldb/Host/common/TCPSocket.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/MainLoop.h"
#include "lldb/Utility/Log.h"
#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"
#ifndef LLDB_DISABLE_POSIX
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#endif
#if defined(LLVM_ON_WIN32)
#include <winsock2.h>
#endif
#ifdef LLVM_ON_WIN32
#define CLOSE_SOCKET closesocket
typedef const char *set_socket_option_arg_type;
#else
#define CLOSE_SOCKET ::close
typedef const void *set_socket_option_arg_type;
#endif
using namespace lldb;
using namespace lldb_private;
namespace {
const int kType = SOCK_STREAM;
}
TCPSocket::TCPSocket(bool should_close, bool child_processes_inherit)
: Socket(ProtocolTcp, should_close, child_processes_inherit) {}
TCPSocket::TCPSocket(NativeSocket socket, const TCPSocket &listen_socket)
: Socket(ProtocolTcp, listen_socket.m_should_close_fd,
listen_socket.m_child_processes_inherit) {
m_socket = socket;
}
TCPSocket::TCPSocket(NativeSocket socket, bool should_close,
bool child_processes_inherit)
: Socket(ProtocolTcp, should_close, child_processes_inherit) {
m_socket = socket;
}
TCPSocket::~TCPSocket() { CloseListenSockets(); }
bool TCPSocket::IsValid() const {
return m_socket != kInvalidSocketValue || m_listen_sockets.size() != 0;
}
// Return the port number that is being used by the socket.
uint16_t TCPSocket::GetLocalPortNumber() const {
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetPort();
} else if (!m_listen_sockets.empty()) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getsockname(m_listen_sockets.begin()->first, sock_addr,
&sock_addr_len) == 0)
return sock_addr.GetPort();
}
return 0;
}
std::string TCPSocket::GetLocalIPAddress() const {
// We bound to port zero, so we need to figure out which port we actually
// bound to
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetIPAddress();
}
return "";
}
uint16_t TCPSocket::GetRemotePortNumber() const {
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetPort();
}
return 0;
}
std::string TCPSocket::GetRemoteIPAddress() const {
// We bound to port zero, so we need to figure out which port we actually
// bound to
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetIPAddress();
}
return "";
}
Error TCPSocket::CreateSocket(int domain) {
Error error;
if (IsValid())
error = Close();
if (error.Fail())
return error;
m_socket = Socket::CreateSocket(domain, kType, IPPROTO_TCP,
m_child_processes_inherit, error);
return error;
}
Error TCPSocket::Connect(llvm::StringRef name) {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
if (log)
log->Printf("TCPSocket::%s (host/port = %s)", __FUNCTION__, name.data());
Error error;
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
return error;
auto addresses = lldb_private::SocketAddress::GetAddressInfo(
host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
for (auto address : addresses) {
error = CreateSocket(address.GetFamily());
if (error.Fail())
continue;
address.SetPort(port);
if (-1 == ::connect(GetNativeSocket(), &address.sockaddr(),
address.GetLength())) {
CLOSE_SOCKET(GetNativeSocket());
continue;
}
SetOptionNoDelay();
error.Clear();
return error;
}
error.SetErrorString("Failed to connect port");
return error;
}
Error TCPSocket::Listen(llvm::StringRef name, int backlog) {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf("TCPSocket::%s (%s)", __FUNCTION__, name.data());
Error error;
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
return error;
auto addresses = lldb_private::SocketAddress::GetAddressInfo(
host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
for (auto address : addresses) {
int fd = Socket::CreateSocket(address.GetFamily(), kType, IPPROTO_TCP,
m_child_processes_inherit, error);
if (error.Fail()) {
error.Clear();
continue;
}
// enable local address reuse
int option_value = 1;
set_socket_option_arg_type option_value_p =
reinterpret_cast<set_socket_option_arg_type>(&option_value);
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, option_value_p,
sizeof(option_value));
address.SetPort(port);
int err = ::bind(fd, &address.sockaddr(), address.GetLength());
if (-1 != err)
err = ::listen(fd, backlog);
if (-1 == err) {
CLOSE_SOCKET(fd);
continue;
}
if (port == 0) {
socklen_t sa_len = address.GetLength();
if (getsockname(fd, &address.sockaddr(), &sa_len) == 0)
port = address.GetPort();
}
m_listen_sockets[fd] = address;
}
if (m_listen_sockets.size() == 0)
error.SetErrorString("Failed to connect port");
return error;
}
void TCPSocket::CloseListenSockets() {
for (auto socket : m_listen_sockets)
CLOSE_SOCKET(socket.first);
m_listen_sockets.clear();
}
Error TCPSocket::Accept(Socket *&conn_socket) {
Error error;
if (m_listen_sockets.size() == 0) {
error.SetErrorString("No open listening sockets!");
return error;
}
int sock = -1;
int listen_sock = -1;
lldb_private::SocketAddress AcceptAddr;
MainLoop accept_loop;
std::vector<MainLoopBase::ReadHandleUP> handles;
for (auto socket : m_listen_sockets) {
auto fd = socket.first;
auto inherit = this->m_child_processes_inherit;
auto io_sp = IOObjectSP(new TCPSocket(socket.first, false, inherit));
handles.emplace_back(accept_loop.RegisterReadObject(
io_sp, [fd, inherit, &sock, &AcceptAddr, &error,
&listen_sock](MainLoopBase &loop) {
socklen_t sa_len = AcceptAddr.GetMaxLength();
sock = AcceptSocket(fd, &AcceptAddr.sockaddr(), &sa_len, inherit,
error);
listen_sock = fd;
loop.RequestTermination();
}, error));
if (error.Fail())
return error;
}
bool accept_connection = false;
std::unique_ptr<TCPSocket> accepted_socket;
// Loop until we are happy with our connection
while (!accept_connection) {
accept_loop.Run();
if (error.Fail())
return error;
lldb_private::SocketAddress &AddrIn = m_listen_sockets[listen_sock];
if (!AddrIn.IsAnyAddr() && AcceptAddr != AddrIn) {
CLOSE_SOCKET(sock);
llvm::errs() << llvm::formatv(
"error: rejecting incoming connection from {0} (expecting {1})",
AcceptAddr.GetIPAddress(), AddrIn.GetIPAddress());
continue;
}
accept_connection = true;
accepted_socket.reset(new TCPSocket(sock, *this));
}
if (!accepted_socket)
return error;
// Keep our TCP packets coming without any delays.
accepted_socket->SetOptionNoDelay();
error.Clear();
conn_socket = accepted_socket.release();
return error;
}
int TCPSocket::SetOptionNoDelay() {
return SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
}
int TCPSocket::SetOptionReuseAddress() {
return SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
}
<commit_msg>TCPSocket: add back support for "*" address<commit_after>//===-- TCPSocket.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#endif
#include "lldb/Host/common/TCPSocket.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/MainLoop.h"
#include "lldb/Utility/Log.h"
#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"
#ifndef LLDB_DISABLE_POSIX
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#endif
#if defined(LLVM_ON_WIN32)
#include <winsock2.h>
#endif
#ifdef LLVM_ON_WIN32
#define CLOSE_SOCKET closesocket
typedef const char *set_socket_option_arg_type;
#else
#define CLOSE_SOCKET ::close
typedef const void *set_socket_option_arg_type;
#endif
using namespace lldb;
using namespace lldb_private;
namespace {
const int kType = SOCK_STREAM;
}
TCPSocket::TCPSocket(bool should_close, bool child_processes_inherit)
: Socket(ProtocolTcp, should_close, child_processes_inherit) {}
TCPSocket::TCPSocket(NativeSocket socket, const TCPSocket &listen_socket)
: Socket(ProtocolTcp, listen_socket.m_should_close_fd,
listen_socket.m_child_processes_inherit) {
m_socket = socket;
}
TCPSocket::TCPSocket(NativeSocket socket, bool should_close,
bool child_processes_inherit)
: Socket(ProtocolTcp, should_close, child_processes_inherit) {
m_socket = socket;
}
TCPSocket::~TCPSocket() { CloseListenSockets(); }
bool TCPSocket::IsValid() const {
return m_socket != kInvalidSocketValue || m_listen_sockets.size() != 0;
}
// Return the port number that is being used by the socket.
uint16_t TCPSocket::GetLocalPortNumber() const {
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetPort();
} else if (!m_listen_sockets.empty()) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getsockname(m_listen_sockets.begin()->first, sock_addr,
&sock_addr_len) == 0)
return sock_addr.GetPort();
}
return 0;
}
std::string TCPSocket::GetLocalIPAddress() const {
// We bound to port zero, so we need to figure out which port we actually
// bound to
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getsockname(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetIPAddress();
}
return "";
}
uint16_t TCPSocket::GetRemotePortNumber() const {
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetPort();
}
return 0;
}
std::string TCPSocket::GetRemoteIPAddress() const {
// We bound to port zero, so we need to figure out which port we actually
// bound to
if (m_socket != kInvalidSocketValue) {
SocketAddress sock_addr;
socklen_t sock_addr_len = sock_addr.GetMaxLength();
if (::getpeername(m_socket, sock_addr, &sock_addr_len) == 0)
return sock_addr.GetIPAddress();
}
return "";
}
Error TCPSocket::CreateSocket(int domain) {
Error error;
if (IsValid())
error = Close();
if (error.Fail())
return error;
m_socket = Socket::CreateSocket(domain, kType, IPPROTO_TCP,
m_child_processes_inherit, error);
return error;
}
Error TCPSocket::Connect(llvm::StringRef name) {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION));
if (log)
log->Printf("TCPSocket::%s (host/port = %s)", __FUNCTION__, name.data());
Error error;
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
return error;
auto addresses = lldb_private::SocketAddress::GetAddressInfo(
host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
for (auto address : addresses) {
error = CreateSocket(address.GetFamily());
if (error.Fail())
continue;
address.SetPort(port);
if (-1 == ::connect(GetNativeSocket(), &address.sockaddr(),
address.GetLength())) {
CLOSE_SOCKET(GetNativeSocket());
continue;
}
SetOptionNoDelay();
error.Clear();
return error;
}
error.SetErrorString("Failed to connect port");
return error;
}
Error TCPSocket::Listen(llvm::StringRef name, int backlog) {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
if (log)
log->Printf("TCPSocket::%s (%s)", __FUNCTION__, name.data());
Error error;
std::string host_str;
std::string port_str;
int32_t port = INT32_MIN;
if (!DecodeHostAndPort(name, host_str, port_str, port, &error))
return error;
if (host_str == "*")
host_str = "0.0.0.0";
auto addresses = lldb_private::SocketAddress::GetAddressInfo(
host_str.c_str(), NULL, AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
for (auto address : addresses) {
int fd = Socket::CreateSocket(address.GetFamily(), kType, IPPROTO_TCP,
m_child_processes_inherit, error);
if (error.Fail()) {
error.Clear();
continue;
}
// enable local address reuse
int option_value = 1;
set_socket_option_arg_type option_value_p =
reinterpret_cast<set_socket_option_arg_type>(&option_value);
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, option_value_p,
sizeof(option_value));
address.SetPort(port);
int err = ::bind(fd, &address.sockaddr(), address.GetLength());
if (-1 != err)
err = ::listen(fd, backlog);
if (-1 == err) {
CLOSE_SOCKET(fd);
continue;
}
if (port == 0) {
socklen_t sa_len = address.GetLength();
if (getsockname(fd, &address.sockaddr(), &sa_len) == 0)
port = address.GetPort();
}
m_listen_sockets[fd] = address;
}
if (m_listen_sockets.size() == 0)
error.SetErrorString("Failed to connect port");
return error;
}
void TCPSocket::CloseListenSockets() {
for (auto socket : m_listen_sockets)
CLOSE_SOCKET(socket.first);
m_listen_sockets.clear();
}
Error TCPSocket::Accept(Socket *&conn_socket) {
Error error;
if (m_listen_sockets.size() == 0) {
error.SetErrorString("No open listening sockets!");
return error;
}
int sock = -1;
int listen_sock = -1;
lldb_private::SocketAddress AcceptAddr;
MainLoop accept_loop;
std::vector<MainLoopBase::ReadHandleUP> handles;
for (auto socket : m_listen_sockets) {
auto fd = socket.first;
auto inherit = this->m_child_processes_inherit;
auto io_sp = IOObjectSP(new TCPSocket(socket.first, false, inherit));
handles.emplace_back(accept_loop.RegisterReadObject(
io_sp, [fd, inherit, &sock, &AcceptAddr, &error,
&listen_sock](MainLoopBase &loop) {
socklen_t sa_len = AcceptAddr.GetMaxLength();
sock = AcceptSocket(fd, &AcceptAddr.sockaddr(), &sa_len, inherit,
error);
listen_sock = fd;
loop.RequestTermination();
}, error));
if (error.Fail())
return error;
}
bool accept_connection = false;
std::unique_ptr<TCPSocket> accepted_socket;
// Loop until we are happy with our connection
while (!accept_connection) {
accept_loop.Run();
if (error.Fail())
return error;
lldb_private::SocketAddress &AddrIn = m_listen_sockets[listen_sock];
if (!AddrIn.IsAnyAddr() && AcceptAddr != AddrIn) {
CLOSE_SOCKET(sock);
llvm::errs() << llvm::formatv(
"error: rejecting incoming connection from {0} (expecting {1})",
AcceptAddr.GetIPAddress(), AddrIn.GetIPAddress());
continue;
}
accept_connection = true;
accepted_socket.reset(new TCPSocket(sock, *this));
}
if (!accepted_socket)
return error;
// Keep our TCP packets coming without any delays.
accepted_socket->SetOptionNoDelay();
error.Clear();
conn_socket = accepted_socket.release();
return error;
}
int TCPSocket::SetOptionNoDelay() {
return SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
}
int TCPSocket::SetOptionReuseAddress() {
return SetOption(SOL_SOCKET, SO_REUSEADDR, 1);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, 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 "test.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
#include "setup_transfer.hpp" // for load_file
#include "libtorrent/file.hpp" // for combine_path
#include <vector>
using namespace libtorrent;
int test_main()
{
std::vector<char> utf8_source;
error_code ec;
load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000);
if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value()
, ec.message().c_str());
TEST_CHECK(!ec);
// test lower level conversions
// utf8 -> utf16 -> utf32 -> utf8
{
std::vector<UTF16> utf16(utf8_source.size());
UTF8 const* in8 = (UTF8 const*)&utf8_source[0];
UTF16* out16 = &utf16[0];
ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source.size()
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF32> utf32(utf8_source.size());
UTF16 const* in16 = &utf16[0];
UTF32* out32 = &utf32[0];
ret = ConvertUTF16toUTF32(&in16, out16
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF8> utf8(utf8_source.size());
UTF32 const* in32 = &utf32[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF32toUTF8(&in32, out32
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
TEST_EQUAL(out8 - &utf8[0], utf8_source.size());
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));
}
// utf8 -> utf32 -> utf16 -> utf8
{
std::vector<UTF32> utf32(utf8_source.size());
UTF8 const* in8 = (UTF8 const*)&utf8_source[0];
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source.size()
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF16> utf16(utf8_source.size());
UTF32 const* in32 = &utf32[0];
UTF16* out16 = &utf16[0];
ret = ConvertUTF32toUTF16(&in32, out32
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
std::vector<UTF8> utf8(utf8_source.size());
UTF16 const* in16 = &utf16[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF16toUTF8(&in16, out16
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
TEST_EQUAL(out8 - &utf8[0], utf8_source.size());
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));
}
// test higher level conversions
std::string utf8;
std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));
std::wstring wide;
utf8_conv_result_t ret = utf8_wchar(utf8, wide);
TEST_EQUAL(ret, conversion_ok);
std::string identity;
ret = wchar_utf8(wide, identity);
TEST_EQUAL(ret, conversion_ok);
TEST_EQUAL(utf8, identity);
return 0;
}
<commit_msg>extend utf8 unit test<commit_after>/*
Copyright (c) 2014, 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 "test.hpp"
#include "libtorrent/utf8.hpp"
#include "libtorrent/ConvertUTF.h"
#include "setup_transfer.hpp" // for load_file
#include "libtorrent/file.hpp" // for combine_path
#include <vector>
using namespace libtorrent;
void verify_transforms(char const* utf8_source, int utf8_source_len = -1)
{
if (utf8_source_len == -1)
utf8_source_len = strlen(utf8_source);
// utf8 -> utf16 -> utf32 -> utf8
{
std::vector<UTF16> utf16(utf8_source_len);
UTF8 const* in8 = (UTF8 const*)utf8_source;
UTF16* out16 = &utf16[0];
ConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source_len
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF32> utf32(utf8_source_len);
UTF16 const* in16 = &utf16[0];
UTF32* out32 = &utf32[0];
ret = ConvertUTF16toUTF32(&in16, out16
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF8> utf8(utf8_source_len);
UTF32 const* in32 = &utf32[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF32toUTF8(&in32, out32
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
TEST_EQUAL(out8 - &utf8[0], utf8_source_len);
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));
}
// utf8 -> utf32 -> utf16 -> utf8
{
std::vector<UTF32> utf32(utf8_source_len);
UTF8 const* in8 = (UTF8 const*)utf8_source;
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source_len
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF16> utf16(utf8_source_len);
UTF32 const* in32 = &utf32[0];
UTF16* out16 = &utf16[0];
ret = ConvertUTF32toUTF16(&in32, out32
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
std::vector<UTF8> utf8(utf8_source_len);
UTF16 const* in16 = &utf16[0];
UTF8* out8 = &utf8[0];
ret = ConvertUTF16toUTF8(&in16, out16
, &out8, out8 + utf8.size(), strictConversion);
TEST_EQUAL(ret, conversionOK);
if (ret != conversionOK && utf8_source_len < 10)
{
for (char const* i = utf8_source; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
TEST_EQUAL(out8 - &utf8[0], utf8_source_len);
TEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));
}
}
void expect_error(char const* utf8, ConversionResult expect)
{
UTF8 const* in8 = (UTF8 const*)utf8;
std::vector<UTF32> utf32(strlen(utf8));
UTF32* out32 = &utf32[0];
ConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + strlen(utf8)
, &out32, out32 + utf32.size(), strictConversion);
TEST_EQUAL(ret, expect);
if (ret != expect)
{
fprintf(stderr, "%d expected %d\n", ret, expect);
for (char const* i = utf8; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
in8 = (UTF8 const*)utf8;
std::vector<UTF16> utf16(strlen(utf8));
UTF16* out16 = &utf16[0];
ret = ConvertUTF8toUTF16(&in8, in8 + strlen(utf8)
, &out16, out16 + utf16.size(), strictConversion);
TEST_EQUAL(ret, expect);
if (ret != expect)
{
fprintf(stderr, "%d expected %d\n", ret, expect);
for (char const* i = utf8; *i != 0; ++i)
fprintf(stderr, "%x ", UTF8(*i));
}
}
int test_main()
{
std::vector<char> utf8_source;
error_code ec;
load_file(combine_path("..", "utf8_test.txt"), utf8_source, ec, 1000000);
if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value()
, ec.message().c_str());
TEST_CHECK(!ec);
// test lower level conversions
verify_transforms(&utf8_source[0], utf8_source.size());
verify_transforms("\xc3\xb0");
verify_transforms("\xed\x9f\xbf");
verify_transforms("\xee\x80\x80");
verify_transforms("\xef\xbf\xbd");
verify_transforms("\xf4\x8f\xbf\xbf");
verify_transforms("\xf0\x91\x80\x80\x30");
// Unexpected continuation bytes
expect_error("\x80", sourceIllegal);
expect_error("\xbf", sourceIllegal);
// Impossible bytes
// The following two bytes cannot appear in a correct UTF-8 string
expect_error("\xff", sourceExhausted);
expect_error("\xfe", sourceExhausted);
expect_error("\xff\xff\xfe\xfe", sourceExhausted);
// Examples of an overlong ASCII character
expect_error("\xc0\xaf", sourceIllegal);
expect_error("\xe0\x80\xaf", sourceIllegal);
expect_error("\xf0\x80\x80\xaf", sourceIllegal);
expect_error("\xf8\x80\x80\x80\xaf ", sourceIllegal);
expect_error("\xfc\x80\x80\x80\x80\xaf", sourceIllegal);
// Maximum overlong sequences
expect_error("\xc1\xbf", sourceIllegal);
expect_error("\xe0\x9f\xbf", sourceIllegal);
expect_error("\xf0\x8f\xbf\xbf", sourceIllegal);
expect_error("\xf8\x87\xbf\xbf\xbf", sourceIllegal);
expect_error("\xfc\x83\xbf\xbf\xbf\xbf", sourceIllegal);
// Overlong representation of the NUL character
expect_error("\xc0\x80", sourceIllegal);
expect_error("\xe0\x80\x80", sourceIllegal);
expect_error("\xf0\x80\x80\x80", sourceIllegal);
expect_error("\xf8\x80\x80\x80\x80", sourceIllegal);
expect_error("\xfc\x80\x80\x80\x80\x80", sourceIllegal);
// Single UTF-16 surrogates
expect_error("\xed\xa0\x80", sourceIllegal);
expect_error("\xed\xad\xbf", sourceIllegal);
expect_error("\xed\xae\x80", sourceIllegal);
expect_error("\xed\xaf\xbf", sourceIllegal);
expect_error("\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xbe\x80", sourceIllegal);
expect_error("\xed\xbf\xbf", sourceIllegal);
// Paired UTF-16 surrogates
expect_error("\xed\xa0\x80\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xa0\x80\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xad\xbf\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xad\xbf\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xae\x80\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xae\x80\xed\xbf\xbf", sourceIllegal);
expect_error("\xed\xaf\xbf\xed\xb0\x80", sourceIllegal);
expect_error("\xed\xaf\xbf\xed\xbf\xbf", sourceIllegal);
// test higher level conversions
std::string utf8;
std::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));
std::wstring wide;
utf8_conv_result_t ret = utf8_wchar(utf8, wide);
TEST_EQUAL(ret, conversion_ok);
std::string identity;
ret = wchar_utf8(wide, identity);
TEST_EQUAL(ret, conversion_ok);
TEST_EQUAL(utf8, identity);
return 0;
}
<|endoftext|> |
<commit_before>
/*
* BSD 3-Clause License
*
* Copyright (c) 2018, mtezych
* 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 holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cl/Platform.h>
#include <cl/Context.h>
#include <cl/CommandQueue.h>
#include <cl/Program.h>
#include <cl/Kernel.h>
#include <cl/Memory.h>
// +------+
// | Host |
// +------+
// |
// +-----------------+-------------------+
// | |
// +----------------|--------------+ +----------------|--------------+
// | OpenCL Device | | OpenCL Device |
// | +------------------------+ | | +------------------------+ |
// | | Compute Unit | | | | Compute Unit | |
// | +------------------------+ | | | +------------------------+ | |
// | | Compute Unit | | | | | Compute Unit | | |
// | | +--------------------+ | | | ... | | +--------------------+ | | |
// | | | Processing Element | | | | | | | Processing Element | | | |
// | | +--------------------+ | | | | | +--------------------+ | | |
// | | +--------------------+ | | | | | +--------------------+ | | |
// | | | Processing Element | | | | | | | Processing Element | | | |
// | | +--------------------+ | | | | | +--------------------+ | | |
// | | ... | | | | | ... | | |
// | | +--------------------+ | | | | | +--------------------+ | | |
// | | | Processing Element | |--+ | | | | Processing Element | |--+ |
// | | +--------------------+ | | | | +--------------------+ | |
// | +------------------------+ | | +------------------------+ |
// +-------------------------------+ +-------------------------------+
// +---------------+ +---------------+ +---------------+
// | Work Group | | Work Group | | Work Group |
// | +-----------+ | | +-----------+ | | +-----------+ |
// | | Work Item | | | | Work Item | | | | Work Item | |
// | +-----------+ | | +-----------+ | | +-----------+ |
// | +-----------+ | | +-----------+ | | +-----------+ |
// | | Work Item | | | | Work Item | | ... | | Work Item | |
// | +-----------+ | | +-----------+ | | +-----------+ |
// | ... | | ... | | ... |
// | +-----------+ | | +-----------+ | | +-----------+ |
// | | Work Item | | | | Work Item | | | | Work Item | |
// | +-----------+ | | +-----------+ | | +-----------+ |
// +---------------+ +---------------+ +---------------+
// Dispatch
// - gl_NumWorkGroups
// - gl_WorkGroupSize
// Work Group
// - gl_WorkGroupID
// Work Item
// - gl_LocalInvocationID
// - gl_GlobalInvocationID = gl_WorkGroupID * gl_WorkGroupSize + gl_LocalInvocationID
int main ()
{
const auto platforms = cl::GetPlatforms();
for (const auto& platform : platforms)
{
const auto platformProfile = platform.GetInfo<CL_PLATFORM_PROFILE >();
const auto platformVersion = platform.GetInfo<CL_PLATFORM_VERSION >();
const auto platformVendor = platform.GetInfo<CL_PLATFORM_VENDOR >();
const auto platformName = platform.GetInfo<CL_PLATFORM_NAME >();
const auto platformExtensions = platform.GetInfo<CL_PLATFORM_EXTENSIONS>();
const auto devices = platform.GetDevices();
for (const auto& device : devices)
{
const auto deviceType = device.GetInfo<CL_DEVICE_TYPE >();
const auto deviceProfile = device.GetInfo<CL_DEVICE_PROFILE >();
const auto deviceVersion = device.GetInfo<CL_DEVICE_VERSION >();
const auto deviceVendor = device.GetInfo<CL_DEVICE_VENDOR >();
const auto deviceName = device.GetInfo<CL_DEVICE_NAME >();
const auto deviceExtensions = device.GetInfo<CL_DEVICE_EXTENSIONS>();
const auto deviceVendorID = device.GetInfo<CL_DEVICE_VENDOR_ID >();
const auto driverVersion = device.GetInfo<CL_DRIVER_VERSION >();
}
const auto context = cl::Context { platform, devices };
const auto contextNumDevices = context.GetInfo<CL_CONTEXT_NUM_DEVICES >();
const auto contextReferenceCount = context.GetInfo<CL_CONTEXT_REFERENCE_COUNT>();
for (const auto& device : devices)
{
const auto commandQueue = cl::CommandQueue { context, device };
}
auto program = cl::Program
{
context,
"__kernel void cl_main \n"
"( \n"
" __global const float* firstInput, \n"
" __global const float* secondInput, \n"
" __global float* output \n"
") \n"
"{ \n"
" int globalID = get_global_id(0); \n"
" \n"
" output[globalID] = firstInput[globalID] + secondInput[globalID]; \n"
"} \n"
};
program.Build();
auto kernel = cl::Kernel { program, "cl_main" };
const auto firstSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
1.5f, 7.6f, 8.1f, 1.5f, 1.7f, 2.4f, 9.0f, 3.5f,
},
};
const auto secondSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
3.6f, 7.0f, 0.8f, 4.3f, 2.7f, 6.5f, 2.8f, 1.4f,
},
};
const auto dstMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::WriteOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
8
};
kernel.SetArg(0, firstSrcMemory);
kernel.SetArg(1, secondSrcMemory);
kernel.SetArg(2, dstMemory);
}
return 0;
}
<commit_msg>CL -> Refined descriptions of Platform, Memory and Execution Models.<commit_after>
/*
* BSD 3-Clause License
*
* Copyright (c) 2018, mtezych
* 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 holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cl/Platform.h>
#include <cl/Context.h>
#include <cl/CommandQueue.h>
#include <cl/Program.h>
#include <cl/Kernel.h>
#include <cl/Memory.h>
//
// [ Platform & Memory Models ]
//
// ┌─────────────────────────────────────────────────────────────────────┐
// │ Host Memory │
// └──────────────────────────────────┰──────────────────────────────────┘
// ┌──────────────────────────────────┸──────────────────────────────────┐
// │ Host │
// └──────────────────────────────────┰──────────────────────────────────┘
// ┏━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━┓
// ┌────────────────┸──────────────┐ ┌────────────────┸──────────────┐
// │ OpenCL Device │ │ OpenCL Device │
// │ ┌────────────────────────┐ │ │ ┌────────────────────────┐ │
// │ │ Compute Unit │ │ │ │ Compute Unit │ │
// │ ┌──┴─────────────────────┐ │ │ │ ┌──┴─────────────────────┐ │ │
// │ │ Compute Unit │ │ │ │ │ Compute Unit │ │ │
// │ │ ┌────────────────────┐ │ │ │ │ │ ┌────────────────────┐ │ │ │
// │ │ │ Processing Element │ │ │ │ │ │ │ Processing Element │ │ │ │
// │ │ └──────────┰─────────┘ │ │ │ │ │ └──────────┰─────────┘ │ │ │
// │ │ ┌──────────┸─────────┐ │ │ │ │ │ ┌──────────┸─────────┐ │ │ │
// │ │ │ Private Memory │ │ │ │ │ │ │ Private Memory │ │ │ │
// │ │ └────────────────────┘ │ │ │ ... │ │ └────────────────────┘ │ │ │
// │ │ ... │ │ │ │ │ ... │ │ │
// │ │ ┌────────────────────┐ │ │ │ │ │ ┌────────────────────┐ │ │ │
// │ │ │ Processing Element │ │ │ │ │ │ │ Processing Element │ │ │ │
// │ │ └──────────┰─────────┘ │ │ │ │ │ └──────────┰─────────┘ │ │ │
// │ │ ┌──────────┸─────────┐ │ │ │ │ │ ┌──────────┸─────────┐ │ │ │
// │ │ │ Private Memory │ ├──┘ │ │ │ │ Private Memory │ ├──┘ │
// │ │ └────────────────────┘ ├──┐ │ │ │ └────────────────────┘ ├──┐ │
// │ └────────────┰───────────┘ │ │ │ └────────────┰───────────┘ │ │
// │ ┌────────────┸───────────┐──┘ │ │ ┌────────────┸───────────┐──┘ │
// │ │ Local Memory │ │ │ │ Local Memory │ │
// │ └────────────────────────┘ │ │ └────────────────────────┘ │
// └──────────────┰────────────────┘ └──────────────┰────────────────┘
// ┌──────────────┸────────────────┐ ┌──────────────┸────────────────┐
// │ Global / Constant Memory │ │ Global / Constant Memory │
// └───────────────────────────────┘ └───────────────────────────────┘
//
// [ Execution Model ]
//
// ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
// │ Work Group │ │ Work Group │ │ Work Group │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ ... │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// │ ... │ │ ... │ │ ... │
// │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │
// │ │ Work Item │ │ │ │ Work Item │ │ │ │ Work Item │ │
// │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
// └───────────────┘ └───────────────┘ └───────────────┘
// ┌───────────────────┬───────────────────────┐
// │ OpenCL C │ GLSL │
// ┌────────────┼───────────────────┼───────────────────────┤
// │ │ get_work_dim() │ │
// │ NDRange │ get_num_groups() │ gl_NumWorkGroups │
// │ │ get_local_size() │ gl_WorkGroupSize │
// │ │ get_global_size() │ │
// ├────────────┼───────────────────┼───────────────────────┤
// │ Work Group │ get_group_id() │ gl_WorkGroupID │
// ├────────────┼───────────────────┼───────────────────────┤
// │ │ get_local_id() │ gl_LocalInvocationID │
// │ Work Item │ get_global_id() │ gl_GlobalInvocationID │
// └────────────┴───────────────────┴───────────────────────┘
//
// get_global_size() = get_num_groups() * get_local_size()
//
// get_global_id() = get_group_id() * get_local_size() + get_local_id()
// gl_GlobalInvocationID = gl_WorkGroupID * gl_WorkGroupSize + gl_LocalInvocationID
//
int main ()
{
const auto platforms = cl::GetPlatforms();
for (const auto& platform : platforms)
{
const auto platformProfile = platform.GetInfo<CL_PLATFORM_PROFILE >();
const auto platformVersion = platform.GetInfo<CL_PLATFORM_VERSION >();
const auto platformVendor = platform.GetInfo<CL_PLATFORM_VENDOR >();
const auto platformName = platform.GetInfo<CL_PLATFORM_NAME >();
const auto platformExtensions = platform.GetInfo<CL_PLATFORM_EXTENSIONS>();
const auto devices = platform.GetDevices();
for (const auto& device : devices)
{
const auto deviceType = device.GetInfo<CL_DEVICE_TYPE >();
const auto deviceProfile = device.GetInfo<CL_DEVICE_PROFILE >();
const auto deviceVersion = device.GetInfo<CL_DEVICE_VERSION >();
const auto deviceVendor = device.GetInfo<CL_DEVICE_VENDOR >();
const auto deviceName = device.GetInfo<CL_DEVICE_NAME >();
const auto deviceExtensions = device.GetInfo<CL_DEVICE_EXTENSIONS>();
const auto deviceVendorID = device.GetInfo<CL_DEVICE_VENDOR_ID >();
const auto driverVersion = device.GetInfo<CL_DRIVER_VERSION >();
}
const auto context = cl::Context { platform, devices };
const auto contextNumDevices = context.GetInfo<CL_CONTEXT_NUM_DEVICES >();
const auto contextReferenceCount = context.GetInfo<CL_CONTEXT_REFERENCE_COUNT>();
for (const auto& device : devices)
{
const auto commandQueue = cl::CommandQueue { context, device };
}
auto program = cl::Program
{
context,
"__kernel void cl_main \n"
"( \n"
" __global const float* firstInput, \n"
" __global const float* secondInput, \n"
" __global float* output \n"
") \n"
"{ \n"
" int globalID = get_global_id(0); \n"
" \n"
" output[globalID] = firstInput[globalID] + secondInput[globalID]; \n"
"} \n"
};
program.Build();
auto kernel = cl::Kernel { program, "cl_main" };
const auto firstSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
1.5f, 7.6f, 8.1f, 1.5f, 1.7f, 2.4f, 9.0f, 3.5f,
},
};
const auto secondSrcMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::ReadOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
std::vector<float>
{
3.6f, 7.0f, 0.8f, 4.3f, 2.7f, 6.5f, 2.8f, 1.4f,
},
};
const auto dstMemory = cl::Memory
{
context,
cl::Memory::DeviceAccess::WriteOnly,
cl::Memory::HostAccess::ReadWrite,
cl::Memory::Alloc::Device,
8
};
kernel.SetArg(0, firstSrcMemory);
kernel.SetArg(1, secondSrcMemory);
kernel.SetArg(2, dstMemory);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "selfdrive/ui/qt/widgets/drive_stats.h"
#include <QDebug>
#include <QGridLayout>
#include <QJsonObject>
#include <QVBoxLayout>
#include "selfdrive/common/params.h"
#include "selfdrive/ui/qt/request_repeater.h"
const double MILE_TO_KM = 1.60934;
namespace {
QLabel* numberLabel() {
QLabel* label = new QLabel("0");
label->setStyleSheet("font-size: 80px; font-weight: 600;");
return label;
}
QLabel* unitLabel(const QString& name) {
QLabel* label = new QLabel(name);
label->setStyleSheet("font-size: 45px; font-weight: 500;");
return label;
}
} // namespace
DriveStats::DriveStats(QWidget* parent) : QWidget(parent) {
metric_ = Params().getBool("IsMetric");
QGridLayout* main_layout = new QGridLayout(this);
main_layout->setMargin(0);
auto add_stats_layouts = [=](const QString &title, StatsLabels& labels) {
int row = main_layout->rowCount();
main_layout->addWidget(new QLabel(title), row++, 0, 1, 3);
main_layout->addWidget(labels.routes = numberLabel(), row, 0, Qt::AlignLeft);
main_layout->addWidget(labels.distance = numberLabel(), row, 1, Qt::AlignLeft);
main_layout->addWidget(labels.hours = numberLabel(), row, 2, Qt::AlignLeft);
main_layout->addWidget(unitLabel("DRIVES"), row + 1, 0, Qt::AlignLeft);
main_layout->addWidget(labels.distance_unit = unitLabel(getDistanceUnit()), row + 1, 1, Qt::AlignLeft);
main_layout->addWidget(unitLabel("HOURS"), row + 1, 2, Qt::AlignLeft);
};
add_stats_layouts("ALL TIME", all_);
add_stats_layouts("PAST WEEK", week_);
std::string dongle_id = Params().get("DongleId");
if (util::is_valid_dongle_id(dongle_id)) {
std::string url = "https://api.commadotai.com/v1.1/devices/" + dongle_id + "/stats";
RequestRepeater* repeater = new RequestRepeater(this, QString::fromStdString(url), "ApiCache_DriveStats", 30);
QObject::connect(repeater, &RequestRepeater::receivedResponse, this, &DriveStats::parseResponse);
}
setStyleSheet(R"(QLabel {font-size: 48px; font-weight: 500;})");
}
void DriveStats::updateStats() {
auto update = [=](const QJsonObject& obj, StatsLabels& labels) {
labels.routes->setText(QString::number((int)obj["routes"].toDouble()));
labels.distance->setText(QString::number(int(obj["distance"].toDouble() * (metric_ ? MILE_TO_KM : 1))));
labels.distance_unit->setText(getDistanceUnit());
labels.hours->setText(QString::number((int)(obj["minutes"].toDouble() / 60)));
};
QJsonObject json = stats_.object();
update(json["all"].toObject(), all_);
update(json["week"].toObject(), week_);
}
void DriveStats::parseResponse(const QString& response) {
QJsonDocument doc = QJsonDocument::fromJson(response.trimmed().toUtf8());
if (doc.isNull()) {
qDebug() << "JSON Parse failed on getting past drives statistics";
return;
}
stats_ = doc;
updateStats();
}
void DriveStats::showEvent(QShowEvent* event) {
bool metric = Params().getBool("IsMetric");
if (metric_ != metric) {
metric_ = metric;
updateStats();
}
}
<commit_msg>DriveStats: using dynamic properties to style QLabel (#21644)<commit_after>#include "selfdrive/ui/qt/widgets/drive_stats.h"
#include <QDebug>
#include <QGridLayout>
#include <QJsonObject>
#include <QVBoxLayout>
#include "selfdrive/common/params.h"
#include "selfdrive/ui/qt/request_repeater.h"
const double MILE_TO_KM = 1.60934;
static QLabel* newLabel(const QString& text, const QString &type) {
QLabel* label = new QLabel(text);
label->setProperty("type", type);
return label;
}
DriveStats::DriveStats(QWidget* parent) : QWidget(parent) {
metric_ = Params().getBool("IsMetric");
QGridLayout* main_layout = new QGridLayout(this);
main_layout->setMargin(0);
auto add_stats_layouts = [=](const QString &title, StatsLabels& labels) {
int row = main_layout->rowCount();
main_layout->addWidget(newLabel(title, "title"), row++, 0, 1, 3);
main_layout->addWidget(labels.routes = newLabel("0", "number"), row, 0, Qt::AlignLeft);
main_layout->addWidget(labels.distance = newLabel("0", "number"), row, 1, Qt::AlignLeft);
main_layout->addWidget(labels.hours = newLabel("0", "number"), row, 2, Qt::AlignLeft);
main_layout->addWidget(newLabel("DRIVES", "unit"), row + 1, 0, Qt::AlignLeft);
main_layout->addWidget(labels.distance_unit = newLabel(getDistanceUnit(), "unit"), row + 1, 1, Qt::AlignLeft);
main_layout->addWidget(newLabel("HOURS", "unit"), row + 1, 2, Qt::AlignLeft);
};
add_stats_layouts("ALL TIME", all_);
add_stats_layouts("PAST WEEK", week_);
std::string dongle_id = Params().get("DongleId");
if (util::is_valid_dongle_id(dongle_id)) {
std::string url = "https://api.commadotai.com/v1.1/devices/" + dongle_id + "/stats";
RequestRepeater* repeater = new RequestRepeater(this, QString::fromStdString(url), "ApiCache_DriveStats", 30);
QObject::connect(repeater, &RequestRepeater::receivedResponse, this, &DriveStats::parseResponse);
}
setStyleSheet(R"(
QLabel[type="title"] { font-size: 48px; font-weight: 500; }
QLabel[type="number"] { font-size: 80px; font-weight: 600; }
QLabel[type="unit"] { font-size: 45px; font-weight: 500; }
)");
}
void DriveStats::updateStats() {
auto update = [=](const QJsonObject& obj, StatsLabels& labels) {
labels.routes->setText(QString::number((int)obj["routes"].toDouble()));
labels.distance->setText(QString::number(int(obj["distance"].toDouble() * (metric_ ? MILE_TO_KM : 1))));
labels.distance_unit->setText(getDistanceUnit());
labels.hours->setText(QString::number((int)(obj["minutes"].toDouble() / 60)));
};
QJsonObject json = stats_.object();
update(json["all"].toObject(), all_);
update(json["week"].toObject(), week_);
}
void DriveStats::parseResponse(const QString& response) {
QJsonDocument doc = QJsonDocument::fromJson(response.trimmed().toUtf8());
if (doc.isNull()) {
qDebug() << "JSON Parse failed on getting past drives statistics";
return;
}
stats_ = doc;
updateStats();
}
void DriveStats::showEvent(QShowEvent* event) {
bool metric = Params().getBool("IsMetric");
if (metric_ != metric) {
metric_ = metric;
updateStats();
}
}
<|endoftext|> |
<commit_before><commit_msg>WaE: format string is not a string literal (potentially insecure)<commit_after><|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "cpds/node.hpp"
#include "cpds/yaml.hpp"
#include "cpds/exception.hpp"
using namespace cpds;
// enforce local linkage
namespace {
Node buildExportNode()
{
Node node(Map({ { "b", true },
{ "c", 25 },
{ "d", 99.2 },
{ "e", "str with ä and / } \" \\ special\n \u0001 chars" },
{ "f", Sequence({false, 3.141592653589793, 6}) },
{ "g", Map({ {"aa", 5}, {"bb", std::numeric_limits<double>::infinity() } }) }
}));
return node;
}
} // unnamed namespace
TEST(YAML, DataExport)
{
YamlExport yaml_export;
std::string exp;
std::string cmp;
exp = yaml_export.dump(buildExportNode());
cmp = "b: true\nc: 25\nd: 99.2\ne: \"str with ä and / } \\\" \\\\ special"
"\\n \\x01 chars\"\nf:\n - false\n - 3.141592653589793\n - 6\n"
"g:\n aa: 5\n bb: inf";
EXPECT_EQ(cmp, exp);
}
TEST(YAML, DefaultDataImport)
{
YamlImport yaml_import;
std::string str;
str = "a:\nb: true\nc: 25\nd: 99.2\ne: \"str with ä and / } \\\" \\\\ special"
"\\n \\x01 chars\"\nf:\n - false\n - 3.141592653589793\n - 6\n"
"g:\n aa: 5\n bb: inf";
Node ref_node(Map({ { "a", Node() },
{ "b", true },
{ "c", 25 },
{ "d", 99.2 },
{ "e", "str with ä and / } \" \\ special\n \u0001 chars" },
{ "f", Sequence({false, 3.141592653589793, 6}) },
{ "g", Map({ {"aa", 5}, {"bb", std::numeric_limits<double>::infinity() } }) }
}));
Node node = yaml_import.load(str);
EXPECT_EQ(ref_node, node);
}
TEST(YAML, StringDataImport)
{
YamlImport yaml_import;
yaml_import.setParseScalars(false);
std::string str;
str = "a:\nb: true\nc: 25\nd: 99.2\ne: \"str with ä and / } \\\" \\\\ special"
"\\n \\x01 chars\"\nf:\n - false\n - 3.141592653589793\n - 6\n"
"g:\n aa: 5\n bb: inf";
Node ref_node(Map({ { "a", Node() },
{ "b", "true" },
{ "c", "25" },
{ "d", "99.2" },
{ "e", "str with ä and / } \" \\ special\n \u0001 chars" },
{ "f", Sequence({"false", "3.141592653589793", "6"}) },
{ "g", Map({ {"aa", "5"}, {"bb", "inf" } }) }
}));
Node node = yaml_import.load(str);
EXPECT_EQ(ref_node, node);
}
<commit_msg>update for the improved floating point handling<commit_after>#include <gtest/gtest.h>
#include "cpds/node.hpp"
#include "cpds/yaml.hpp"
#include "cpds/exception.hpp"
using namespace cpds;
// enforce local linkage
namespace {
Node buildExportNode()
{
Node node(Map({ { "b", true },
{ "c", 25 },
{ "d", 99.2 },
{ "e", "str with ä and / } \" \\ special\n \u0001 chars" },
{ "f", Sequence({false, 3.141592653589793, 6}) },
{ "g", Map({ {"aa", 5}, {"bb", std::numeric_limits<double>::infinity() } }) }
}));
return node;
}
} // unnamed namespace
TEST(YAML, DataExport)
{
YamlExport yaml_export;
std::string exp;
std::string cmp;
exp = yaml_export.dump(buildExportNode());
cmp = "b: true\nc: 25\nd: 99.2\ne: \"str with ä and / } \\\" \\\\ special"
"\\n \\x01 chars\"\nf:\n - false\n - 3.141592653589793\n - 6\n"
"g:\n aa: 5\n bb: .inf";
EXPECT_EQ(cmp, exp);
}
TEST(YAML, DefaultDataImport)
{
YamlImport yaml_import;
std::string str;
str = "a:\nb: true\nc: 25\nd: 99.2\ne: \"str with ä and / } \\\" \\\\ special"
"\\n \\x01 chars\"\nf:\n - false\n - 3.141592653589793\n - 6\n"
"g:\n aa: 5\n bb: -.inf";
Node ref_node(Map({ { "a", Node() },
{ "b", true },
{ "c", 25 },
{ "d", 99.2 },
{ "e", "str with ä and / } \" \\ special\n \u0001 chars" },
{ "f", Sequence({false, 3.141592653589793, 6}) },
{ "g", Map({ {"aa", 5}, {"bb", -std::numeric_limits<double>::infinity() } }) }
}));
Node node = yaml_import.load(str);
EXPECT_EQ(ref_node, node);
}
TEST(YAML, StringDataImport)
{
YamlImport yaml_import;
yaml_import.setParseScalars(false);
std::string str;
str = "a:\nb: true\nc: 25\nd: 99.2\ne: \"str with ä and / } \\\" \\\\ special"
"\\n \\x01 chars\"\nf:\n - false\n - 3.141592653589793\n - 6\n"
"g:\n aa: 5\n bb: .inf";
Node ref_node(Map({ { "a", Node() },
{ "b", "true" },
{ "c", "25" },
{ "d", "99.2" },
{ "e", "str with ä and / } \" \\ special\n \u0001 chars" },
{ "f", Sequence({"false", "3.141592653589793", "6"}) },
{ "g", Map({ {"aa", "5"}, {"bb", ".inf" } }) }
}));
Node node = yaml_import.load(str);
EXPECT_EQ(ref_node, node);
}
<|endoftext|> |
<commit_before><commit_msg>Change if-out definition.<commit_after><|endoftext|> |
<commit_before>//===--- Diagnostic.cpp - Framework for clang diagnostics tools ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements classes to support/store diagnostics refactoring.
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Core/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
namespace clang {
namespace tooling {
DiagnosticMessage::DiagnosticMessage(llvm::StringRef Message)
: Message(Message), FileOffset(0) {}
DiagnosticMessage::DiagnosticMessage(llvm::StringRef Message,
const SourceManager &Sources,
SourceLocation Loc)
: Message(Message) {
assert(Loc.isValid() && Loc.isFileID());
FilePath = Sources.getFilename(Loc);
FileOffset = Sources.getFileOffset(Loc);
}
Diagnostic::Diagnostic(llvm::StringRef DiagnosticName,
Diagnostic::Level DiagLevel, StringRef BuildDirectory)
: DiagnosticName(DiagnosticName), DiagLevel(DiagLevel),
BuildDirectory(BuildDirectory) {}
Diagnostic::Diagnostic(llvm::StringRef DiagnosticName,
const DiagnosticMessage &Message,
const llvm::StringMap<Replacements> &Fix,
const SmallVector<DiagnosticMessage, 1> &Notes,
Level DiagLevel, llvm::StringRef BuildDirectory)
: DiagnosticName(DiagnosticName), Message(Message), Fix(Fix), Notes(Notes),
DiagLevel(DiagLevel), BuildDirectory(BuildDirectory) {}
} // end namespace tooling
} // end namespace clang
<commit_msg>clang::tooling::Diagnostic: Don't store offset in the scratch space.<commit_after>//===--- Diagnostic.cpp - Framework for clang diagnostics tools ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements classes to support/store diagnostics refactoring.
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Core/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
namespace clang {
namespace tooling {
DiagnosticMessage::DiagnosticMessage(llvm::StringRef Message)
: Message(Message), FileOffset(0) {}
DiagnosticMessage::DiagnosticMessage(llvm::StringRef Message,
const SourceManager &Sources,
SourceLocation Loc)
: Message(Message), FileOffset(0) {
assert(Loc.isValid() && Loc.isFileID());
FilePath = Sources.getFilename(Loc);
// Don't store offset in the scratch space. It doesn't tell anything to the
// user. Moreover, it depends on the history of macro expansions and thus
// prevents deduplication of warnings in headers.
if (!FilePath.empty())
FileOffset = Sources.getFileOffset(Loc);
}
Diagnostic::Diagnostic(llvm::StringRef DiagnosticName,
Diagnostic::Level DiagLevel, StringRef BuildDirectory)
: DiagnosticName(DiagnosticName), DiagLevel(DiagLevel),
BuildDirectory(BuildDirectory) {}
Diagnostic::Diagnostic(llvm::StringRef DiagnosticName,
const DiagnosticMessage &Message,
const llvm::StringMap<Replacements> &Fix,
const SmallVector<DiagnosticMessage, 1> &Notes,
Level DiagLevel, llvm::StringRef BuildDirectory)
: DiagnosticName(DiagnosticName), Message(Message), Fix(Fix), Notes(Notes),
DiagLevel(DiagLevel), BuildDirectory(BuildDirectory) {}
} // end namespace tooling
} // end namespace clang
<|endoftext|> |
<commit_before>#include "acmacs-base/time-series.hh"
#include "acmacs-base/rjson-v3-helper.hh"
#include "acmacs-base/string-compare.hh"
#include "acmacs-map-draw/mapi-settings.hh"
#include "acmacs-map-draw/draw.hh"
// ----------------------------------------------------------------------
// "?start": "2019-01", "?end": "2019-11",
// "interval": {"month": 1}, "?": "month, week, year, day (interval: month also supported)",
// "output": "/path/name-{ts-name}.pdf",
// "shown-on-all": <Select Antigens>, -- reference antigens and sera are shown on all maps, select here other antigens to show on all the maps
// "report": true
bool acmacs::mapi::v1::Settings::apply_time_series()
{
using namespace std::string_view_literals;
auto ts_params = getenv("interval"sv).visit([]<typename Val>(const Val& val) -> acmacs::time_series::parameters {
if constexpr (std::is_same_v<Val, rjson::v3::detail::object>) {
for (const auto& interval_n : {"year"sv, "month"sv, "week"sv, "day"sv}) {
if (const auto& num = val[interval_n]; !num.is_null())
return {interval_n, num.template to<date::period_diff_t>()};
}
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
else if constexpr (std::is_same_v<Val, rjson::v3::detail::string>) {
return {val.template to<std::string_view>()};
}
else {
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
});
if (const auto& start = getenv("start"sv); !start.is_null())
ts_params.first = date::from_string(start.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
if (const auto& end = getenv("end"sv); !end.is_null())
ts_params.after_last = date::from_string(end.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
// const auto ts_stat = acmacs::time_series::stat(ts_params, tal().tree().all_dates());
// const auto [first, after_last] = acmacs::time_series::suggest_start_end(ts_params, ts_stat);
auto series = acmacs::time_series::make(ts_params);
// if (!ts_stat.counter().empty())
// AD_INFO("time series full range {} .. {}", ts_stat.counter().begin()->first, ts_stat.counter().rbegin()->first);
// AD_INFO("time series suggested {} .. {}", first, after_last);
AD_INFO("time series used {} .. {}", ts_params.first, ts_params.after_last);
if (rjson::v3::read_bool(getenv("report"sv), false)) {
// AD_INFO("time series report:\n{}", ts_stat.report(" {value} {counter:6d}\n"));
}
const auto& chart_access = chart_draw().chart(0); // can draw just the chart 0 // get_chart(getenv("chart"sv), 0);
if (const auto filename_pattern = rjson::v3::read_string(getenv("output"sv, toplevel_only::no, throw_if_partial_substitution::no)); filename_pattern.has_value()) {
auto filename{substitute_chart_metadata(*filename_pattern, chart_access)};
if (!acmacs::string::endswith_ignore_case(filename, ".pdf"sv))
filename = fmt::format("{}.pdf", filename);
chart_draw().calculate_viewport();
chart_draw().draw(filename, rjson::v3::read_number(getenv("width"sv), 800.0), report_time::no);
}
else
AD_WARNING("Cannot make time series: no \"output\" in {}", getenv_toplevel());
return true;
} // acmacs::mapi::v1::Settings::apply_time_series
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>time series API updated<commit_after>#include "acmacs-base/time-series.hh"
#include "acmacs-base/rjson-v3-helper.hh"
#include "acmacs-base/string-compare.hh"
#include "acmacs-map-draw/mapi-settings.hh"
#include "acmacs-map-draw/draw.hh"
// ----------------------------------------------------------------------
// "?start": "2019-01", "?end": "2019-11",
// "interval": {"month": 1}, "?": "month, week, year, day (interval: month also supported)",
// "output": "/path/name-{ts-name}.pdf",
// "shown-on-all": <Select Antigens>, -- reference antigens and sera are shown on all maps, select here other antigens to show on all the maps
// "report": true
bool acmacs::mapi::v1::Settings::apply_time_series()
{
using namespace std::string_view_literals;
auto ts_params = getenv("interval"sv).visit([]<typename Val>(const Val& val) -> acmacs::time_series::parameters {
if constexpr (std::is_same_v<Val, rjson::v3::detail::object>) {
for (const auto& interval_n : {"year"sv, "month"sv, "week"sv, "day"sv}) {
if (const auto& num = val[interval_n]; !num.is_null())
return {interval_n, num.template to<date::period_diff_t>()};
}
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
else if constexpr (std::is_same_v<Val, rjson::v3::detail::string>) {
return {val.template to<std::string_view>()};
}
else {
AD_WARNING("unrecognized interval specification: {}, month assumed", val);
return {"month"sv};
}
});
if (const auto& start = getenv("start"sv); !start.is_null())
ts_params.first = date::from_string(start.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
if (const auto& end = getenv("end"sv); !end.is_null())
ts_params.after_last = date::from_string(end.to<std::string_view>(), date::allow_incomplete::yes, date::throw_on_error::yes);
const auto& chart_access = chart_draw().chart(0); // can draw just the chart 0 // get_chart(getenv("chart"sv), 0);
const auto ts_stat = acmacs::time_series::stat(ts_params, chart_access.chart().antigens()->all_dates());
const auto [first, after_last] = acmacs::time_series::suggest_start_end(ts_params, ts_stat);
auto series = acmacs::time_series::make(ts_params);
if (!ts_stat.counter().empty())
AD_INFO("time series full range {} .. {}", ts_stat.counter().begin()->first, ts_stat.counter().rbegin()->first);
AD_INFO("time series suggested {} .. {}", first, after_last);
AD_INFO("time series used {} .. {}", ts_params.first, ts_params.after_last);
if (rjson::v3::read_bool(getenv("report"sv), false)) {
AD_INFO("time series report:\n{}", ts_stat.report(" {value} {counter:6d}\n"));
}
if (const auto filename_pattern = rjson::v3::read_string(getenv("output"sv, toplevel_only::no, throw_if_partial_substitution::no)); filename_pattern.has_value()) {
auto filename{substitute_chart_metadata(*filename_pattern, chart_access)};
if (!acmacs::string::endswith_ignore_case(filename, ".pdf"sv))
filename = fmt::format("{}.pdf", filename);
chart_draw().calculate_viewport();
chart_draw().draw(filename, rjson::v3::read_number(getenv("width"sv), 800.0), report_time::no);
}
else
AD_WARNING("Cannot make time series: no \"output\" in {}", getenv_toplevel());
return true;
} // acmacs::mapi::v1::Settings::apply_time_series
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIAnimationInstance.cpp
created: 7/8/2010
author: Martin Preisler
purpose: Implements the AnimationInstance class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/AnimationInstance.h"
#include "CEGUI/Animation.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/Window.h"
#include "CEGUI/Affector.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String AnimationInstance::EventNamespace("AnimationInstance");
const String AnimationInstance::EventAnimationStarted("AnimationStarted");
const String AnimationInstance::EventAnimationStopped("AnimationStopped");
const String AnimationInstance::EventAnimationPaused("AnimationPaused");
const String AnimationInstance::EventAnimationUnpaused("AnimationUnpaused");
const String AnimationInstance::EventAnimationEnded("AnimationEnded");
const String AnimationInstance::EventAnimationLooped("AnimationLooped");
//----------------------------------------------------------------------------//
AnimationInstance::AnimationInstance(Animation* definition):
d_definition(definition),
d_target(0),
d_eventReceiver(0),
d_eventSender(0),
d_position(0.0),
d_speed(1.0),
d_bounceBackwards(false),
d_running(false),
d_skipNextStep(false),
// default behaviour is to never skip
d_maxStepDeltaSkip(-1.0f),
// default behaviour is to never clamp
d_maxStepDeltaClamp(-1.0f),
d_autoSteppingEnabled(true)
{}
//----------------------------------------------------------------------------//
AnimationInstance::~AnimationInstance(void)
{
if (d_eventSender)
{
d_definition->autoUnsubscribe(this);
}
}
//----------------------------------------------------------------------------//
Animation* AnimationInstance::getDefinition() const
{
return d_definition;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setTarget(PropertySet* target)
{
d_target = target;
purgeSavedPropertyValues();
if (d_definition->getAutoStart() && !isRunning())
{
start();
}
}
//----------------------------------------------------------------------------//
PropertySet* AnimationInstance::getTarget() const
{
return d_target;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setEventReceiver(EventSet* receiver)
{
d_eventReceiver = receiver;
}
//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventReceiver() const
{
return d_eventReceiver;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setEventSender(EventSet* sender)
{
if (d_eventSender)
{
d_definition->autoUnsubscribe(this);
}
d_eventSender = sender;
if (d_eventSender)
{
d_definition->autoSubscribe(this);
}
}
//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventSender() const
{
return d_eventSender;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setTargetWindow(Window* target)
{
setTarget(target);
setEventReceiver(target);
setEventSender(target);
}
//----------------------------------------------------------------------------//
void AnimationInstance::setPosition(float position)
{
if (position < 0.0 || position > d_definition->getDuration())
{
CEGUI_THROW(InvalidRequestException(
"Unable to set position of this animation instance "
"because given position isn't in interval "
"[0.0, duration of animation]."));
}
d_position = position;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getPosition() const
{
return d_position;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setSpeed(float speed)
{
// first sort out the adventurous users
if (speed < 0.0f)
{
CEGUI_THROW(InvalidRequestException(
"You can't set playback speed to a value that's lower "
"than 0.0"));
}
if (speed == 0.0f)
{
CEGUI_THROW(InvalidRequestException(
"AnimationInstance::setSpeed: You can't set playback speed "
"to zero, please use AnimationInstance::pause instead"));
}
d_speed = speed;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getSpeed() const
{
return d_speed;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setSkipNextStep(bool skip)
{
d_skipNextStep = skip;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::getSkipNextStep() const
{
return d_skipNextStep;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaSkip(float maxDelta)
{
d_maxStepDeltaSkip = maxDelta;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaSkip() const
{
return d_maxStepDeltaSkip;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaClamp(float maxDelta)
{
d_maxStepDeltaClamp = maxDelta;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaClamp() const
{
return d_maxStepDeltaClamp;
}
//----------------------------------------------------------------------------//
void AnimationInstance::start(bool skipNextStep)
{
setPosition(0.0);
d_running = true;
d_skipNextStep = skipNextStep;
onAnimationStarted();
}
//----------------------------------------------------------------------------//
void AnimationInstance::stop()
{
setPosition(0.0);
d_running = false;
onAnimationStopped();
}
//----------------------------------------------------------------------------//
void AnimationInstance::pause()
{
d_running = false;
onAnimationPaused();
}
//----------------------------------------------------------------------------//
void AnimationInstance::unpause(bool skipNextStep)
{
d_running = true;
d_skipNextStep = skipNextStep;
onAnimationUnpaused();
}
//----------------------------------------------------------------------------//
void AnimationInstance::togglePause(bool skipNextStep)
{
if (isRunning())
{
pause();
}
else
{
unpause(skipNextStep);
}
}
//----------------------------------------------------------------------------//
bool AnimationInstance::isRunning() const
{
return d_running;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setAutoSteppingEnabled(bool enabled)
{
d_autoSteppingEnabled = enabled;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::isAutoSteppingEnabled() const
{
return d_autoSteppingEnabled;
}
//----------------------------------------------------------------------------//
void AnimationInstance::step(float delta)
{
if (!d_running)
{
// nothing to do if this animation instance isn't running
return;
}
if (delta < 0.0f)
{
CEGUI_THROW(InvalidRequestException(
"You can't step the Animation Instance with negative "
"delta! You can't reverse the flow of time, stop "
"trying!"));
}
// first we deal with delta size
if (d_maxStepDeltaSkip > 0.0f && delta > d_maxStepDeltaSkip)
{
// skip the step entirely if delta gets over the threshold
// note that default value is 0.0f which means this never gets triggered
delta = 0.0f;
}
if (d_maxStepDeltaClamp > 0.0f)
{
// clamp to threshold, note that default value is -1.0f which means
// this line does nothing (delta should always be larger or equal than 0.0f
delta = std::min(delta, d_maxStepDeltaClamp);
}
// if asked to do so, we skip this step, but mark that the next one
// shouldn't be skipped
// NB: This gets rid of annoying animation skips when FPS gets too low
// after complex layout loading, etc...
if (d_skipNextStep)
{
d_skipNextStep = false;
// we skip the step by setting delta to 0, this doesn't step the time
// but still sets the animation position accordingly
delta = 0.0f;
}
const float duration = d_definition->getDuration();
// we modify the delta according to playback speed
delta *= d_speed;
// the position could have gotten out of the desired range, we have to
// alter it depending on replay method of our animation definition
// first a simple clamp with RM_Once
if (d_definition->getReplayMode() == Animation::RM_Once)
{
float newPosition = d_position + delta;
newPosition = std::max(0.0f, newPosition);
if (newPosition >= duration)
{
newPosition = duration;
stop();
onAnimationEnded();
}
setPosition(newPosition);
}
// a both sided wrap with RM_Loop
else if (d_definition->getReplayMode() == Animation::RM_Loop)
{
float newPosition = d_position + delta;
while (newPosition > duration)
{
newPosition -= duration;
onAnimationLooped();
}
setPosition(newPosition);
}
// bounce back and forth with RM_Bounce
else if (d_definition->getReplayMode() == Animation::RM_Bounce)
{
if (d_bounceBackwards)
{
delta = -delta;
}
float newPosition = d_position + delta;
while (newPosition < 0.f || newPosition > duration)
{
if (newPosition < 0.f)
{
d_bounceBackwards = false;
newPosition = -newPosition;
onAnimationLooped();
}
if (newPosition > duration)
{
d_bounceBackwards = true;
newPosition = 2.0f * duration - newPosition;
onAnimationLooped();
}
}
setPosition(newPosition);
}
apply();
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleStart(const CEGUI::EventArgs&)
{
start();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleStop(const CEGUI::EventArgs&)
{
stop();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handlePause(const CEGUI::EventArgs&)
{
pause();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleUnpause(const CEGUI::EventArgs&)
{
unpause();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleTogglePause(const CEGUI::EventArgs&)
{
togglePause();
return true;
}
//----------------------------------------------------------------------------//
void AnimationInstance::savePropertyValue(const String& propertyName)
{
assert(d_target);
d_savedPropertyValues[propertyName] = d_target->getProperty(propertyName);
}
//----------------------------------------------------------------------------//
void AnimationInstance::purgeSavedPropertyValues(void)
{
d_savedPropertyValues.clear();
}
//----------------------------------------------------------------------------//
const String& AnimationInstance::getSavedPropertyValue(const String& propertyName)
{
PropertyValueMap::iterator it = d_savedPropertyValues.find(propertyName);
if (it == d_savedPropertyValues.end())
{
// even though we explicitly save all used property values when
// starting the animation, this can happen when user changes
// animation definition whilst the animation is running
// (Yes, it's nasty, but people do nasty things)
savePropertyValue(propertyName);
return getSavedPropertyValue(propertyName);
}
return it->second;
}
//----------------------------------------------------------------------------//
void AnimationInstance::addAutoConnection(Event::Connection conn)
{
d_autoConnections.push_back(conn);
}
//----------------------------------------------------------------------------//
void AnimationInstance::unsubscribeAutoConnections()
{
for (ConnectionTracker::iterator it = d_autoConnections.begin();
it != d_autoConnections.end(); ++it)
{
(*it)->disconnect();
}
d_autoConnections.clear();
}
//----------------------------------------------------------------------------//
void AnimationInstance::apply()
{
if (d_target)
{
d_definition->apply(this);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStarted()
{
purgeSavedPropertyValues();
d_definition->savePropertyValues(this);
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationStarted, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStopped()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationStopped, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationPaused()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationPaused, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationUnpaused()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationUnpaused, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationEnded()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationEnded, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationLooped()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationLooped, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>MOD: 0.f to 0.0f<commit_after>/***********************************************************************
filename: CEGUIAnimationInstance.cpp
created: 7/8/2010
author: Martin Preisler
purpose: Implements the AnimationInstance class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/AnimationInstance.h"
#include "CEGUI/Animation.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/Window.h"
#include "CEGUI/Affector.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String AnimationInstance::EventNamespace("AnimationInstance");
const String AnimationInstance::EventAnimationStarted("AnimationStarted");
const String AnimationInstance::EventAnimationStopped("AnimationStopped");
const String AnimationInstance::EventAnimationPaused("AnimationPaused");
const String AnimationInstance::EventAnimationUnpaused("AnimationUnpaused");
const String AnimationInstance::EventAnimationEnded("AnimationEnded");
const String AnimationInstance::EventAnimationLooped("AnimationLooped");
//----------------------------------------------------------------------------//
AnimationInstance::AnimationInstance(Animation* definition):
d_definition(definition),
d_target(0),
d_eventReceiver(0),
d_eventSender(0),
d_position(0.0),
d_speed(1.0),
d_bounceBackwards(false),
d_running(false),
d_skipNextStep(false),
// default behaviour is to never skip
d_maxStepDeltaSkip(-1.0f),
// default behaviour is to never clamp
d_maxStepDeltaClamp(-1.0f),
d_autoSteppingEnabled(true)
{}
//----------------------------------------------------------------------------//
AnimationInstance::~AnimationInstance(void)
{
if (d_eventSender)
{
d_definition->autoUnsubscribe(this);
}
}
//----------------------------------------------------------------------------//
Animation* AnimationInstance::getDefinition() const
{
return d_definition;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setTarget(PropertySet* target)
{
d_target = target;
purgeSavedPropertyValues();
if (d_definition->getAutoStart() && !isRunning())
{
start();
}
}
//----------------------------------------------------------------------------//
PropertySet* AnimationInstance::getTarget() const
{
return d_target;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setEventReceiver(EventSet* receiver)
{
d_eventReceiver = receiver;
}
//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventReceiver() const
{
return d_eventReceiver;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setEventSender(EventSet* sender)
{
if (d_eventSender)
{
d_definition->autoUnsubscribe(this);
}
d_eventSender = sender;
if (d_eventSender)
{
d_definition->autoSubscribe(this);
}
}
//----------------------------------------------------------------------------//
EventSet* AnimationInstance::getEventSender() const
{
return d_eventSender;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setTargetWindow(Window* target)
{
setTarget(target);
setEventReceiver(target);
setEventSender(target);
}
//----------------------------------------------------------------------------//
void AnimationInstance::setPosition(float position)
{
if (position < 0.0 || position > d_definition->getDuration())
{
CEGUI_THROW(InvalidRequestException(
"Unable to set position of this animation instance "
"because given position isn't in interval "
"[0.0, duration of animation]."));
}
d_position = position;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getPosition() const
{
return d_position;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setSpeed(float speed)
{
// first sort out the adventurous users
if (speed < 0.0f)
{
CEGUI_THROW(InvalidRequestException(
"You can't set playback speed to a value that's lower "
"than 0.0"));
}
if (speed == 0.0f)
{
CEGUI_THROW(InvalidRequestException(
"AnimationInstance::setSpeed: You can't set playback speed "
"to zero, please use AnimationInstance::pause instead"));
}
d_speed = speed;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getSpeed() const
{
return d_speed;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setSkipNextStep(bool skip)
{
d_skipNextStep = skip;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::getSkipNextStep() const
{
return d_skipNextStep;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaSkip(float maxDelta)
{
d_maxStepDeltaSkip = maxDelta;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaSkip() const
{
return d_maxStepDeltaSkip;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setMaxStepDeltaClamp(float maxDelta)
{
d_maxStepDeltaClamp = maxDelta;
}
//----------------------------------------------------------------------------//
float AnimationInstance::getMaxStepDeltaClamp() const
{
return d_maxStepDeltaClamp;
}
//----------------------------------------------------------------------------//
void AnimationInstance::start(bool skipNextStep)
{
setPosition(0.0);
d_running = true;
d_skipNextStep = skipNextStep;
onAnimationStarted();
}
//----------------------------------------------------------------------------//
void AnimationInstance::stop()
{
setPosition(0.0);
d_running = false;
onAnimationStopped();
}
//----------------------------------------------------------------------------//
void AnimationInstance::pause()
{
d_running = false;
onAnimationPaused();
}
//----------------------------------------------------------------------------//
void AnimationInstance::unpause(bool skipNextStep)
{
d_running = true;
d_skipNextStep = skipNextStep;
onAnimationUnpaused();
}
//----------------------------------------------------------------------------//
void AnimationInstance::togglePause(bool skipNextStep)
{
if (isRunning())
{
pause();
}
else
{
unpause(skipNextStep);
}
}
//----------------------------------------------------------------------------//
bool AnimationInstance::isRunning() const
{
return d_running;
}
//----------------------------------------------------------------------------//
void AnimationInstance::setAutoSteppingEnabled(bool enabled)
{
d_autoSteppingEnabled = enabled;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::isAutoSteppingEnabled() const
{
return d_autoSteppingEnabled;
}
//----------------------------------------------------------------------------//
void AnimationInstance::step(float delta)
{
if (!d_running)
{
// nothing to do if this animation instance isn't running
return;
}
if (delta < 0.0f)
{
CEGUI_THROW(InvalidRequestException(
"You can't step the Animation Instance with negative "
"delta! You can't reverse the flow of time, stop "
"trying!"));
}
// first we deal with delta size
if (d_maxStepDeltaSkip > 0.0f && delta > d_maxStepDeltaSkip)
{
// skip the step entirely if delta gets over the threshold
// note that default value is 0.0f which means this never gets triggered
delta = 0.0f;
}
if (d_maxStepDeltaClamp > 0.0f)
{
// clamp to threshold, note that default value is -1.0f which means
// this line does nothing (delta should always be larger or equal than 0.0f
delta = std::min(delta, d_maxStepDeltaClamp);
}
// if asked to do so, we skip this step, but mark that the next one
// shouldn't be skipped
// NB: This gets rid of annoying animation skips when FPS gets too low
// after complex layout loading, etc...
if (d_skipNextStep)
{
d_skipNextStep = false;
// we skip the step by setting delta to 0, this doesn't step the time
// but still sets the animation position accordingly
delta = 0.0f;
}
const float duration = d_definition->getDuration();
// we modify the delta according to playback speed
delta *= d_speed;
// the position could have gotten out of the desired range, we have to
// alter it depending on replay method of our animation definition
// first a simple clamp with RM_Once
if (d_definition->getReplayMode() == Animation::RM_Once)
{
float newPosition = d_position + delta;
newPosition = std::max(0.0f, newPosition);
if (newPosition >= duration)
{
newPosition = duration;
stop();
onAnimationEnded();
}
setPosition(newPosition);
}
// a both sided wrap with RM_Loop
else if (d_definition->getReplayMode() == Animation::RM_Loop)
{
float newPosition = d_position + delta;
while (newPosition > duration)
{
newPosition -= duration;
onAnimationLooped();
}
setPosition(newPosition);
}
// bounce back and forth with RM_Bounce
else if (d_definition->getReplayMode() == Animation::RM_Bounce)
{
if (d_bounceBackwards)
{
delta = -delta;
}
float newPosition = d_position + delta;
while (newPosition < 0.0f || newPosition > duration)
{
if (newPosition < 0.0f)
{
d_bounceBackwards = false;
newPosition = -newPosition;
onAnimationLooped();
}
if (newPosition > duration)
{
d_bounceBackwards = true;
newPosition = 2.0f * duration - newPosition;
onAnimationLooped();
}
}
setPosition(newPosition);
}
apply();
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleStart(const CEGUI::EventArgs&)
{
start();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleStop(const CEGUI::EventArgs&)
{
stop();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handlePause(const CEGUI::EventArgs&)
{
pause();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleUnpause(const CEGUI::EventArgs&)
{
unpause();
return true;
}
//----------------------------------------------------------------------------//
bool AnimationInstance::handleTogglePause(const CEGUI::EventArgs&)
{
togglePause();
return true;
}
//----------------------------------------------------------------------------//
void AnimationInstance::savePropertyValue(const String& propertyName)
{
assert(d_target);
d_savedPropertyValues[propertyName] = d_target->getProperty(propertyName);
}
//----------------------------------------------------------------------------//
void AnimationInstance::purgeSavedPropertyValues(void)
{
d_savedPropertyValues.clear();
}
//----------------------------------------------------------------------------//
const String& AnimationInstance::getSavedPropertyValue(const String& propertyName)
{
PropertyValueMap::iterator it = d_savedPropertyValues.find(propertyName);
if (it == d_savedPropertyValues.end())
{
// even though we explicitly save all used property values when
// starting the animation, this can happen when user changes
// animation definition whilst the animation is running
// (Yes, it's nasty, but people do nasty things)
savePropertyValue(propertyName);
return getSavedPropertyValue(propertyName);
}
return it->second;
}
//----------------------------------------------------------------------------//
void AnimationInstance::addAutoConnection(Event::Connection conn)
{
d_autoConnections.push_back(conn);
}
//----------------------------------------------------------------------------//
void AnimationInstance::unsubscribeAutoConnections()
{
for (ConnectionTracker::iterator it = d_autoConnections.begin();
it != d_autoConnections.end(); ++it)
{
(*it)->disconnect();
}
d_autoConnections.clear();
}
//----------------------------------------------------------------------------//
void AnimationInstance::apply()
{
if (d_target)
{
d_definition->apply(this);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStarted()
{
purgeSavedPropertyValues();
d_definition->savePropertyValues(this);
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationStarted, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationStopped()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationStopped, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationPaused()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationPaused, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationUnpaused()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationUnpaused, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationEnded()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationEnded, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
void AnimationInstance::onAnimationLooped()
{
if (d_eventReceiver)
{
AnimationEventArgs args(this);
d_eventReceiver->fireEvent(EventAnimationLooped, args, EventNamespace);
}
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include "latticePair.hpp"
awgPair::awgPair(unsigned long baudRate, double clockFrequency) {
_masterAWG.clockFrequency(clockFrequency);
_masterAWG.baudRate(baudRate);
_masterAWG.waveName(std::string("MASTER.WFM"));
_slaveAWG.clockFrequency(clockFrequency);
_slaveAWG.baudRate(baudRate);
_slaveAWG.waveName(std::string("SLAVE.WFM"));
}
void awgPair::baudRate(unsigned long newBaudRate) {
_masterAWG.baudRate(newBaudRate);
_slaveAWG.baudRate(newBaudRate);
}
void awgPair::clockFrequency(double newClockFrequency) {
_masterAWG.clockFrequency(newClockFrequency);
_slaveAWG.clockFrequency(newClockFrequency);
}
void awgPair::sampleRate(double newSampleRate) {
_masterAWG.sampleRate(newSampleRate);
_slaveAWG.sampleRate(newSampleRate);
}
void awgPair::startPulseLength(double newStartPulseLength) {
_masterAWG.startPulseLength(newStartPulseLength);
_slaveAWG.startPulseLength(newStartPulseLength);
}
void latticePair::addPulse(double pulseFrequency, double pulseAmplitude, double pulseDuration, double pulsePhaseDifference, bool setStart) {
_masterAWG.outputPulses.pushPulse(freqPulse(pulseFrequency, pulseAmplitude, pulseDuration, pulsePhaseDifference/2.0, setStart));
_slaveAWG.outputPulses.pushPulse(freqPulse(pulseFrequency, pulseAmplitude, pulseDuration, -pulsePhaseDifference/2.0, setStart));
}
bool latticePair::processLine(const std::string &pulseSpecLine, bool firstLine) {
double pulseFrequency, pulseAmplitude, pulseDuration, pulsePhaseDiff;
std::istringstream pulseLine(pulseSpecLine);
char delim;
// Check if WS or just a comment, if it skip the line
pulseLine >> std::skipws >> delim;
if ('#' == delim || pulseLine.eof()) return true;
pulseLine.putback(delim); // Shouldn't have removed it
// Read CSV line, return false if misformatted
pulseLine >> pulseFrequency >> delim;
if (',' != delim) return false;
pulseLine >> pulseAmplitude >> delim;
if (',' != delim) return false;
pulseLine >> pulseDuration >> delim;
if (',' != delim) return false;
pulseLine >> pulsePhaseDiff >> delim;
if ((!pulseLine.eof()) && ('#' != delim)) return false;
addPulse(pulseFrequency, pulseAmplitude, pulseDuration, pulsePhaseDiff, firstLine);
return true;
}
<commit_msg>Correct parsing to work properly, pass added tests<commit_after>#include "latticePair.hpp"
awgPair::awgPair(unsigned long baudRate, double clockFrequency) {
_masterAWG.clockFrequency(clockFrequency);
_masterAWG.baudRate(baudRate);
_masterAWG.waveName(std::string("MASTER.WFM"));
_slaveAWG.clockFrequency(clockFrequency);
_slaveAWG.baudRate(baudRate);
_slaveAWG.waveName(std::string("SLAVE.WFM"));
}
void awgPair::baudRate(unsigned long newBaudRate) {
_masterAWG.baudRate(newBaudRate);
_slaveAWG.baudRate(newBaudRate);
}
void awgPair::clockFrequency(double newClockFrequency) {
_masterAWG.clockFrequency(newClockFrequency);
_slaveAWG.clockFrequency(newClockFrequency);
}
void awgPair::sampleRate(double newSampleRate) {
_masterAWG.sampleRate(newSampleRate);
_slaveAWG.sampleRate(newSampleRate);
}
void awgPair::startPulseLength(double newStartPulseLength) {
_masterAWG.startPulseLength(newStartPulseLength);
_slaveAWG.startPulseLength(newStartPulseLength);
}
void latticePair::addPulse(double pulseFrequency, double pulseAmplitude, double pulseDuration, double pulsePhaseDifference, bool setStart) {
_masterAWG.outputPulses.pushPulse(freqPulse(pulseFrequency, pulseAmplitude, pulseDuration, pulsePhaseDifference/2.0, setStart));
_slaveAWG.outputPulses.pushPulse(freqPulse(pulseFrequency, pulseAmplitude, pulseDuration, -pulsePhaseDifference/2.0, setStart));
}
bool latticePair::processLine(const std::string &pulseSpecLine, bool firstLine) {
double pulseFrequency, pulseAmplitude, pulseDuration, pulsePhaseDiff;
std::istringstream pulseLine(pulseSpecLine);
char delim;
// Check if WS or just a comment, if it skip the line
pulseLine >> std::skipws >> delim;
if ('#' == delim || pulseLine.eof()) return true;
pulseLine.putback(delim); // Shouldn't have removed it
// Read CSV line, return false if misformatted
pulseLine >> pulseFrequency >> delim;
if ( !pulseLine.good() || ',' != delim) return false;
pulseLine >> pulseAmplitude >> delim;
if ( !pulseLine.good() || ',' != delim) return false;
pulseLine >> pulseDuration >> delim;
if ( !pulseLine.good() || ',' != delim) return false;
pulseLine >> pulsePhaseDiff;
if ( pulseLine.fail() ) return false;
pulseLine >> delim;
if ((!pulseLine.eof()) && ('#' != delim)) return false;
addPulse(pulseFrequency, pulseAmplitude, pulseDuration, pulsePhaseDiff, firstLine);
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: drawdoc.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2007-04-25 08:53:18 $
*
* 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 _DRAWDOC_HXX
#define _DRAWDOC_HXX
#ifndef _FM_FMMODEL_HXX
#include <svx/fmmodel.hxx>
#endif
class SwDoc;
class SwDocShell;
//==================================================================
class SwDrawDocument : public FmFormModel
{
SwDoc* pDoc;
public:
SwDrawDocument( SwDoc* pDoc );
~SwDrawDocument();
const SwDoc& GetDoc() const { return *pDoc; }
SwDoc& GetDoc() { return *pDoc; }
virtual SdrPage* AllocPage(FASTBOOL bMasterPage);
// fuers "load on demand" von Grafiken im DrawingLayer
virtual SvStream* GetDocumentStream( SdrDocumentStreamInfo& rInfo ) const;
// fuers Speicher von Rechtecken als Control-Ersatz fuker Versionen < 5.0
virtual SdrLayerID GetControlExportLayerId( const SdrObject & ) const;
protected:
// --> OD 2006-03-01 #b6382898#
// overload of <SdrModel::createUnoModel()> is needed to provide corresponding uno model.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createUnoModel();
// <--
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.436); FILE MERGED 2008/03/31 16:52:36 rt 1.5.436.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: drawdoc.hxx,v $
* $Revision: 1.6 $
*
* 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.
*
************************************************************************/
#ifndef _DRAWDOC_HXX
#define _DRAWDOC_HXX
#ifndef _FM_FMMODEL_HXX
#include <svx/fmmodel.hxx>
#endif
class SwDoc;
class SwDocShell;
//==================================================================
class SwDrawDocument : public FmFormModel
{
SwDoc* pDoc;
public:
SwDrawDocument( SwDoc* pDoc );
~SwDrawDocument();
const SwDoc& GetDoc() const { return *pDoc; }
SwDoc& GetDoc() { return *pDoc; }
virtual SdrPage* AllocPage(FASTBOOL bMasterPage);
// fuers "load on demand" von Grafiken im DrawingLayer
virtual SvStream* GetDocumentStream( SdrDocumentStreamInfo& rInfo ) const;
// fuers Speicher von Rechtecken als Control-Ersatz fuker Versionen < 5.0
virtual SdrLayerID GetControlExportLayerId( const SdrObject & ) const;
protected:
// --> OD 2006-03-01 #b6382898#
// overload of <SdrModel::createUnoModel()> is needed to provide corresponding uno model.
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createUnoModel();
// <--
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "lhttp_stock.hxx"
#include "lhttp_address.hxx"
#include "stock/Stock.hxx"
#include "stock/MapStock.hxx"
#include "stock/MultiStock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "pool/tpool.hxx"
#include "lease.hxx"
#include "child_stock.hxx"
#include "spawn/JailParams.hxx"
#include "spawn/Prepared.hxx"
#include "event/SocketEvent.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "io/Logger.hxx"
#include "util/RuntimeError.hxx"
#include "util/Exception.hxx"
#include <assert.h>
#include <unistd.h>
#include <string.h>
class LhttpStock final : StockClass, ChildStockClass {
ChildStock child_stock;
MultiStock mchild_stock;
StockMap hstock;
public:
LhttpStock(unsigned limit, unsigned max_idle,
EventLoop &event_loop, SpawnService &spawn_service,
SocketDescriptor log_socket) noexcept;
void FadeAll() noexcept {
hstock.FadeAll();
child_stock.GetStockMap().FadeAll();
mchild_stock.FadeAll();
}
void FadeTag(const char *tag) noexcept;
StockMap &GetConnectionStock() noexcept {
return hstock;
}
private:
/* virtual methods from class StockClass */
void Create(CreateStockItem c, void *info, struct pool &caller_pool,
CancellablePointer &cancel_ptr) override;
/* virtual methods from class ChildStockClass */
int GetChildSocketType(void *info) const noexcept override;
const char *GetChildTag(void *info) const noexcept override;
void PrepareChild(void *info, UniqueSocketDescriptor &&fd,
PreparedChildProcess &p) override;
};
class LhttpConnection final : LoggerDomainFactory, StockItem {
LazyDomainLogger logger;
StockItem *child = nullptr;
struct lease_ref lease_ref;
UniqueSocketDescriptor fd;
SocketEvent event;
public:
explicit LhttpConnection(CreateStockItem c) noexcept
:StockItem(c),
logger(*this),
event(c.stock.GetEventLoop(), BIND_THIS_METHOD(EventCallback)) {}
~LhttpConnection() noexcept override;
void Connect(MultiStock &child_stock, struct pool &caller_pool,
const char *key, void *info,
unsigned concurrency);
SocketDescriptor GetSocket() const noexcept {
assert(fd.IsDefined());
return fd;
}
gcc_pure
const char *GetTag() const noexcept {
assert(child != nullptr);
return child_stock_item_get_tag(*child);
}
void SetSite(const char *site) noexcept {
child_stock_item_set_site(*child, site);
}
void SetUri(const char *uri) noexcept {
child_stock_item_set_uri(*child, uri);
}
private:
void EventCallback(unsigned events) noexcept;
/* virtual methods from LoggerDomainFactory */
std::string MakeLoggerDomain() const noexcept override {
return GetStockName();
}
/* virtual methods from class StockItem */
bool Borrow() noexcept override {
event.Delete();
return true;
}
bool Release() noexcept override {
event.Add(EventDuration<300>::value);
return true;
}
};
void
LhttpConnection::Connect(MultiStock &child_stock, struct pool &caller_pool,
const char *key, void *info,
unsigned concurrency)
{
try {
child = child_stock.GetNow(caller_pool,
key, info, concurrency,
lease_ref);
} catch (...) {
delete this;
std::throw_with_nested(FormatRuntimeError("Failed to launch LHTTP server '%s'",
key));
}
try {
fd = child_stock_item_connect(*child);
} catch (...) {
delete this;
std::throw_with_nested(FormatRuntimeError("Failed to connect to LHTTP server '%s'",
key));
}
event.Set(fd.Get(), SocketEvent::READ);
InvokeCreateSuccess();
}
static const char *
lhttp_stock_key(struct pool *pool, const LhttpAddress *address) noexcept
{
return address->GetServerId(pool);
}
/*
* libevent callback
*
*/
inline void
LhttpConnection::EventCallback(unsigned events) noexcept
{
if ((events & SocketEvent::TIMEOUT) == 0) {
char buffer;
ssize_t nbytes = fd.Read(&buffer, sizeof(buffer));
if (nbytes < 0)
logger(2, "error on idle LHTTP connection: ", strerror(errno));
else if (nbytes > 0)
logger(2, "unexpected data from idle LHTTP connection");
}
InvokeIdleDisconnect();
}
/*
* child_stock class
*
*/
int
LhttpStock::GetChildSocketType(void *info) const noexcept
{
const auto &address = *(const LhttpAddress *)info;
int type = SOCK_STREAM;
if (!address.blocking)
type |= SOCK_NONBLOCK;
return type;
}
const char *
LhttpStock::GetChildTag(void *info) const noexcept
{
const auto &address = *(const LhttpAddress *)info;
return address.options.tag;
}
void
LhttpStock::PrepareChild(void *info, UniqueSocketDescriptor &&fd,
PreparedChildProcess &p)
{
const auto &address = *(const LhttpAddress *)info;
p.SetStdin(std::move(fd));
address.CopyTo(p);
}
/*
* stock class
*
*/
void
LhttpStock::Create(CreateStockItem c, void *info,
struct pool &caller_pool,
gcc_unused CancellablePointer &cancel_ptr)
{
const auto *address = (const LhttpAddress *)info;
assert(address != nullptr);
assert(address->path != nullptr);
auto *connection = new LhttpConnection(c);
connection->Connect(mchild_stock, caller_pool,
c.GetStockName(), info, address->concurrency);
}
LhttpConnection::~LhttpConnection() noexcept
{
if (fd.IsDefined()) {
event.Delete();
fd.Close();
}
if (child != nullptr)
lease_ref.Release(true);
}
/*
* interface
*
*/
inline
LhttpStock::LhttpStock(unsigned limit, unsigned max_idle,
EventLoop &event_loop, SpawnService &spawn_service,
SocketDescriptor log_socket) noexcept
:child_stock(event_loop, spawn_service,
*this,
log_socket,
limit, max_idle),
mchild_stock(child_stock.GetStockMap()),
hstock(event_loop, *this, limit, max_idle) {}
void
LhttpStock::FadeTag(const char *tag) noexcept
{
assert(tag != nullptr);
hstock.FadeIf([tag](const StockItem &item){
const auto &connection = (const LhttpConnection &)item;
const char *tag2 = connection.GetTag();
return tag2 != nullptr && strcmp(tag, tag2) == 0;
});
mchild_stock.FadeIf([tag](const StockItem &item){
const char *tag2 = child_stock_item_get_tag(item);
return tag2 != nullptr && strcmp(tag, tag2) == 0;
});
child_stock.FadeTag(tag);
}
LhttpStock *
lhttp_stock_new(unsigned limit, unsigned max_idle,
EventLoop &event_loop, SpawnService &spawn_service,
SocketDescriptor log_socket) noexcept
{
return new LhttpStock(limit, max_idle, event_loop, spawn_service,
log_socket);
}
void
lhttp_stock_free(LhttpStock *ls) noexcept
{
delete ls;
}
void
lhttp_stock_fade_all(LhttpStock &ls) noexcept
{
ls.FadeAll();
}
void
lhttp_stock_fade_tag(LhttpStock &ls, const char *tag) noexcept
{
ls.FadeTag(tag);
}
StockItem *
lhttp_stock_get(LhttpStock *lhttp_stock,
const LhttpAddress *address)
{
const auto *const jail = address->options.jail;
if (jail != nullptr)
jail->Check();
union {
const LhttpAddress *in;
void *out;
} deconst = { .in = address };
const AutoRewindPool auto_rewind(*tpool);
return lhttp_stock->GetConnectionStock().GetNow(*tpool,
lhttp_stock_key(tpool, address),
deconst.out);
}
SocketDescriptor
lhttp_stock_item_get_socket(const StockItem &item) noexcept
{
const auto *connection = (const LhttpConnection *)&item;
return connection->GetSocket();
}
FdType
lhttp_stock_item_get_type(gcc_unused const StockItem &item) noexcept
{
return FdType::FD_SOCKET;
}
void
lhttp_stock_item_set_site(StockItem &item, const char *site) noexcept
{
auto &connection = (LhttpConnection &)item;
connection.SetSite(site);
}
void
lhttp_stock_item_set_uri(StockItem &item, const char *uri) noexcept
{
auto &connection = (LhttpConnection &)item;
connection.SetUri(uri);
}
<commit_msg>lhttp_stock: separate TimerEvent for the timeout<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "lhttp_stock.hxx"
#include "lhttp_address.hxx"
#include "stock/Stock.hxx"
#include "stock/MapStock.hxx"
#include "stock/MultiStock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "pool/tpool.hxx"
#include "lease.hxx"
#include "child_stock.hxx"
#include "spawn/JailParams.hxx"
#include "spawn/Prepared.hxx"
#include "event/SocketEvent.hxx"
#include "event/TimerEvent.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "io/Logger.hxx"
#include "util/RuntimeError.hxx"
#include "util/Exception.hxx"
#include <assert.h>
#include <unistd.h>
#include <string.h>
class LhttpStock final : StockClass, ChildStockClass {
ChildStock child_stock;
MultiStock mchild_stock;
StockMap hstock;
public:
LhttpStock(unsigned limit, unsigned max_idle,
EventLoop &event_loop, SpawnService &spawn_service,
SocketDescriptor log_socket) noexcept;
void FadeAll() noexcept {
hstock.FadeAll();
child_stock.GetStockMap().FadeAll();
mchild_stock.FadeAll();
}
void FadeTag(const char *tag) noexcept;
StockMap &GetConnectionStock() noexcept {
return hstock;
}
private:
/* virtual methods from class StockClass */
void Create(CreateStockItem c, void *info, struct pool &caller_pool,
CancellablePointer &cancel_ptr) override;
/* virtual methods from class ChildStockClass */
int GetChildSocketType(void *info) const noexcept override;
const char *GetChildTag(void *info) const noexcept override;
void PrepareChild(void *info, UniqueSocketDescriptor &&fd,
PreparedChildProcess &p) override;
};
class LhttpConnection final : LoggerDomainFactory, StockItem {
LazyDomainLogger logger;
StockItem *child = nullptr;
struct lease_ref lease_ref;
UniqueSocketDescriptor fd;
SocketEvent event;
TimerEvent idle_timeout_event;
public:
explicit LhttpConnection(CreateStockItem c) noexcept
:StockItem(c),
logger(*this),
event(c.stock.GetEventLoop(), BIND_THIS_METHOD(EventCallback)),
idle_timeout_event(c.stock.GetEventLoop(),
BIND_THIS_METHOD(OnIdleTimeout)) {}
~LhttpConnection() noexcept override;
void Connect(MultiStock &child_stock, struct pool &caller_pool,
const char *key, void *info,
unsigned concurrency);
SocketDescriptor GetSocket() const noexcept {
assert(fd.IsDefined());
return fd;
}
gcc_pure
const char *GetTag() const noexcept {
assert(child != nullptr);
return child_stock_item_get_tag(*child);
}
void SetSite(const char *site) noexcept {
child_stock_item_set_site(*child, site);
}
void SetUri(const char *uri) noexcept {
child_stock_item_set_uri(*child, uri);
}
private:
void EventCallback(unsigned events) noexcept;
void OnIdleTimeout() noexcept;
/* virtual methods from LoggerDomainFactory */
std::string MakeLoggerDomain() const noexcept override {
return GetStockName();
}
/* virtual methods from class StockItem */
bool Borrow() noexcept override {
event.Delete();
idle_timeout_event.Cancel();
return true;
}
bool Release() noexcept override {
event.Add();
idle_timeout_event.Add(EventDuration<300>::value);
return true;
}
};
void
LhttpConnection::Connect(MultiStock &child_stock, struct pool &caller_pool,
const char *key, void *info,
unsigned concurrency)
{
try {
child = child_stock.GetNow(caller_pool,
key, info, concurrency,
lease_ref);
} catch (...) {
delete this;
std::throw_with_nested(FormatRuntimeError("Failed to launch LHTTP server '%s'",
key));
}
try {
fd = child_stock_item_connect(*child);
} catch (...) {
delete this;
std::throw_with_nested(FormatRuntimeError("Failed to connect to LHTTP server '%s'",
key));
}
event.Set(fd.Get(), SocketEvent::READ);
InvokeCreateSuccess();
}
static const char *
lhttp_stock_key(struct pool *pool, const LhttpAddress *address) noexcept
{
return address->GetServerId(pool);
}
/*
* libevent callback
*
*/
inline void
LhttpConnection::EventCallback(unsigned) noexcept
{
char buffer;
ssize_t nbytes = fd.Read(&buffer, sizeof(buffer));
if (nbytes < 0)
logger(2, "error on idle LHTTP connection: ", strerror(errno));
else if (nbytes > 0)
logger(2, "unexpected data from idle LHTTP connection");
InvokeIdleDisconnect();
}
inline void
LhttpConnection::OnIdleTimeout() noexcept
{
InvokeIdleDisconnect();
}
/*
* child_stock class
*
*/
int
LhttpStock::GetChildSocketType(void *info) const noexcept
{
const auto &address = *(const LhttpAddress *)info;
int type = SOCK_STREAM;
if (!address.blocking)
type |= SOCK_NONBLOCK;
return type;
}
const char *
LhttpStock::GetChildTag(void *info) const noexcept
{
const auto &address = *(const LhttpAddress *)info;
return address.options.tag;
}
void
LhttpStock::PrepareChild(void *info, UniqueSocketDescriptor &&fd,
PreparedChildProcess &p)
{
const auto &address = *(const LhttpAddress *)info;
p.SetStdin(std::move(fd));
address.CopyTo(p);
}
/*
* stock class
*
*/
void
LhttpStock::Create(CreateStockItem c, void *info,
struct pool &caller_pool,
gcc_unused CancellablePointer &cancel_ptr)
{
const auto *address = (const LhttpAddress *)info;
assert(address != nullptr);
assert(address->path != nullptr);
auto *connection = new LhttpConnection(c);
connection->Connect(mchild_stock, caller_pool,
c.GetStockName(), info, address->concurrency);
}
LhttpConnection::~LhttpConnection() noexcept
{
if (fd.IsDefined()) {
event.Delete();
fd.Close();
}
if (child != nullptr)
lease_ref.Release(true);
}
/*
* interface
*
*/
inline
LhttpStock::LhttpStock(unsigned limit, unsigned max_idle,
EventLoop &event_loop, SpawnService &spawn_service,
SocketDescriptor log_socket) noexcept
:child_stock(event_loop, spawn_service,
*this,
log_socket,
limit, max_idle),
mchild_stock(child_stock.GetStockMap()),
hstock(event_loop, *this, limit, max_idle) {}
void
LhttpStock::FadeTag(const char *tag) noexcept
{
assert(tag != nullptr);
hstock.FadeIf([tag](const StockItem &item){
const auto &connection = (const LhttpConnection &)item;
const char *tag2 = connection.GetTag();
return tag2 != nullptr && strcmp(tag, tag2) == 0;
});
mchild_stock.FadeIf([tag](const StockItem &item){
const char *tag2 = child_stock_item_get_tag(item);
return tag2 != nullptr && strcmp(tag, tag2) == 0;
});
child_stock.FadeTag(tag);
}
LhttpStock *
lhttp_stock_new(unsigned limit, unsigned max_idle,
EventLoop &event_loop, SpawnService &spawn_service,
SocketDescriptor log_socket) noexcept
{
return new LhttpStock(limit, max_idle, event_loop, spawn_service,
log_socket);
}
void
lhttp_stock_free(LhttpStock *ls) noexcept
{
delete ls;
}
void
lhttp_stock_fade_all(LhttpStock &ls) noexcept
{
ls.FadeAll();
}
void
lhttp_stock_fade_tag(LhttpStock &ls, const char *tag) noexcept
{
ls.FadeTag(tag);
}
StockItem *
lhttp_stock_get(LhttpStock *lhttp_stock,
const LhttpAddress *address)
{
const auto *const jail = address->options.jail;
if (jail != nullptr)
jail->Check();
union {
const LhttpAddress *in;
void *out;
} deconst = { .in = address };
const AutoRewindPool auto_rewind(*tpool);
return lhttp_stock->GetConnectionStock().GetNow(*tpool,
lhttp_stock_key(tpool, address),
deconst.out);
}
SocketDescriptor
lhttp_stock_item_get_socket(const StockItem &item) noexcept
{
const auto *connection = (const LhttpConnection *)&item;
return connection->GetSocket();
}
FdType
lhttp_stock_item_get_type(gcc_unused const StockItem &item) noexcept
{
return FdType::FD_SOCKET;
}
void
lhttp_stock_item_set_site(StockItem &item, const char *site) noexcept
{
auto &connection = (LhttpConnection &)item;
connection.SetSite(site);
}
void
lhttp_stock_item_set_uri(StockItem &item, const char *uri) noexcept
{
auto &connection = (LhttpConnection &)item;
connection.SetUri(uri);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "build/build_config.h"
// Need to include this before most other files because it defines
// IPC_MESSAGE_LOG_ENABLED. We need to use it to define
// IPC_MESSAGE_MACROS_LOG_ENABLED so render_messages.h will generate the
// ViewMsgLog et al. functions.
#include "ipc/ipc_message.h"
// On Windows, the about:ipc dialog shows IPCs; on POSIX, we hook up a
// logger in this file. (We implement about:ipc on Mac but implement
// the loggers here anyway). We need to do this real early to be sure
// IPC_MESSAGE_MACROS_LOG_ENABLED doesn't get undefined.
#if defined(OS_POSIX) && defined(IPC_MESSAGE_LOG_ENABLED)
#define IPC_MESSAGE_MACROS_LOG_ENABLED
#include "chrome/common/devtools_messages.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/worker_messages.h"
#endif
#if defined(OS_WIN)
#include <windows.h>
#endif
#include <iostream>
#include <fstream>
#include "chrome/common/logging_chrome.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/debug_util.h"
#include "base/env_var.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "ipc/ipc_logging.h"
#if defined(OS_WIN)
#include "base/logging_win.h"
#include <initguid.h>
#endif
// When true, this means that error dialogs should not be shown.
static bool dialogs_are_suppressed_ = false;
// This should be true for exactly the period between the end of
// InitChromeLogging() and the beginning of CleanupChromeLogging().
static bool chrome_logging_initialized_ = false;
#if defined(OS_WIN)
// {7FE69228-633E-4f06-80C1-527FEA23E3A7}
DEFINE_GUID(kChromeTraceProviderName,
0x7fe69228, 0x633e, 0x4f06, 0x80, 0xc1, 0x52, 0x7f, 0xea, 0x23, 0xe3, 0xa7);
#endif
// Assertion handler for logging errors that occur when dialogs are
// silenced. To record a new error, pass the log string associated
// with that error in the str parameter.
MSVC_DISABLE_OPTIMIZE();
static void SilentRuntimeAssertHandler(const std::string& str) {
DebugUtil::BreakDebugger();
}
static void SilentRuntimeReportHandler(const std::string& str) {
}
MSVC_ENABLE_OPTIMIZE();
// Suppresses error/assertion dialogs and enables the logging of
// those errors into silenced_errors_.
static void SuppressDialogs() {
if (dialogs_are_suppressed_)
return;
logging::SetLogAssertHandler(SilentRuntimeAssertHandler);
logging::SetLogReportHandler(SilentRuntimeReportHandler);
#if defined(OS_WIN)
UINT new_flags = SEM_FAILCRITICALERRORS |
SEM_NOGPFAULTERRORBOX |
SEM_NOOPENFILEERRORBOX;
// Preserve existing error mode, as discussed at http://t/dmea
UINT existing_flags = SetErrorMode(new_flags);
SetErrorMode(existing_flags | new_flags);
#endif
dialogs_are_suppressed_ = true;
}
namespace logging {
LoggingDestination DetermineLogMode(const CommandLine& command_line) {
// only use OutputDebugString in debug mode
#ifdef NDEBUG
bool enable_logging = false;
const char *kInvertLoggingSwitch = switches::kEnableLogging;
const logging::LoggingDestination kDefaultLoggingMode =
logging::LOG_ONLY_TO_FILE;
#else
bool enable_logging = true;
const char *kInvertLoggingSwitch = switches::kDisableLogging;
const logging::LoggingDestination kDefaultLoggingMode =
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG;
#endif
if (command_line.HasSwitch(kInvertLoggingSwitch))
enable_logging = !enable_logging;
logging::LoggingDestination log_mode;
if (enable_logging) {
// Let --enable-logging=stderr force only stderr, particularly useful for
// non-debug builds where otherwise you can't get logs to stderr at all.
if (command_line.GetSwitchValueASCII(switches::kEnableLogging) == "stderr")
log_mode = logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
else
log_mode = kDefaultLoggingMode;
} else {
log_mode = logging::LOG_NONE;
}
return log_mode;
}
#if defined(OS_CHROMEOS)
void SetUpSymlink(const FilePath& symlink_path, const FilePath& new_log_path) {
if (access(symlink_path.value().c_str(), F_OK) == 0 &&
file_util::Delete(symlink_path, false)) {
PLOG(ERROR) << "Unable to unlink " << symlink_path.value();
}
if (symlink(new_log_path.value().c_str(),
symlink_path.value().c_str()) == -1) {
PLOG(ERROR) << "Unable to create symlink " << symlink_path.value()
<< " pointing at " << new_log_path.value();
}
}
FilePath TimestampLog(const FilePath& new_log_file, base::Time timestamp) {
base::Time::Exploded time_deets;
timestamp.LocalExplode(&time_deets);
std::string suffix = StringPrintf("_%02d%02d%02d-%02d%02d%02d",
time_deets.year,
time_deets.month,
time_deets.day_of_month,
time_deets.hour,
time_deets.minute,
time_deets.second);
FilePath new_log_path = new_log_file.InsertBeforeExtension(suffix);
SetUpSymlink(new_log_file, new_log_path);
return new_log_path;
}
void RedirectChromeLogging(const FilePath& new_log_dir,
const CommandLine& command_line,
OldFileDeletionState delete_old_log_file) {
FilePath log_file_name = GetLogFileName().BaseName();
FilePath new_log_path =
TimestampLog(new_log_dir.Append(log_file_name), base::Time::Now());
InitLogging(new_log_path.value().c_str(),
DetermineLogMode(command_line),
logging::LOCK_LOG_FILE,
delete_old_log_file);
}
#endif
void InitChromeLogging(const CommandLine& command_line,
OldFileDeletionState delete_old_log_file) {
DCHECK(!chrome_logging_initialized_) <<
"Attempted to initialize logging when it was already initialized.";
#if defined(OS_POSIX) && defined(IPC_MESSAGE_LOG_ENABLED)
IPC::Logging::SetLoggerFunctions(g_log_function_mapping);
#endif
FilePath log_path = GetLogFileName();
#if defined(OS_CHROMEOS)
log_path = TimestampLog(log_path, base::Time::Now());
#endif
logging::InitLogging(log_path.value().c_str(),
DetermineLogMode(command_line),
logging::LOCK_LOG_FILE,
delete_old_log_file);
// we want process and thread IDs because we have a lot of things running
logging::SetLogItems(true, true, false, true);
// We call running in unattended mode "headless", and allow
// headless mode to be configured either by the Environment
// Variable or by the Command Line Switch. This is for
// automated test purposes.
scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create());
if (env->HasEnv(env_vars::kHeadless) ||
command_line.HasSwitch(switches::kNoErrorDialogs))
SuppressDialogs();
std::string log_filter_prefix =
command_line.GetSwitchValueASCII(switches::kLogFilterPrefix);
logging::SetLogFilterPrefix(log_filter_prefix.c_str());
// Use a minimum log level if the command line has one, otherwise set the
// default to LOG_WARNING.
std::string log_level = command_line.GetSwitchValueASCII(
switches::kLoggingLevel);
int level = 0;
if (StringToInt(log_level, &level)) {
if ((level >= 0) && (level < LOG_NUM_SEVERITIES))
logging::SetMinLogLevel(level);
} else {
logging::SetMinLogLevel(LOG_WARNING);
}
#if defined(OS_WIN)
// Enable trace control and transport through event tracing for Windows.
if (env->HasEnv(env_vars::kEtwLogging))
logging::LogEventProvider::Initialize(kChromeTraceProviderName);
#endif
chrome_logging_initialized_ = true;
}
// This is a no-op, but we'll keep it around in case
// we need to do more cleanup in the future.
void CleanupChromeLogging() {
DCHECK(chrome_logging_initialized_) <<
"Attempted to clean up logging when it wasn't initialized.";
CloseLogFile();
chrome_logging_initialized_ = false;
}
FilePath GetLogFileName() {
std::string filename;
scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create());
if (env->GetEnv(env_vars::kLogFileName, &filename) && !filename.empty()) {
#if defined(OS_WIN)
return FilePath(UTF8ToWide(filename).c_str());
#elif defined(OS_POSIX)
return FilePath(filename.c_str());
#endif
}
const FilePath log_filename(FILE_PATH_LITERAL("chrome_debug.log"));
FilePath log_path;
if (PathService::Get(chrome::DIR_LOGS, &log_path)) {
log_path = log_path.Append(log_filename);
return log_path;
} else {
// error with path service, just use some default file somewhere
return log_filename;
}
}
bool DialogsAreSuppressed() {
return dialogs_are_suppressed_;
}
size_t GetFatalAssertions(AssertionList* assertions) {
// In this function, we don't assume that assertions is non-null, so
// that if you just want an assertion count, you can pass in NULL.
if (assertions)
assertions->clear();
size_t assertion_count = 0;
std::ifstream log_file;
log_file.open(GetLogFileName().value().c_str());
if (!log_file.is_open())
return 0;
std::string utf8_line;
std::wstring wide_line;
while (!log_file.eof()) {
getline(log_file, utf8_line);
if (utf8_line.find(":FATAL:") != std::string::npos) {
wide_line = UTF8ToWide(utf8_line);
if (assertions)
assertions->push_back(wide_line);
++assertion_count;
}
}
log_file.close();
return assertion_count;
}
} // namespace logging
<commit_msg>be more aggressive about removing symlink to latest chrome log<commit_after>// Copyright (c) 2010 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 "build/build_config.h"
// Need to include this before most other files because it defines
// IPC_MESSAGE_LOG_ENABLED. We need to use it to define
// IPC_MESSAGE_MACROS_LOG_ENABLED so render_messages.h will generate the
// ViewMsgLog et al. functions.
#include "ipc/ipc_message.h"
// On Windows, the about:ipc dialog shows IPCs; on POSIX, we hook up a
// logger in this file. (We implement about:ipc on Mac but implement
// the loggers here anyway). We need to do this real early to be sure
// IPC_MESSAGE_MACROS_LOG_ENABLED doesn't get undefined.
#if defined(OS_POSIX) && defined(IPC_MESSAGE_LOG_ENABLED)
#define IPC_MESSAGE_MACROS_LOG_ENABLED
#include "chrome/common/devtools_messages.h"
#include "chrome/common/plugin_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/worker_messages.h"
#endif
#if defined(OS_WIN)
#include <windows.h>
#endif
#include <iostream>
#include <fstream>
#include "chrome/common/logging_chrome.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/debug_util.h"
#include "base/env_var.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "ipc/ipc_logging.h"
#if defined(OS_WIN)
#include "base/logging_win.h"
#include <initguid.h>
#endif
// When true, this means that error dialogs should not be shown.
static bool dialogs_are_suppressed_ = false;
// This should be true for exactly the period between the end of
// InitChromeLogging() and the beginning of CleanupChromeLogging().
static bool chrome_logging_initialized_ = false;
#if defined(OS_WIN)
// {7FE69228-633E-4f06-80C1-527FEA23E3A7}
DEFINE_GUID(kChromeTraceProviderName,
0x7fe69228, 0x633e, 0x4f06, 0x80, 0xc1, 0x52, 0x7f, 0xea, 0x23, 0xe3, 0xa7);
#endif
// Assertion handler for logging errors that occur when dialogs are
// silenced. To record a new error, pass the log string associated
// with that error in the str parameter.
MSVC_DISABLE_OPTIMIZE();
static void SilentRuntimeAssertHandler(const std::string& str) {
DebugUtil::BreakDebugger();
}
static void SilentRuntimeReportHandler(const std::string& str) {
}
MSVC_ENABLE_OPTIMIZE();
// Suppresses error/assertion dialogs and enables the logging of
// those errors into silenced_errors_.
static void SuppressDialogs() {
if (dialogs_are_suppressed_)
return;
logging::SetLogAssertHandler(SilentRuntimeAssertHandler);
logging::SetLogReportHandler(SilentRuntimeReportHandler);
#if defined(OS_WIN)
UINT new_flags = SEM_FAILCRITICALERRORS |
SEM_NOGPFAULTERRORBOX |
SEM_NOOPENFILEERRORBOX;
// Preserve existing error mode, as discussed at http://t/dmea
UINT existing_flags = SetErrorMode(new_flags);
SetErrorMode(existing_flags | new_flags);
#endif
dialogs_are_suppressed_ = true;
}
namespace logging {
LoggingDestination DetermineLogMode(const CommandLine& command_line) {
// only use OutputDebugString in debug mode
#ifdef NDEBUG
bool enable_logging = false;
const char *kInvertLoggingSwitch = switches::kEnableLogging;
const logging::LoggingDestination kDefaultLoggingMode =
logging::LOG_ONLY_TO_FILE;
#else
bool enable_logging = true;
const char *kInvertLoggingSwitch = switches::kDisableLogging;
const logging::LoggingDestination kDefaultLoggingMode =
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG;
#endif
if (command_line.HasSwitch(kInvertLoggingSwitch))
enable_logging = !enable_logging;
logging::LoggingDestination log_mode;
if (enable_logging) {
// Let --enable-logging=stderr force only stderr, particularly useful for
// non-debug builds where otherwise you can't get logs to stderr at all.
if (command_line.GetSwitchValueASCII(switches::kEnableLogging) == "stderr")
log_mode = logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
else
log_mode = kDefaultLoggingMode;
} else {
log_mode = logging::LOG_NONE;
}
return log_mode;
}
#if defined(OS_CHROMEOS)
void SetUpSymlink(const FilePath& symlink_path, const FilePath& new_log_path) {
// We don't care if the unlink fails; we're going to continue anyway.
if (unlink(symlink_path.value().c_str()) == -1)
PLOG(WARNING) << "Unable to unlink " << symlink_path.value();
if (symlink(new_log_path.value().c_str(),
symlink_path.value().c_str()) == -1) {
PLOG(ERROR) << "Unable to create symlink " << symlink_path.value()
<< " pointing at " << new_log_path.value();
}
}
FilePath TimestampLog(const FilePath& new_log_file, base::Time timestamp) {
base::Time::Exploded time_deets;
timestamp.LocalExplode(&time_deets);
std::string suffix = StringPrintf("_%02d%02d%02d-%02d%02d%02d",
time_deets.year,
time_deets.month,
time_deets.day_of_month,
time_deets.hour,
time_deets.minute,
time_deets.second);
FilePath new_log_path = new_log_file.InsertBeforeExtension(suffix);
SetUpSymlink(new_log_file, new_log_path);
return new_log_path;
}
void RedirectChromeLogging(const FilePath& new_log_dir,
const CommandLine& command_line,
OldFileDeletionState delete_old_log_file) {
FilePath log_file_name = GetLogFileName().BaseName();
FilePath new_log_path =
TimestampLog(new_log_dir.Append(log_file_name), base::Time::Now());
InitLogging(new_log_path.value().c_str(),
DetermineLogMode(command_line),
logging::LOCK_LOG_FILE,
delete_old_log_file);
}
#endif
void InitChromeLogging(const CommandLine& command_line,
OldFileDeletionState delete_old_log_file) {
DCHECK(!chrome_logging_initialized_) <<
"Attempted to initialize logging when it was already initialized.";
#if defined(OS_POSIX) && defined(IPC_MESSAGE_LOG_ENABLED)
IPC::Logging::SetLoggerFunctions(g_log_function_mapping);
#endif
FilePath log_path = GetLogFileName();
#if defined(OS_CHROMEOS)
log_path = TimestampLog(log_path, base::Time::Now());
#endif
logging::InitLogging(log_path.value().c_str(),
DetermineLogMode(command_line),
logging::LOCK_LOG_FILE,
delete_old_log_file);
// we want process and thread IDs because we have a lot of things running
logging::SetLogItems(true, true, false, true);
// We call running in unattended mode "headless", and allow
// headless mode to be configured either by the Environment
// Variable or by the Command Line Switch. This is for
// automated test purposes.
scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create());
if (env->HasEnv(env_vars::kHeadless) ||
command_line.HasSwitch(switches::kNoErrorDialogs))
SuppressDialogs();
std::string log_filter_prefix =
command_line.GetSwitchValueASCII(switches::kLogFilterPrefix);
logging::SetLogFilterPrefix(log_filter_prefix.c_str());
// Use a minimum log level if the command line has one, otherwise set the
// default to LOG_WARNING.
std::string log_level = command_line.GetSwitchValueASCII(
switches::kLoggingLevel);
int level = 0;
if (StringToInt(log_level, &level)) {
if ((level >= 0) && (level < LOG_NUM_SEVERITIES))
logging::SetMinLogLevel(level);
} else {
logging::SetMinLogLevel(LOG_WARNING);
}
#if defined(OS_WIN)
// Enable trace control and transport through event tracing for Windows.
if (env->HasEnv(env_vars::kEtwLogging))
logging::LogEventProvider::Initialize(kChromeTraceProviderName);
#endif
chrome_logging_initialized_ = true;
}
// This is a no-op, but we'll keep it around in case
// we need to do more cleanup in the future.
void CleanupChromeLogging() {
DCHECK(chrome_logging_initialized_) <<
"Attempted to clean up logging when it wasn't initialized.";
CloseLogFile();
chrome_logging_initialized_ = false;
}
FilePath GetLogFileName() {
std::string filename;
scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create());
if (env->GetEnv(env_vars::kLogFileName, &filename) && !filename.empty()) {
#if defined(OS_WIN)
return FilePath(UTF8ToWide(filename).c_str());
#elif defined(OS_POSIX)
return FilePath(filename.c_str());
#endif
}
const FilePath log_filename(FILE_PATH_LITERAL("chrome_debug.log"));
FilePath log_path;
if (PathService::Get(chrome::DIR_LOGS, &log_path)) {
log_path = log_path.Append(log_filename);
return log_path;
} else {
// error with path service, just use some default file somewhere
return log_filename;
}
}
bool DialogsAreSuppressed() {
return dialogs_are_suppressed_;
}
size_t GetFatalAssertions(AssertionList* assertions) {
// In this function, we don't assume that assertions is non-null, so
// that if you just want an assertion count, you can pass in NULL.
if (assertions)
assertions->clear();
size_t assertion_count = 0;
std::ifstream log_file;
log_file.open(GetLogFileName().value().c_str());
if (!log_file.is_open())
return 0;
std::string utf8_line;
std::wstring wide_line;
while (!log_file.eof()) {
getline(log_file, utf8_line);
if (utf8_line.find(":FATAL:") != std::string::npos) {
wide_line = UTF8ToWide(utf8_line);
if (assertions)
assertions->push_back(wide_line);
++assertion_count;
}
}
log_file.close();
return assertion_count;
}
} // namespace logging
<|endoftext|> |
<commit_before>/**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Logging functions.
*/
#include "thcrap.h"
#include <io.h>
#include <fcntl.h>
#include <ThreadPool.h>
// -------
// Globals
// -------
static HANDLE log_file = INVALID_HANDLE_VALUE;
static bool console_open = false;
static ThreadPool *log_queue = NULL;
// For checking nested thcrap instances that access the same log file.
// We only want to print an error message for the first instance.
static HANDLE log_filemapping = INVALID_HANDLE_VALUE;
static const char LOG[] = "logs/thcrap_log.txt";
static const char LOG_ROTATED[] = "logs/thcrap_log.%d.txt";
static const int ROTATIONS = 5; // Number of backups to keep
static void (*log_print_hook)(const char*) = NULL;
static void(*log_nprint_hook)(const char*, size_t) = NULL;
static HWND mbox_owner_hwnd = NULL; // Set by log_mbox_set_owner
// -----------------------
struct lasterror_t {
char str[DECIMAL_DIGITS_BOUND(DWORD) + 1];
};
THREAD_LOCAL(lasterror_t, lasterror_tls, nullptr, nullptr);
const char* lasterror_str_for(DWORD err)
{
switch(err) {
case ERROR_SHARING_VIOLATION:
return "File in use";
case ERROR_MOD_NOT_FOUND:
return "File not found";
default: // -Wswitch...
break;
}
auto str = lasterror_tls_get();
if(!str) {
static lasterror_t lasterror_static;
str = &lasterror_static;
}
snprintf(str->str, sizeof(str->str), "%lu", err);
return str->str;
}
const char* lasterror_str()
{
return lasterror_str_for(GetLastError());
}
void log_set_hook(void(*print_hook)(const char*), void(*nprint_hook)(const char*,size_t)){
log_print_hook = print_hook;
log_nprint_hook = nprint_hook;
}
// Rotation
// --------
void log_fn_for_rotation(char *fn, int rotnum)
{
if(rotnum == 0) {
strcpy(fn, LOG);
} else {
sprintf(fn, LOG_ROTATED, rotnum);
}
}
void log_rotate(void)
{
size_t rot_fn_len = MAX(sizeof(LOG_ROTATED), sizeof(LOG));
VLA(char, rot_from, rot_fn_len);
VLA(char, rot_to, rot_fn_len);
for(int rotation = ROTATIONS; rotation > 0; rotation--) {
log_fn_for_rotation(rot_from, rotation - 1);
log_fn_for_rotation(rot_to, rotation);
MoveFileExU(rot_from, rot_to, MOVEFILE_REPLACE_EXISTING);
}
VLA_FREE(rot_from);
VLA_FREE(rot_to);
}
// --------
void log_print(const char *str)
{
if (log_queue) {
log_queue->enqueue([str = strdup(str)]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, strlen(str), &byteRet, NULL);
}
if (log_file) {
WriteFile(log_file, str, strlen(str), &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_print_fast(const char* str, size_t n) {
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_nprint(const char *str, size_t n)
{
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_nprint_hook) {
log_nprint_hook(str, n);
}
free(str);
});
}
}
void log_vprintf(const char *format, va_list va)
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, str, total_size + 1);
vsprintf(str, format, va);
log_print_fast(str, total_size);
VLA_FREE(str);
}
}
void log_printf(const char *format, ...)
{
va_list va;
va_start(va, format);
log_vprintf(format, va);
va_end(va);
}
/**
* Message box functions.
*/
struct EnumStatus
{
HWND hwnd;
int w;
int h;
};
static BOOL CALLBACK enumWindowProc(HWND hwnd, LPARAM lParam)
{
EnumStatus *status = (EnumStatus*)lParam;
if (!IsWindowVisible(hwnd)) {
return TRUE;
}
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
if (pid != GetCurrentProcessId()) {
return TRUE;
}
RECT rect;
GetWindowRect(hwnd, &rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
if (w * h > status->w * status->h) {
status->hwnd = hwnd;
}
return TRUE;
}
static HWND guess_mbox_owner()
{
// If an owner have been set, easy - just return it.
if (mbox_owner_hwnd) {
return mbox_owner_hwnd;
}
// Time to guess. If the current thread has an active window, it's probably a good window to steal.
HWND hwnd = GetActiveWindow();
if (hwnd) {
return hwnd;
}
// It's getting harder. Look at all the top-level visible windows of our processes, and take the biggest one.
EnumStatus status;
status.hwnd = nullptr;
status.w = 10; // Ignore windows smaller than 10x10
status.h = 10;
EnumWindows(enumWindowProc, (LPARAM)&status);
if (status.hwnd) {
return status.hwnd;
}
// Let's hope our process is allowed to take the focus.
return nullptr;
}
int log_mbox(const char *caption, const UINT type, const char *text)
{
log_printf(
"---------------------------\n"
"%s\n"
"---------------------------\n"
, text
);
return MessageBox(guess_mbox_owner(), text, (caption ? caption : PROJECT_NAME), type);
}
int log_vmboxf(const char *caption, const UINT type, const char *format, va_list va)
{
int ret = 0;
if(format) {
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1);
vsprintf(formatted_str, format, va);
ret = log_mbox(caption, type, formatted_str);
VLA_FREE(formatted_str);
}
}
return ret;
}
int log_mboxf(const char *caption, const UINT type, const char *format, ...)
{
va_list va;
va_start(va, format);
int ret = log_vmboxf(caption, type, format, va);
va_end(va);
return ret;
}
void log_mbox_set_owner(HWND hwnd)
{
mbox_owner_hwnd = hwnd;
}
static void OpenConsole(void)
{
if(console_open) {
return;
}
AllocConsole();
// To match the behavior of the native Windows console, Wine additionally
// needs read rights because its WriteConsole() implementation calls
// GetConsoleMode(), and setvbuf() because… I don't know?
freopen("CONOUT$", "w+b", stdout);
setvbuf(stdout, NULL, _IONBF, 0);
/// This breaks all normal, unlogged printf() calls to stdout!
// _setmode(_fileno(stdout), _O_U16TEXT);
console_open = true;
}
/// Per-module loggers
/// ------------------
std::nullptr_t logger_t::verrorf(const char *format, va_list va) const
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1 + prefix.length());
memcpy(formatted_str, prefix.data(), prefix.length());
vsprintf(formatted_str + prefix.length(), format, va);
log_mbox(err_caption, MB_OK | MB_ICONERROR, formatted_str);
VLA_FREE(formatted_str);
}
return nullptr;
}
std::nullptr_t logger_t::errorf(const char *format, ...) const
{
va_list va;
va_start(va, format);
auto ret = verrorf(format, va);
va_end(va);
return ret;
}
/// ------------------
void log_init(int console)
{
CreateDirectoryU("logs", NULL);
log_rotate();
// Using CreateFile, _open_osfhandle and _fdopen instead of plain fopen because we need the flag FILE_SHARE_DELETE for log rotation
log_file = CreateFileU(LOG, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
log_queue = new ThreadPool(1);
#ifdef _DEBUG
OpenConsole();
#else
if(console) {
OpenConsole();
}
if(log_file) {
constexpr std::string_view DashUChar = u8"―";
const size_t line_len = (strlen(PROJECT_NAME) + strlen(" logfile")) * DashUChar.length();
VLA(char, line, line_len + 1);
line[line_len] = '\0';
for (size_t i = 0; i < line_len; i += DashUChar.length()) {
memcpy(&line[i], DashUChar.data(), DashUChar.length());
}
fprintf(log_file, "%s\n", line);
fprintf(log_file, "%s logfile\n", PROJECT_NAME);
fprintf(log_file, "Branch: %s\n", PROJECT_BRANCH);
fprintf(log_file, "Version: %s\n", PROJECT_VERSION_STRING);
fprintf(log_file, "Build time: " __DATE__ " " __TIME__ "\n");
#if defined(BUILDER_NAME_W)
{
const wchar_t *builder = BUILDER_NAME_W;
UTF8_DEC(builder);
UTF8_CONV(builder);
fprintf(log_file, "Built by: %s\n", builder_utf8);
UTF8_FREE(builder);
}
#elif defined(BUILDER_NAME)
fprintf(log_file, "Built by: %s\n", BUILDER_NAME);
#endif
fprintf(log_file, "Command line: %s\n", GetCommandLineU());
fprintf(log_file, "%s\n\n", line);
fflush(log_file);
VLA_FREE(line);
}
#endif
size_t cur_dir_len = GetCurrentDirectoryU(0, nullptr);
size_t full_fn_len = cur_dir_len + sizeof(LOG);
VLA(char, full_fn, full_fn_len);
defer(VLA_FREE(full_fn));
GetCurrentDirectoryU(cur_dir_len, full_fn);
full_fn[cur_dir_len - 1] = '/';
full_fn[cur_dir_len] = '\0';
str_slash_normalize(full_fn); // Necessary!
memcpy(full_fn + cur_dir_len, LOG, sizeof(LOG));
log_filemapping = CreateFileMappingU(
INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 1, full_fn
);
if(log_file == INVALID_HANDLE_VALUE && GetLastError() != ERROR_ALREADY_EXISTS) {
auto ret = log_mboxf(nullptr, MB_OKCANCEL | MB_ICONHAND,
"Error creating %s: %s\n"
"\n"
"Logging will be unavailable. "
"Further writes to this directory are likely to fail as well. "
"Moving %s to a different directory will probably fix this.\n"
"\n"
"Continue?",
full_fn, strerror(errno), PROJECT_NAME_SHORT
);
if(ret == IDCANCEL) {
auto pExitProcess = ((void (TH_STDCALL*)(UINT))detour_top(
"kernel32.dll", "ExitProcess", (FARPROC)thcrap_ExitProcess
));
pExitProcess(-1);
}
}
}
void log_exit(void)
{
// Run the destructor to ensure all remaining log messages were printed
delete log_queue;
if(console_open)
FreeConsole();
if(log_file) {
CloseHandle(log_filemapping);
CloseHandle(log_file);
log_file = INVALID_HANDLE_VALUE;
}
}
<commit_msg>thcrap: fix log build errors<commit_after>/**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Logging functions.
*/
#include "thcrap.h"
#include <io.h>
#include <fcntl.h>
#include <ThreadPool.h>
// -------
// Globals
// -------
static HANDLE log_file = INVALID_HANDLE_VALUE;
static bool console_open = false;
static ThreadPool *log_queue = NULL;
// For checking nested thcrap instances that access the same log file.
// We only want to print an error message for the first instance.
static HANDLE log_filemapping = INVALID_HANDLE_VALUE;
static const char LOG[] = "logs/thcrap_log.txt";
static const char LOG_ROTATED[] = "logs/thcrap_log.%d.txt";
static const int ROTATIONS = 5; // Number of backups to keep
static void (*log_print_hook)(const char*) = NULL;
static void(*log_nprint_hook)(const char*, size_t) = NULL;
static HWND mbox_owner_hwnd = NULL; // Set by log_mbox_set_owner
// -----------------------
struct lasterror_t {
char str[DECIMAL_DIGITS_BOUND(DWORD) + 1];
};
THREAD_LOCAL(lasterror_t, lasterror_tls, nullptr, nullptr);
const char* lasterror_str_for(DWORD err)
{
switch(err) {
case ERROR_SHARING_VIOLATION:
return "File in use";
case ERROR_MOD_NOT_FOUND:
return "File not found";
default: // -Wswitch...
break;
}
auto str = lasterror_tls_get();
if(!str) {
static lasterror_t lasterror_static;
str = &lasterror_static;
}
snprintf(str->str, sizeof(str->str), "%lu", err);
return str->str;
}
const char* lasterror_str()
{
return lasterror_str_for(GetLastError());
}
void log_set_hook(void(*print_hook)(const char*), void(*nprint_hook)(const char*,size_t)){
log_print_hook = print_hook;
log_nprint_hook = nprint_hook;
}
// Rotation
// --------
void log_fn_for_rotation(char *fn, int rotnum)
{
if(rotnum == 0) {
strcpy(fn, LOG);
} else {
sprintf(fn, LOG_ROTATED, rotnum);
}
}
void log_rotate(void)
{
size_t rot_fn_len = MAX(sizeof(LOG_ROTATED), sizeof(LOG));
VLA(char, rot_from, rot_fn_len);
VLA(char, rot_to, rot_fn_len);
for(int rotation = ROTATIONS; rotation > 0; rotation--) {
log_fn_for_rotation(rot_from, rotation - 1);
log_fn_for_rotation(rot_to, rotation);
MoveFileExU(rot_from, rot_to, MOVEFILE_REPLACE_EXISTING);
}
VLA_FREE(rot_from);
VLA_FREE(rot_to);
}
// --------
void log_print(const char *str)
{
if (log_queue) {
log_queue->enqueue([str = strdup(str)]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, strlen(str), &byteRet, NULL);
}
if (log_file) {
WriteFile(log_file, str, strlen(str), &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_print_fast(const char* str, size_t n) {
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_print_hook) {
log_print_hook(str);
}
free(str);
});
}
}
void log_nprint(const char *str, size_t n)
{
if (log_queue) {
log_queue->enqueue([str = strndup(str, n), n]() {
DWORD byteRet;
if (console_open) {
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), str, n, &byteRet, NULL);
}
if (log_file != INVALID_HANDLE_VALUE) {
WriteFile(log_file, str, n, &byteRet, NULL);
}
if (log_nprint_hook) {
log_nprint_hook(str, n);
}
free(str);
});
}
}
void log_vprintf(const char *format, va_list va)
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, str, total_size + 1);
vsprintf(str, format, va);
log_print_fast(str, total_size);
VLA_FREE(str);
}
}
void log_printf(const char *format, ...)
{
va_list va;
va_start(va, format);
log_vprintf(format, va);
va_end(va);
}
/**
* Message box functions.
*/
struct EnumStatus
{
HWND hwnd;
int w;
int h;
};
static BOOL CALLBACK enumWindowProc(HWND hwnd, LPARAM lParam)
{
EnumStatus *status = (EnumStatus*)lParam;
if (!IsWindowVisible(hwnd)) {
return TRUE;
}
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
if (pid != GetCurrentProcessId()) {
return TRUE;
}
RECT rect;
GetWindowRect(hwnd, &rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
if (w * h > status->w * status->h) {
status->hwnd = hwnd;
}
return TRUE;
}
static HWND guess_mbox_owner()
{
// If an owner have been set, easy - just return it.
if (mbox_owner_hwnd) {
return mbox_owner_hwnd;
}
// Time to guess. If the current thread has an active window, it's probably a good window to steal.
HWND hwnd = GetActiveWindow();
if (hwnd) {
return hwnd;
}
// It's getting harder. Look at all the top-level visible windows of our processes, and take the biggest one.
EnumStatus status;
status.hwnd = nullptr;
status.w = 10; // Ignore windows smaller than 10x10
status.h = 10;
EnumWindows(enumWindowProc, (LPARAM)&status);
if (status.hwnd) {
return status.hwnd;
}
// Let's hope our process is allowed to take the focus.
return nullptr;
}
int log_mbox(const char *caption, const UINT type, const char *text)
{
log_printf(
"---------------------------\n"
"%s\n"
"---------------------------\n"
, text
);
return MessageBox(guess_mbox_owner(), text, (caption ? caption : PROJECT_NAME), type);
}
int log_vmboxf(const char *caption, const UINT type, const char *format, va_list va)
{
int ret = 0;
if(format) {
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1);
vsprintf(formatted_str, format, va);
ret = log_mbox(caption, type, formatted_str);
VLA_FREE(formatted_str);
}
}
return ret;
}
int log_mboxf(const char *caption, const UINT type, const char *format, ...)
{
va_list va;
va_start(va, format);
int ret = log_vmboxf(caption, type, format, va);
va_end(va);
return ret;
}
void log_mbox_set_owner(HWND hwnd)
{
mbox_owner_hwnd = hwnd;
}
static void OpenConsole(void)
{
if(console_open) {
return;
}
AllocConsole();
// To match the behavior of the native Windows console, Wine additionally
// needs read rights because its WriteConsole() implementation calls
// GetConsoleMode(), and setvbuf() because… I don't know?
/// This breaks all normal, unlogged printf() calls to stdout!
// _setmode(_fileno(stdout), _O_U16TEXT);
console_open = true;
}
/// Per-module loggers
/// ------------------
std::nullptr_t logger_t::verrorf(const char *format, va_list va) const
{
va_list va2;
va_copy(va2, va);
const int total_size = vsnprintf(NULL, 0, format, va2);
va_end(va2);
if (total_size > 0) {
VLA(char, formatted_str, total_size + 1 + prefix.length());
memcpy(formatted_str, prefix.data(), prefix.length());
vsprintf(formatted_str + prefix.length(), format, va);
log_mbox(err_caption, MB_OK | MB_ICONERROR, formatted_str);
VLA_FREE(formatted_str);
}
return nullptr;
}
std::nullptr_t logger_t::errorf(const char *format, ...) const
{
va_list va;
va_start(va, format);
auto ret = verrorf(format, va);
va_end(va);
return ret;
}
/// ------------------
void log_init(int console)
{
CreateDirectoryU("logs", NULL);
log_rotate();
// Using CreateFile, _open_osfhandle and _fdopen instead of plain fopen because we need the flag FILE_SHARE_DELETE for log rotation
log_file = CreateFileU(LOG, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
log_queue = new ThreadPool(1);
#ifdef _DEBUG
OpenConsole();
#else
if(log_file) {
constexpr std::string_view DashUChar = u8"―";
const size_t line_len = (strlen(PROJECT_NAME) + strlen(" logfile")) * DashUChar.length();
VLA(char, line, line_len + 1);
line[line_len] = '\0';
for (size_t i = 0; i < line_len; i += DashUChar.length()) {
memcpy(&line[i], DashUChar.data(), DashUChar.length());
}
log_printf("%s\n", line);
log_printf("%s logfile\n", PROJECT_NAME);
log_printf("Branch: %s\n", PROJECT_BRANCH);
log_printf("Version: %s\n", PROJECT_VERSION_STRING);
log_printf("Build time: " __DATE__ " " __TIME__ "\n");
#if defined(BUILDER_NAME_W)
{
const wchar_t *builder = BUILDER_NAME_W;
UTF8_DEC(builder);
UTF8_CONV(builder);
log_printf("Built by: %s\n", builder_utf8);
UTF8_FREE(builder);
}
#elif defined(BUILDER_NAME)
log_printf("Built by: %s\n", BUILDER_NAME);
#endif
log_printf("Command line: %s\n", GetCommandLineU());
log_printf("%s\n\n", line);
FlushFileBuffers(log_file);
VLA_FREE(line);
}
if (console) {
OpenConsole();
}
#endif
size_t cur_dir_len = GetCurrentDirectoryU(0, nullptr);
size_t full_fn_len = cur_dir_len + sizeof(LOG);
VLA(char, full_fn, full_fn_len);
defer(VLA_FREE(full_fn));
GetCurrentDirectoryU(cur_dir_len, full_fn);
full_fn[cur_dir_len - 1] = '/';
full_fn[cur_dir_len] = '\0';
str_slash_normalize(full_fn); // Necessary!
memcpy(full_fn + cur_dir_len, LOG, sizeof(LOG));
log_filemapping = CreateFileMappingU(
INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 1, full_fn
);
if(log_file == INVALID_HANDLE_VALUE && GetLastError() != ERROR_ALREADY_EXISTS) {
auto ret = log_mboxf(nullptr, MB_OKCANCEL | MB_ICONHAND,
"Error creating %s: %s\n"
"\n"
"Logging will be unavailable. "
"Further writes to this directory are likely to fail as well. "
"Moving %s to a different directory will probably fix this.\n"
"\n"
"Continue?",
full_fn, strerror(errno), PROJECT_NAME_SHORT
);
if(ret == IDCANCEL) {
auto pExitProcess = ((void (TH_STDCALL*)(UINT))detour_top(
"kernel32.dll", "ExitProcess", (FARPROC)thcrap_ExitProcess
));
pExitProcess(-1);
}
}
}
void log_exit(void)
{
// Run the destructor to ensure all remaining log messages were printed
delete log_queue;
if(console_open)
FreeConsole();
if(log_file) {
CloseHandle(log_filemapping);
CloseHandle(log_file);
log_file = INVALID_HANDLE_VALUE;
}
}
<|endoftext|> |
<commit_before>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 "output_format.h"
#include "utils/parse_int.h"
#include "utils/split.h"
#include "utils/xml_encoded.h"
namespace ufal {
namespace udpipe {
// CoNLL-U output format
class output_format_conllu : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
private:
static const string underscore;
const string& underscore_on_empty(const string& str) const { return str.empty() ? underscore : str; }
};
const string output_format_conllu::underscore = "_";
void output_format_conllu::write_sentence(const sentence& s, ostream& os) {
// Comments
for (auto&& comment : s.comments)
os << comment << '\n';
// Words and multiword tokens
size_t multiword_token = 0, empty_node = 0;
for (int i = 0; i < int(s.words.size()); i++) {
// Write non-root nodes
if (i > 0) {
// Multiword token if present
if (multiword_token < s.multiword_tokens.size() &&
i == s.multiword_tokens[multiword_token].id_first) {
os << s.multiword_tokens[multiword_token].id_first << '-'
<< s.multiword_tokens[multiword_token].id_last << '\t'
<< s.multiword_tokens[multiword_token].form << "\t_\t_\t_\t_\t_\t_\t_\t"
<< underscore_on_empty(s.multiword_tokens[multiword_token].misc) << '\n';
multiword_token++;
}
// Write the word
os << i << '\t'
<< s.words[i].form << '\t'
<< underscore_on_empty(s.words[i].lemma) << '\t'
<< underscore_on_empty(s.words[i].upostag) << '\t'
<< underscore_on_empty(s.words[i].xpostag) << '\t'
<< underscore_on_empty(s.words[i].feats) << '\t';
if (s.words[i].head < 0) os << '_'; else os << s.words[i].head; os << '\t'
<< underscore_on_empty(s.words[i].deprel) << '\t'
<< underscore_on_empty(s.words[i].deps) << '\t'
<< underscore_on_empty(s.words[i].misc) << '\n';
}
// Empty nodes
for (; empty_node < s.empty_nodes.size() && i == s.empty_nodes[empty_node].id; empty_node++) {
os << i << '.' << s.empty_nodes[empty_node].index << '\t'
<< s.empty_nodes[empty_node].form << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].lemma) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].upostag) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].xpostag) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].feats) << '\t'
<< "_\t"
<< "_\t"
<< underscore_on_empty(s.empty_nodes[empty_node].deps) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].misc) << '\n';
}
}
os << endl;
}
// Matxin output format
class output_format_matxin : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
virtual void finish_document(ostream& os) override;
private:
void write_node(const sentence& s, int node, string& pad, ostream& os);
int sentences = 0;
};
void output_format_matxin::write_sentence(const sentence& s, ostream& os) {
if (!sentences) {
os << "<corpus>";
}
os << "\n<SENTENCE ord=\"" << ++sentences << "\" alloc=\"" << 0 << "\">\n";
string pad;
for (auto&& node : s.words[0].children)
write_node(s, node, pad, os);
os << "</SENTENCE>" << endl;
}
void output_format_matxin::finish_document(ostream& os) {
os << "</corpus>\n";
sentences = 0;
}
void output_format_matxin::write_node(const sentence& s, int node, string& pad, ostream& os) {
// <NODE ord="%d" alloc="%d" form="%s" lem="%s" mi="%s" si="%s">
pad.push_back(' ');
os << pad << "<NODE ord=\"" << node << "\" alloc=\"" << 0
<< "\" form=\"" << xml_encoded(s.words[node].form, true)
<< "\" lem=\"" << xml_encoded(s.words[node].lemma, true)
<< "\" mi=\"" << xml_encoded(s.words[node].feats, true)
<< "\" si=\"" << xml_encoded(s.words[node].deprel, true) << '"';
if (s.words[node].children.empty()) {
os << "/>\n";
} else {
os << ">\n";
for (auto&& child : s.words[node].children)
write_node(s, child, pad, os);
os << pad << "</NODE>\n";
}
pad.pop_back();
}
// Horizontal output format
class output_format_horizontal : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
};
void output_format_horizontal::write_sentence(const sentence& s, ostream& os) {
for (size_t i = 1; i < s.words.size(); i++) {
os << s.words[i].form;
if (i+1 < s.words.size()) os << ' ';
}
os << endl;
}
// Plaintext output format
class output_format_plaintext : public output_format {
public:
output_format_plaintext(bool normalized): normalized(normalized) {}
virtual void write_sentence(const sentence& s, ostream& os) override;
private:
bool normalized;
};
void output_format_plaintext::write_sentence(const sentence& s, ostream& os) {
if (normalized) {
for (size_t i = 1; i < s.words.size(); i++) {
if (i > 1 && s.words[i-1].get_space_after()) os << ' ';
os << s.words[i].form;
}
os << endl;
} else {
string spaces;
for (size_t i = 1; i < s.words.size(); i++) {
s.words[i].get_spaces_before(spaces); os << spaces;
os << s.words[i].form;
s.words[i].get_spaces_after(spaces); os << spaces;
}
os << flush;
}
}
// Vertical output format
class output_format_vertical : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
};
void output_format_vertical::write_sentence(const sentence& s, ostream& os) {
for (size_t i = 1; i < s.words.size(); i++)
os << s.words[i].form << '\n';
os << endl;
}
// Static factory methods
output_format* output_format::new_conllu_output_format() {
return new output_format_conllu();
}
output_format* output_format::new_matxin_output_format() {
return new output_format_matxin();
}
output_format* output_format::new_horizontal_output_format() {
return new output_format_horizontal();
}
output_format* output_format::new_plaintext_output_format() {
return new output_format_plaintext(false);
}
output_format* output_format::new_plaintext_normalized_output_format() {
return new output_format_plaintext(true);
}
output_format* output_format::new_vertical_output_format() {
return new output_format_vertical();
}
output_format* output_format::new_output_format(const string& name) {
if (name == "conllu") return new_conllu_output_format();
if (name == "matxin") return new_matxin_output_format();
if (name == "horizontal") return new_horizontal_output_format();
if (name == "plaintext") return new_plaintext_output_format();
if (name == "plaintext_normalized") return new_plaintext_normalized_output_format();
if (name == "vertical") return new_vertical_output_format();
return nullptr;
}
} // namespace udpipe
} // namespace ufal
<commit_msg>Replace spaces by in horizontal output format.<commit_after>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 "output_format.h"
#include "utils/parse_int.h"
#include "utils/split.h"
#include "utils/xml_encoded.h"
namespace ufal {
namespace udpipe {
// CoNLL-U output format
class output_format_conllu : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
private:
static const string underscore;
const string& underscore_on_empty(const string& str) const { return str.empty() ? underscore : str; }
};
const string output_format_conllu::underscore = "_";
void output_format_conllu::write_sentence(const sentence& s, ostream& os) {
// Comments
for (auto&& comment : s.comments)
os << comment << '\n';
// Words and multiword tokens
size_t multiword_token = 0, empty_node = 0;
for (int i = 0; i < int(s.words.size()); i++) {
// Write non-root nodes
if (i > 0) {
// Multiword token if present
if (multiword_token < s.multiword_tokens.size() &&
i == s.multiword_tokens[multiword_token].id_first) {
os << s.multiword_tokens[multiword_token].id_first << '-'
<< s.multiword_tokens[multiword_token].id_last << '\t'
<< s.multiword_tokens[multiword_token].form << "\t_\t_\t_\t_\t_\t_\t_\t"
<< underscore_on_empty(s.multiword_tokens[multiword_token].misc) << '\n';
multiword_token++;
}
// Write the word
os << i << '\t'
<< s.words[i].form << '\t'
<< underscore_on_empty(s.words[i].lemma) << '\t'
<< underscore_on_empty(s.words[i].upostag) << '\t'
<< underscore_on_empty(s.words[i].xpostag) << '\t'
<< underscore_on_empty(s.words[i].feats) << '\t';
if (s.words[i].head < 0) os << '_'; else os << s.words[i].head; os << '\t'
<< underscore_on_empty(s.words[i].deprel) << '\t'
<< underscore_on_empty(s.words[i].deps) << '\t'
<< underscore_on_empty(s.words[i].misc) << '\n';
}
// Empty nodes
for (; empty_node < s.empty_nodes.size() && i == s.empty_nodes[empty_node].id; empty_node++) {
os << i << '.' << s.empty_nodes[empty_node].index << '\t'
<< s.empty_nodes[empty_node].form << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].lemma) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].upostag) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].xpostag) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].feats) << '\t'
<< "_\t"
<< "_\t"
<< underscore_on_empty(s.empty_nodes[empty_node].deps) << '\t'
<< underscore_on_empty(s.empty_nodes[empty_node].misc) << '\n';
}
}
os << endl;
}
// Matxin output format
class output_format_matxin : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
virtual void finish_document(ostream& os) override;
private:
void write_node(const sentence& s, int node, string& pad, ostream& os);
int sentences = 0;
};
void output_format_matxin::write_sentence(const sentence& s, ostream& os) {
if (!sentences) {
os << "<corpus>";
}
os << "\n<SENTENCE ord=\"" << ++sentences << "\" alloc=\"" << 0 << "\">\n";
string pad;
for (auto&& node : s.words[0].children)
write_node(s, node, pad, os);
os << "</SENTENCE>" << endl;
}
void output_format_matxin::finish_document(ostream& os) {
os << "</corpus>\n";
sentences = 0;
}
void output_format_matxin::write_node(const sentence& s, int node, string& pad, ostream& os) {
// <NODE ord="%d" alloc="%d" form="%s" lem="%s" mi="%s" si="%s">
pad.push_back(' ');
os << pad << "<NODE ord=\"" << node << "\" alloc=\"" << 0
<< "\" form=\"" << xml_encoded(s.words[node].form, true)
<< "\" lem=\"" << xml_encoded(s.words[node].lemma, true)
<< "\" mi=\"" << xml_encoded(s.words[node].feats, true)
<< "\" si=\"" << xml_encoded(s.words[node].deprel, true) << '"';
if (s.words[node].children.empty()) {
os << "/>\n";
} else {
os << ">\n";
for (auto&& child : s.words[node].children)
write_node(s, child, pad, os);
os << pad << "</NODE>\n";
}
pad.pop_back();
}
// Horizontal output format
class output_format_horizontal : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
};
void output_format_horizontal::write_sentence(const sentence& s, ostream& os) {
string line;
for (size_t i = 1; i < s.words.size(); i++) {
// Append word, but replace spaces by s
for (auto&& chr : s.words[i].form)
if (chr == ' ')
line.append("\302\240");
else
line.push_back(chr);
if (i+1 < s.words.size())
line.push_back(' ');
}
os << line << endl;
}
// Plaintext output format
class output_format_plaintext : public output_format {
public:
output_format_plaintext(bool normalized): normalized(normalized) {}
virtual void write_sentence(const sentence& s, ostream& os) override;
private:
bool normalized;
};
void output_format_plaintext::write_sentence(const sentence& s, ostream& os) {
if (normalized) {
for (size_t i = 1; i < s.words.size(); i++) {
if (i > 1 && s.words[i-1].get_space_after()) os << ' ';
os << s.words[i].form;
}
os << endl;
} else {
string spaces;
for (size_t i = 1; i < s.words.size(); i++) {
s.words[i].get_spaces_before(spaces); os << spaces;
os << s.words[i].form;
s.words[i].get_spaces_after(spaces); os << spaces;
}
os << flush;
}
}
// Vertical output format
class output_format_vertical : public output_format {
public:
virtual void write_sentence(const sentence& s, ostream& os) override;
};
void output_format_vertical::write_sentence(const sentence& s, ostream& os) {
for (size_t i = 1; i < s.words.size(); i++)
os << s.words[i].form << '\n';
os << endl;
}
// Static factory methods
output_format* output_format::new_conllu_output_format() {
return new output_format_conllu();
}
output_format* output_format::new_matxin_output_format() {
return new output_format_matxin();
}
output_format* output_format::new_horizontal_output_format() {
return new output_format_horizontal();
}
output_format* output_format::new_plaintext_output_format() {
return new output_format_plaintext(false);
}
output_format* output_format::new_plaintext_normalized_output_format() {
return new output_format_plaintext(true);
}
output_format* output_format::new_vertical_output_format() {
return new output_format_vertical();
}
output_format* output_format::new_output_format(const string& name) {
if (name == "conllu") return new_conllu_output_format();
if (name == "matxin") return new_matxin_output_format();
if (name == "horizontal") return new_horizontal_output_format();
if (name == "plaintext") return new_plaintext_output_format();
if (name == "plaintext_normalized") return new_plaintext_normalized_output_format();
if (name == "vertical") return new_vertical_output_format();
return nullptr;
}
} // namespace udpipe
} // namespace ufal
<|endoftext|> |
<commit_before>#include <sys/time.h>
#include "thread_private.h"
#include "parameters.h"
#define NUM_PAGES (40960 * nthreads)
bool align_req = false;
int align_size = PAGE_SIZE;
extern bool verify_read_content;
void check_read_content(char *buf, int size, off_t off)
{
// I assume the space in the buffer is larger than 8 bytes.
off_t aligned_off = off & (~(sizeof(off_t) - 1));
long data[2];
data[0] = aligned_off / sizeof(off_t);
data[1] = aligned_off / sizeof(off_t) + 1;
long expected = 0;
int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
long read_value = 0;
memcpy(&read_value, buf, copy_size);
if(read_value != expected)
printf("%ld %ld\n", read_value, expected);
assert(read_value == expected);
}
void create_write_data(char *buf, int size, off_t off)
{
off_t aligned_start = off & (~(sizeof(off_t) - 1));
off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
long start_data = aligned_start / sizeof(off_t);
long end_data = aligned_end / sizeof(off_t);
/* If all data is in one 8-byte word. */
if (aligned_start == aligned_end) {
memcpy(buf, ((char *) &start_data) + (off - aligned_start), size);
return;
}
int first_size = (int)(sizeof(off_t) - (off - aligned_start));
int last_size = (int) (off + size - aligned_end);
if (first_size == sizeof(off_t))
first_size = 0;
if (first_size)
memcpy(buf, ((char *) &start_data) + (off - aligned_start),
first_size);
for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) {
*((long *) (buf + i)) = (off + i) / sizeof(off_t);
}
if (aligned_end > aligned_start
|| (aligned_end == aligned_start && first_size == 0)) {
if (last_size)
memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
}
check_read_content(buf, size, off);
}
class cleanup_callback: public callback
{
rand_buf *buf;
ssize_t read_bytes;
int thread_id;
thread_private *thread;
public:
cleanup_callback(rand_buf *buf, int idx, thread_private *thread) {
this->buf = buf;
read_bytes = 0;
this->thread_id = idx;
this->thread = thread;
}
int invoke(io_request *rqs[], int num) {
for (int i = 0; i < num; i++) {
io_request *rq = rqs[i];
extern bool verify_read_content;
if (rq->get_access_method() == READ && verify_read_content) {
off_t off = rq->get_offset();
for (int i = 0; i < rq->get_num_bufs(); i++) {
check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
off += rq->get_buf_size(i);
}
}
for (int i = 0; i < rq->get_num_bufs(); i++)
buf->free_entry(rq->get_buf(i));
read_bytes += rq->get_size();
}
#ifdef STATISTICS
thread->num_completes.inc(num);
thread->num_pending.dec(num);
#endif
return 0;
}
ssize_t get_size() {
return read_bytes;
}
};
ssize_t thread_private::get_read_bytes() {
if (cb)
return cb->get_size();
else
return read_bytes;
}
int thread_private::thread_init() {
attach2cpu();
io->init();
extern int buf_size;
rand_buf *buf = new rand_buf(NUM_PAGES / (nthreads
// TODO maybe I should set the right entry size for a buffer.
// If each access size is irregular, I'll break each access
// into pages so each access is no larger than a page, so it
// should workl fine.
/ NUM_NODES) * PAGE_SIZE, buf_size);
this->buf = buf;
if (io->support_aio()) {
cb = new cleanup_callback(buf, idx, this);
io->set_callback(cb);
}
return 0;
}
int thread_private::run()
{
int node_id = io->get_node_id();
ssize_t ret = -1;
gettimeofday(&start_time, NULL);
io_request reqs[NUM_REQS_BY_USER];
char *entry = NULL;
if (!io->support_aio()) {
extern int buf_size;
entry = (char *) valloc(buf_size);
}
while (gen->has_next()) {
if (io->support_aio()) {
int i;
for (i = 0; i < NUM_REQS_BY_USER && gen->has_next(); ) {
workload_t workload = gen->next();
int access_method = workload.read ? READ : WRITE;
off_t off = workload.off;
int size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
size = ROUNDUP(off + size, align_size)
- ROUND(off, align_size);
}
/*
* If the size of the request is larger than a page size,
* and the user explicitly wants to use multibuf requests.
*/
if (buf_type == MULTI_BUF) {
assert(off % PAGE_SIZE == 0);
int num_vecs = size / PAGE_SIZE;
reqs[i].init(off, io, access_method, node_id);
assert(buf->get_entry_size() >= PAGE_SIZE);
for (int k = 0; k < num_vecs; k++) {
reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
}
i++;
}
else if (buf_type == SINGLE_SMALL_BUF) {
again:
while (size > 0 && i < NUM_REQS_BY_USER) {
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + size)
next_off = off + size;
char *p = buf->next_entry(next_off - off);
if (access_method == WRITE && verify_read_content)
create_write_data(p, next_off - off, off);
reqs[i].init(p, off, next_off - off, access_method,
io, node_id);
size -= next_off - off;
off = next_off;
i++;
}
if (size > 0) {
ret = io->access(reqs, i);
#ifdef STATISTICS
num_pending.inc(i);
#endif
num_accesses += i;
i = 0;
goto again;
}
}
else {
char *p = buf->next_entry(size);
if (access_method == WRITE && verify_read_content)
create_write_data(p, size, off);
reqs[i++].init(p, off, size, access_method, io, node_id);
}
}
ret = io->access(reqs, i);
if (ret < 0) {
perror("access_vector");
exit(1);
}
num_accesses += i;
#ifdef STATISTICS
int curr = num_pending.inc(i);
if (max_num_pending < curr)
max_num_pending = curr;
if (num_accesses % 100 == 0) {
num_sampling++;
tot_num_pending += curr;
}
#endif
}
else {
workload_t workload = gen->next();
off_t off = workload.off;
int access_method = workload.read ? READ : WRITE;
int entry_size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
entry_size = ROUNDUP(off + entry_size, align_size)
- ROUND(off, align_size);
}
if (buf_type == SINGLE_SMALL_BUF) {
while (entry_size > 0) {
/*
* generate the data for writing the file,
* so the data in the file isn't changed.
*/
if (access_method == WRITE && verify_read_content) {
create_write_data(entry, entry_size, off);
}
// There is at least one byte we need to access in the page.
// By adding 1 and rounding up the offset, we'll get the next page
// behind the current offset.
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + entry_size)
next_off = off + entry_size;
ret = io->access(entry, off, next_off - off, access_method);
if (ret > 0) {
num_accesses++;
if (access_method == READ && verify_read_content) {
check_read_content(entry, next_off - off, off);
}
read_bytes += ret;
}
if (ret < 0) {
perror("access");
exit(1);
}
entry_size -= next_off - off;
off = next_off;
}
}
else {
if (access_method == WRITE && verify_read_content) {
create_write_data(entry, entry_size, off);
}
ret = io->access(entry, off, entry_size, access_method);
if (ret > 0) {
num_accesses++;
if (access_method == READ && verify_read_content) {
check_read_content(entry, entry_size, off);
}
read_bytes += ret;
}
if (ret < 0) {
perror("access");
exit(1);
}
}
}
}
io->cleanup();
printf("thread %d exits\n", idx);
gettimeofday(&end_time, NULL);
return 0;
}
int thread_private::attach2cpu()
{
#if NCPUS > 0
cpu_set_t cpuset;
pthread_t thread = pthread_self();
CPU_ZERO(&cpuset);
int cpu_num = idx % NCPUS;
CPU_SET(cpu_num, &cpuset);
int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (ret != 0) {
perror("pthread_setaffinity_np");
exit(1);
}
printf("attach thread %d to CPU %d\n", idx, cpu_num);
return ret;
#else
return -1;
#endif
}
static void *rand_read(void *arg)
{
thread_private *priv = (thread_private *) arg;
// We put the thread at the specified NUMA node at the very beginning
// to make sure all data created in this thread will be on the specified
// node.
int node_id = priv->get_io()->get_node_id();
printf("run thread rand_read: pid: %d, tid: %ld, on node %d\n",
getpid(), gettid(), node_id);
bind2node_id(node_id);
priv->thread_init();
priv->run();
return NULL;
}
#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
pid_t id = fork();
if (id < 0)
return -1;
if (id == 0) { // child
func(priv);
exit(0);
}
if (id > 0)
*pid = id;
return 0;
}
static int process_join(pid_t pid)
{
int status;
pid_t ret = waitpid(pid, &status, 0);
return ret < 0 ? ret : 0;
}
#endif
int thread_private::start_thread()
{
int ret;
#ifdef USE_PROCESS
ret = process_create(&id, rand_read, (void *) this);
#else
ret = pthread_create(&id, NULL, rand_read, (void *) this);
#endif
return ret;
}
int thread_private::wait_thread_end()
{
int ret;
#ifdef USE_PROCESS
ret = process_join(id);
#else
ret = pthread_join(id, NULL);
#endif
return ret;
}
<commit_msg>Print more useful info.<commit_after>#include <sys/time.h>
#include "thread_private.h"
#include "parameters.h"
#define NUM_PAGES (40960 * nthreads)
bool align_req = false;
int align_size = PAGE_SIZE;
extern bool verify_read_content;
void check_read_content(char *buf, int size, off_t off)
{
// I assume the space in the buffer is larger than 8 bytes.
off_t aligned_off = off & (~(sizeof(off_t) - 1));
long data[2];
data[0] = aligned_off / sizeof(off_t);
data[1] = aligned_off / sizeof(off_t) + 1;
long expected = 0;
int copy_size = size < (int) sizeof(off_t) ? size : (int) sizeof(off_t);
memcpy(&expected, ((char *) data) + (off - aligned_off), copy_size);
long read_value = 0;
memcpy(&read_value, buf, copy_size);
if(read_value != expected)
printf("%ld %ld\n", read_value, expected);
assert(read_value == expected);
}
void create_write_data(char *buf, int size, off_t off)
{
off_t aligned_start = off & (~(sizeof(off_t) - 1));
off_t aligned_end = (off + size) & (~(sizeof(off_t) - 1));
long start_data = aligned_start / sizeof(off_t);
long end_data = aligned_end / sizeof(off_t);
/* If all data is in one 8-byte word. */
if (aligned_start == aligned_end) {
memcpy(buf, ((char *) &start_data) + (off - aligned_start), size);
return;
}
int first_size = (int)(sizeof(off_t) - (off - aligned_start));
int last_size = (int) (off + size - aligned_end);
if (first_size == sizeof(off_t))
first_size = 0;
if (first_size)
memcpy(buf, ((char *) &start_data) + (off - aligned_start),
first_size);
for (int i = first_size; i < aligned_end - off; i += sizeof(off_t)) {
*((long *) (buf + i)) = (off + i) / sizeof(off_t);
}
if (aligned_end > aligned_start
|| (aligned_end == aligned_start && first_size == 0)) {
if (last_size)
memcpy(buf + (aligned_end - off), (char *) &end_data, last_size);
}
check_read_content(buf, size, off);
}
class cleanup_callback: public callback
{
rand_buf *buf;
ssize_t read_bytes;
int thread_id;
thread_private *thread;
public:
cleanup_callback(rand_buf *buf, int idx, thread_private *thread) {
this->buf = buf;
read_bytes = 0;
this->thread_id = idx;
this->thread = thread;
}
int invoke(io_request *rqs[], int num) {
for (int i = 0; i < num; i++) {
io_request *rq = rqs[i];
extern bool verify_read_content;
if (rq->get_access_method() == READ && verify_read_content) {
off_t off = rq->get_offset();
for (int i = 0; i < rq->get_num_bufs(); i++) {
check_read_content(rq->get_buf(i), rq->get_buf_size(i), off);
off += rq->get_buf_size(i);
}
}
for (int i = 0; i < rq->get_num_bufs(); i++)
buf->free_entry(rq->get_buf(i));
read_bytes += rq->get_size();
}
#ifdef STATISTICS
thread->num_completes.inc(num);
thread->num_pending.dec(num);
#endif
return 0;
}
ssize_t get_size() {
return read_bytes;
}
};
ssize_t thread_private::get_read_bytes() {
if (cb)
return cb->get_size();
else
return read_bytes;
}
int thread_private::thread_init() {
attach2cpu();
io->init();
extern int buf_size;
rand_buf *buf = new rand_buf(NUM_PAGES / (nthreads
// TODO maybe I should set the right entry size for a buffer.
// If each access size is irregular, I'll break each access
// into pages so each access is no larger than a page, so it
// should workl fine.
/ NUM_NODES) * PAGE_SIZE, buf_size);
this->buf = buf;
if (io->support_aio()) {
cb = new cleanup_callback(buf, idx, this);
io->set_callback(cb);
}
return 0;
}
int thread_private::run()
{
int node_id = io->get_node_id();
ssize_t ret = -1;
gettimeofday(&start_time, NULL);
io_request reqs[NUM_REQS_BY_USER];
char *entry = NULL;
if (!io->support_aio()) {
extern int buf_size;
entry = (char *) valloc(buf_size);
}
while (gen->has_next()) {
if (io->support_aio()) {
int i;
for (i = 0; i < NUM_REQS_BY_USER && gen->has_next(); ) {
workload_t workload = gen->next();
int access_method = workload.read ? READ : WRITE;
off_t off = workload.off;
int size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
size = ROUNDUP(off + size, align_size)
- ROUND(off, align_size);
}
/*
* If the size of the request is larger than a page size,
* and the user explicitly wants to use multibuf requests.
*/
if (buf_type == MULTI_BUF) {
assert(off % PAGE_SIZE == 0);
int num_vecs = size / PAGE_SIZE;
reqs[i].init(off, io, access_method, node_id);
assert(buf->get_entry_size() >= PAGE_SIZE);
for (int k = 0; k < num_vecs; k++) {
reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE);
}
i++;
}
else if (buf_type == SINGLE_SMALL_BUF) {
again:
while (size > 0 && i < NUM_REQS_BY_USER) {
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + size)
next_off = off + size;
char *p = buf->next_entry(next_off - off);
if (access_method == WRITE && verify_read_content)
create_write_data(p, next_off - off, off);
reqs[i].init(p, off, next_off - off, access_method,
io, node_id);
size -= next_off - off;
off = next_off;
i++;
}
if (size > 0) {
ret = io->access(reqs, i);
#ifdef STATISTICS
num_pending.inc(i);
#endif
num_accesses += i;
i = 0;
goto again;
}
}
else {
char *p = buf->next_entry(size);
if (access_method == WRITE && verify_read_content)
create_write_data(p, size, off);
reqs[i++].init(p, off, size, access_method, io, node_id);
}
}
ret = io->access(reqs, i);
if (ret < 0) {
perror("access_vector");
exit(1);
}
num_accesses += i;
#ifdef STATISTICS
int curr = num_pending.inc(i);
if (max_num_pending < curr)
max_num_pending = curr;
if (num_accesses % 100 == 0) {
num_sampling++;
tot_num_pending += curr;
}
#endif
}
else {
workload_t workload = gen->next();
off_t off = workload.off;
int access_method = workload.read ? READ : WRITE;
int entry_size = workload.size;
if (align_req) {
off = ROUND(off, align_size);
entry_size = ROUNDUP(off + entry_size, align_size)
- ROUND(off, align_size);
}
if (buf_type == SINGLE_SMALL_BUF) {
while (entry_size > 0) {
/*
* generate the data for writing the file,
* so the data in the file isn't changed.
*/
if (access_method == WRITE && verify_read_content) {
create_write_data(entry, entry_size, off);
}
// There is at least one byte we need to access in the page.
// By adding 1 and rounding up the offset, we'll get the next page
// behind the current offset.
off_t next_off = ROUNDUP_PAGE(off + 1);
if (next_off > off + entry_size)
next_off = off + entry_size;
ret = io->access(entry, off, next_off - off, access_method);
if (ret > 0) {
num_accesses++;
if (access_method == READ && verify_read_content) {
check_read_content(entry, next_off - off, off);
}
read_bytes += ret;
}
if (ret == 0)
printf("read %ld get 0 bytes\n", off);
if (ret < 0) {
perror("access");
exit(1);
}
entry_size -= next_off - off;
off = next_off;
}
}
else {
if (access_method == WRITE && verify_read_content) {
create_write_data(entry, entry_size, off);
}
ret = io->access(entry, off, entry_size, access_method);
if (ret > 0) {
num_accesses++;
if (access_method == READ && verify_read_content) {
check_read_content(entry, entry_size, off);
}
read_bytes += ret;
}
if (ret < 0) {
perror("access");
exit(1);
}
}
}
}
io->cleanup();
printf("thread %d exits\n", idx);
gettimeofday(&end_time, NULL);
return 0;
}
int thread_private::attach2cpu()
{
#if NCPUS > 0
cpu_set_t cpuset;
pthread_t thread = pthread_self();
CPU_ZERO(&cpuset);
int cpu_num = idx % NCPUS;
CPU_SET(cpu_num, &cpuset);
int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (ret != 0) {
perror("pthread_setaffinity_np");
exit(1);
}
printf("attach thread %d to CPU %d\n", idx, cpu_num);
return ret;
#else
return -1;
#endif
}
static void *rand_read(void *arg)
{
thread_private *priv = (thread_private *) arg;
// We put the thread at the specified NUMA node at the very beginning
// to make sure all data created in this thread will be on the specified
// node.
int node_id = priv->get_io()->get_node_id();
time_t curr_time = time(NULL);
printf("run thread rand_read: pid: %d, tid: %ld, on node %d at %s",
getpid(), gettid(), node_id, ctime(&curr_time));
bind2node_id(node_id);
priv->thread_init();
priv->run();
return NULL;
}
#ifdef USE_PROCESS
static int process_create(pid_t *pid, void (*func)(void *), void *priv)
{
pid_t id = fork();
if (id < 0)
return -1;
if (id == 0) { // child
func(priv);
exit(0);
}
if (id > 0)
*pid = id;
return 0;
}
static int process_join(pid_t pid)
{
int status;
pid_t ret = waitpid(pid, &status, 0);
return ret < 0 ? ret : 0;
}
#endif
int thread_private::start_thread()
{
int ret;
#ifdef USE_PROCESS
ret = process_create(&id, rand_read, (void *) this);
#else
ret = pthread_create(&id, NULL, rand_read, (void *) this);
#endif
return ret;
}
int thread_private::wait_thread_end()
{
int ret;
#ifdef USE_PROCESS
ret = process_join(id);
#else
ret = pthread_join(id, NULL);
#endif
return ret;
}
<|endoftext|> |
<commit_before>#include <QtTest/QtTest>
#include <QLocalSocket>
#include <gui/shell.h>
#include "common.h"
namespace NeovimQt {
class Test: public QObject
{
Q_OBJECT
private slots:
void benchStart() {
QBENCHMARK {
NeovimConnector *c = NeovimConnector::spawn();
QSignalSpy onReady(c, SIGNAL(ready()));
QVERIFY(onReady.isValid());
QVERIFY(SPYWAIT(onReady));
Shell *s = new Shell(c);
QSignalSpy onResize(s, SIGNAL(neovimResized(int, int)));
QVERIFY(onResize.isValid());
QVERIFY(SPYWAIT(onResize));
}
}
protected:
NeovimQt::NeovimConnector *m_c;
};
} // Namespace NeovimQt
QTEST_MAIN(NeovimQt::Test)
#include "tst_shell.moc"
<commit_msg>GUI: POC unit test<commit_after>#include <QtTest/QtTest>
#include <QLocalSocket>
#include <gui/shell.h>
#include "common.h"
namespace NeovimQt {
class Test: public QObject
{
Q_OBJECT
private slots:
void benchStart() {
QBENCHMARK {
NeovimConnector *c = NeovimConnector::spawn();
QSignalSpy onReady(c, SIGNAL(ready()));
QVERIFY(onReady.isValid());
QVERIFY(SPYWAIT(onReady));
Shell *s = new Shell(c);
QSignalSpy onResize(s, SIGNAL(neovimResized(int, int)));
QVERIFY(onResize.isValid());
QVERIFY(SPYWAIT(onResize));
}
}
void uiStart() {
QStringList args;
args << "-u" << "NONE";
NeovimConnector *c = NeovimConnector::spawn(args);
Shell *s = new Shell(c);
QSignalSpy onAttached(s, SIGNAL(neovimAttached(bool)));
QVERIFY(onAttached.isValid());
QVERIFY(SPYWAIT(onAttached));
QVERIFY(s->neovimAttached());
s->repaint();
QPixmap p = s->grab();
p.save("tst_shell_start.jpg");
}
protected:
NeovimQt::NeovimConnector *m_c;
};
} // Namespace NeovimQt
QTEST_MAIN(NeovimQt::Test)
#include "tst_shell.moc"
<|endoftext|> |
<commit_before>/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include <gst/gst.h>
#include "RabbitMQConnection.hpp"
#include <amqp.h>
#include <amqp_tcp_socket.h>
#include <gst/gst.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#define GST_CAT_DEFAULT kurento_rabbitmq_connection
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoRabbitMQConnection"
namespace kurento
{
static void
exception_on_error (amqp_rpc_reply_t x, const char *context)
{
std::string ctx = context;
switch (x.reply_type) {
case AMQP_RESPONSE_NORMAL:
return;
case AMQP_RESPONSE_NONE:
throw RabbitMQException (ctx + ": missing RPC reply type");
case AMQP_RESPONSE_LIBRARY_EXCEPTION:
if (AMQP_STATUS_TIMEOUT == x.library_error) {
throw RabbitMQTimeoutException (ctx + ": Tiemout exception: " +
amqp_error_string2 (x.library_error) );
} else {
throw RabbitMQException (ctx + ": Library exception: " +
amqp_error_string2 (x.library_error) );
}
case AMQP_RESPONSE_SERVER_EXCEPTION:
switch (x.reply.id) {
case AMQP_CONNECTION_CLOSE_METHOD: {
amqp_connection_close_t *m = (amqp_connection_close_t *) x.reply.decoded;
std::string message;
gchar *error_message;
error_message =
g_strdup_printf ("%s: server connection error %d, message: %.*s\n", context,
m->reply_code, (int) m->reply_text.len, (char *) m->reply_text.bytes);
message = error_message;
g_free (error_message);
throw RabbitMQException (message);
}
case AMQP_CHANNEL_CLOSE_METHOD: {
amqp_channel_close_t *m = (amqp_channel_close_t *) x.reply.decoded;
std::string message;
gchar *error_message;
error_message = g_strdup_printf ("%s: server channel error %d, message: %.*s\n",
context, m->reply_code, (int) m->reply_text.len, (char *) m->reply_text.bytes);
message = error_message;
g_free (error_message);
throw RabbitMQException (message);
break;
}
default:
throw RabbitMQException (ctx + ": Channel Unknown Error");
break;
}
break;
}
}
static void
makeSocketLinger (int fd)
{
struct linger ling;
ling.l_onoff = 1;
ling.l_linger = 30;
if (setsockopt (fd, SOL_SOCKET, SO_LINGER, &ling, sizeof (ling) ) < 0) {
GST_WARNING ("Could not configure SO_LINGER option on RabbitMQ socket");
}
}
RabbitMQConnection::RabbitMQConnection (const std::string &address, int port) :
address (address), port (port)
{
conn = amqp_new_connection();
socket = amqp_tcp_socket_new (conn);
if (!socket) {
throw Glib::IOChannelError (Glib::IOChannelError::Code::FAILED,
"Cannot create TCP socket");
}
if (amqp_socket_open (socket, address.c_str(), port) ) {
throw Glib::IOChannelError (Glib::IOChannelError::Code::FAILED,
"Cannot open TCP socket");
}
makeSocketLinger (amqp_socket_get_sockfd (socket) );
exception_on_error (amqp_login (conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
"guest", "guest"), "Loging in");
amqp_channel_open (conn, 1);
exception_on_error (amqp_get_rpc_reply (conn), "Opening channel");
}
RabbitMQConnection::~RabbitMQConnection()
{
if (conn == NULL) {
GST_DEBUG ("service already stopped");
return;
}
/* Errors are ignored during close */
if (!closeOnRelease) {
int fd = amqp_socket_get_sockfd (socket);
/* inform remote side that we are done */
shutdown (fd, SHUT_WR);
/* close socket */
close (fd);
}
amqp_channel_close (conn, 1, AMQP_REPLY_SUCCESS);
amqp_connection_close (conn, AMQP_REPLY_SUCCESS);
amqp_destroy_connection (conn);
conn = NULL;
}
int
RabbitMQConnection::getFd()
{
return amqp_socket_get_sockfd (socket);
}
void RabbitMQConnection::declareQueue (const std::string &queue_name,
bool durable, int ttl)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_table_entry_t entries[1];
amqp_table_t table;
table.entries = entries;
if (ttl > 0) {
table.num_entries = 1;
entries[0].key = amqp_cstring_bytes ("x-expires");
entries[0].value.kind = AMQP_FIELD_KIND_I32;
entries[0].value.value.i32 = ttl;
} else {
table.num_entries = 0;
}
amqp_queue_declare (conn, 1,
queue, /* passive */ false, durable, /* exclusive */ false,
/* autodelete */ false, table);
exception_on_error (amqp_get_rpc_reply (conn), "Declaring queue");
}
void RabbitMQConnection::deleteQueue (const std::string &queue_name,
bool ifUnused, bool ifEmpty)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_queue_delete (conn, 1, queue, ifUnused, ifEmpty);
}
void RabbitMQConnection::declareExchange (const std::string &exchange_name,
const std::string &type, bool durable, const int ttl)
{
amqp_bytes_t exchange = amqp_cstring_bytes (exchange_name.c_str() );
amqp_bytes_t exchange_type = amqp_cstring_bytes (type.c_str() );
amqp_table_entry_t entries[1];
amqp_table_t table;
table.entries = entries;
if (ttl > 0) {
table.num_entries = 1;
entries[0].key = amqp_cstring_bytes ("x-expires");
entries[0].value.kind = AMQP_FIELD_KIND_I32;
entries[0].value.value.i32 = ttl;
} else {
table.num_entries = 0;
}
amqp_exchange_declare (conn, 1, exchange, exchange_type,
/* passive */ false, durable, table);
exception_on_error (amqp_get_rpc_reply (conn), "Declaring exchange");
}
void RabbitMQConnection::deleteExchange (const std::string &exchange_name,
bool ifUnused)
{
amqp_bytes_t exchange = amqp_cstring_bytes (exchange_name.c_str() );
amqp_exchange_delete (conn, 1, exchange, ifUnused);
}
void
RabbitMQConnection::bindQueue (const std::string &queue_name,
const std::string &exchange_name)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_bytes_t exchange = amqp_cstring_bytes (exchange_name.c_str() );
amqp_queue_bind (conn, 1, queue, exchange, amqp_empty_bytes,
amqp_empty_table);
exception_on_error (amqp_get_rpc_reply (conn), "Binding queue");
}
void
RabbitMQConnection::consumeQueue (const std::string &queue_name,
const std::string &tag)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_bytes_t tag_id = amqp_cstring_bytes (tag.c_str() );
amqp_basic_consume (conn, 1, queue, tag_id, /* no_local */ false,
/* no_ack */ false, /* exclusive */ false,
amqp_empty_table);
exception_on_error (amqp_get_rpc_reply (conn), "Consuming");
}
void
RabbitMQConnection::readMessage (struct timeval *timeout,
std::function <void (RabbitMQMessage &) > process)
{
RabbitMQMessage message (shared_from_this () );
exception_on_error (amqp_consume_message (conn, &message.envelope, timeout, 0),
"Reading message");
message.valid = true;
try {
process (message);
} catch (...) {
GST_WARNING ("Error processing message");
}
}
void
RabbitMQConnection::sendReply (const amqp_envelope_t &envelope,
const amqp_bytes_t &reply)
{
sendMessage (reply, amqp_empty_bytes, envelope.message.properties.reply_to,
envelope.message.properties.correlation_id);
}
void
RabbitMQConnection::sendMessage (const std::string &message,
const std::string &exchange, const std::string &routingKey,
const std::string &correlationID)
{
sendMessage (amqp_cstring_bytes (message.c_str() ),
amqp_cstring_bytes (exchange.c_str() ),
amqp_cstring_bytes (routingKey.c_str() ),
amqp_cstring_bytes (correlationID.c_str() ) );
}
void
RabbitMQConnection::sendMessage (const amqp_bytes_t &message,
const amqp_bytes_t &exchange, const amqp_bytes_t &routingKey,
const amqp_bytes_t &correlationID)
{
amqp_basic_properties_t props;
int ret;
props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
props.content_type = amqp_cstring_bytes ("text/plain");
props.delivery_mode = 2; /* persistent delivery mode */
if (correlationID.len > 0) {
props._flags |= AMQP_BASIC_CORRELATION_ID_FLAG;
props.correlation_id = correlationID;
}
ret = amqp_basic_publish (conn, 1, exchange,
routingKey, /* mandatory */ false, /* inmediate */ false, &props, message);
if (ret != AMQP_STATUS_OK) {
GST_ERROR ("Error ret value: %d", ret);
}
}
RabbitMQMessage::RabbitMQMessage (std::shared_ptr <RabbitMQConnection>
connection) : connection (connection)
{
}
RabbitMQMessage::~RabbitMQMessage()
{
if (!acked && valid) {
GST_WARNING ("Rejecting message because it is not acked");
amqp_basic_reject (connection->conn, 1,
envelope.delivery_tag, /* requeue */ true);
}
amqp_destroy_envelope (&envelope);
}
void
RabbitMQMessage::reply (std::shared_ptr< RabbitMQConnection > conn,
const std::string &response)
{
conn->sendReply (envelope, amqp_cstring_bytes (response.c_str() ) );
}
void
RabbitMQMessage::reply (const std::string &response)
{
reply (connection, response);
}
std::string
RabbitMQMessage::getData()
{
std::string data (reinterpret_cast<char const *>
(envelope.message.body.bytes), envelope.message.body.len );
return data;
}
void
RabbitMQMessage::ack()
{
amqp_basic_ack (connection->conn, 1,
envelope.delivery_tag, /* multiple */ false);
acked = true;
}
RabbitMQConnection::StaticConstructor RabbitMQConnection::staticConstructor;
RabbitMQConnection::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
const std::string RabbitMQConnection::EXCHANGE_TYPE_DIRECT ("direct");
const std::string RabbitMQConnection::EXCHANGE_TYPE_FANOUT ("fanout");
const std::string RabbitMQConnection::EXCHANGE_TYPE_TOPIC ("topic");
} /* kurento */
<commit_msg>RabbitMQ: Do not shutdown socket if closeOnRelease is not set<commit_after>/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include <gst/gst.h>
#include "RabbitMQConnection.hpp"
#include <amqp.h>
#include <amqp_tcp_socket.h>
#include <gst/gst.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#define GST_CAT_DEFAULT kurento_rabbitmq_connection
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoRabbitMQConnection"
namespace kurento
{
static void
exception_on_error (amqp_rpc_reply_t x, const char *context)
{
std::string ctx = context;
switch (x.reply_type) {
case AMQP_RESPONSE_NORMAL:
return;
case AMQP_RESPONSE_NONE:
throw RabbitMQException (ctx + ": missing RPC reply type");
case AMQP_RESPONSE_LIBRARY_EXCEPTION:
if (AMQP_STATUS_TIMEOUT == x.library_error) {
throw RabbitMQTimeoutException (ctx + ": Tiemout exception: " +
amqp_error_string2 (x.library_error) );
} else {
throw RabbitMQException (ctx + ": Library exception: " +
amqp_error_string2 (x.library_error) );
}
case AMQP_RESPONSE_SERVER_EXCEPTION:
switch (x.reply.id) {
case AMQP_CONNECTION_CLOSE_METHOD: {
amqp_connection_close_t *m = (amqp_connection_close_t *) x.reply.decoded;
std::string message;
gchar *error_message;
error_message =
g_strdup_printf ("%s: server connection error %d, message: %.*s\n", context,
m->reply_code, (int) m->reply_text.len, (char *) m->reply_text.bytes);
message = error_message;
g_free (error_message);
throw RabbitMQException (message);
}
case AMQP_CHANNEL_CLOSE_METHOD: {
amqp_channel_close_t *m = (amqp_channel_close_t *) x.reply.decoded;
std::string message;
gchar *error_message;
error_message = g_strdup_printf ("%s: server channel error %d, message: %.*s\n",
context, m->reply_code, (int) m->reply_text.len, (char *) m->reply_text.bytes);
message = error_message;
g_free (error_message);
throw RabbitMQException (message);
break;
}
default:
throw RabbitMQException (ctx + ": Channel Unknown Error");
break;
}
break;
}
}
static void
makeSocketLinger (int fd)
{
struct linger ling;
ling.l_onoff = 1;
ling.l_linger = 30;
if (setsockopt (fd, SOL_SOCKET, SO_LINGER, &ling, sizeof (ling) ) < 0) {
GST_WARNING ("Could not configure SO_LINGER option on RabbitMQ socket");
}
}
RabbitMQConnection::RabbitMQConnection (const std::string &address, int port) :
address (address), port (port)
{
conn = amqp_new_connection();
socket = amqp_tcp_socket_new (conn);
if (!socket) {
throw Glib::IOChannelError (Glib::IOChannelError::Code::FAILED,
"Cannot create TCP socket");
}
if (amqp_socket_open (socket, address.c_str(), port) ) {
throw Glib::IOChannelError (Glib::IOChannelError::Code::FAILED,
"Cannot open TCP socket");
}
makeSocketLinger (amqp_socket_get_sockfd (socket) );
exception_on_error (amqp_login (conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
"guest", "guest"), "Loging in");
amqp_channel_open (conn, 1);
exception_on_error (amqp_get_rpc_reply (conn), "Opening channel");
}
RabbitMQConnection::~RabbitMQConnection()
{
int fd;
if (conn == NULL) {
GST_DEBUG ("service already stopped");
return;
}
fd = amqp_socket_get_sockfd (socket);
/* Errors are ignored during close */
if (!closeOnRelease) {
/* close socket */
close (fd);
}
amqp_channel_close (conn, 1, AMQP_REPLY_SUCCESS);
amqp_connection_close (conn, AMQP_REPLY_SUCCESS);
amqp_destroy_connection (conn);
if (closeOnRelease) {
/* inform remote side that we are done */
shutdown (fd, SHUT_WR);
}
conn = NULL;
}
int
RabbitMQConnection::getFd()
{
return amqp_socket_get_sockfd (socket);
}
void RabbitMQConnection::declareQueue (const std::string &queue_name,
bool durable, int ttl)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_table_entry_t entries[1];
amqp_table_t table;
table.entries = entries;
if (ttl > 0) {
table.num_entries = 1;
entries[0].key = amqp_cstring_bytes ("x-expires");
entries[0].value.kind = AMQP_FIELD_KIND_I32;
entries[0].value.value.i32 = ttl;
} else {
table.num_entries = 0;
}
amqp_queue_declare (conn, 1,
queue, /* passive */ false, durable, /* exclusive */ false,
/* autodelete */ false, table);
exception_on_error (amqp_get_rpc_reply (conn), "Declaring queue");
}
void RabbitMQConnection::deleteQueue (const std::string &queue_name,
bool ifUnused, bool ifEmpty)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_queue_delete (conn, 1, queue, ifUnused, ifEmpty);
}
void RabbitMQConnection::declareExchange (const std::string &exchange_name,
const std::string &type, bool durable, const int ttl)
{
amqp_bytes_t exchange = amqp_cstring_bytes (exchange_name.c_str() );
amqp_bytes_t exchange_type = amqp_cstring_bytes (type.c_str() );
amqp_table_entry_t entries[1];
amqp_table_t table;
table.entries = entries;
if (ttl > 0) {
table.num_entries = 1;
entries[0].key = amqp_cstring_bytes ("x-expires");
entries[0].value.kind = AMQP_FIELD_KIND_I32;
entries[0].value.value.i32 = ttl;
} else {
table.num_entries = 0;
}
amqp_exchange_declare (conn, 1, exchange, exchange_type,
/* passive */ false, durable, table);
exception_on_error (amqp_get_rpc_reply (conn), "Declaring exchange");
}
void RabbitMQConnection::deleteExchange (const std::string &exchange_name,
bool ifUnused)
{
amqp_bytes_t exchange = amqp_cstring_bytes (exchange_name.c_str() );
amqp_exchange_delete (conn, 1, exchange, ifUnused);
}
void
RabbitMQConnection::bindQueue (const std::string &queue_name,
const std::string &exchange_name)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_bytes_t exchange = amqp_cstring_bytes (exchange_name.c_str() );
amqp_queue_bind (conn, 1, queue, exchange, amqp_empty_bytes,
amqp_empty_table);
exception_on_error (amqp_get_rpc_reply (conn), "Binding queue");
}
void
RabbitMQConnection::consumeQueue (const std::string &queue_name,
const std::string &tag)
{
amqp_bytes_t queue = amqp_cstring_bytes (queue_name.c_str() );
amqp_bytes_t tag_id = amqp_cstring_bytes (tag.c_str() );
amqp_basic_consume (conn, 1, queue, tag_id, /* no_local */ false,
/* no_ack */ false, /* exclusive */ false,
amqp_empty_table);
exception_on_error (amqp_get_rpc_reply (conn), "Consuming");
}
void
RabbitMQConnection::readMessage (struct timeval *timeout,
std::function <void (RabbitMQMessage &) > process)
{
RabbitMQMessage message (shared_from_this () );
exception_on_error (amqp_consume_message (conn, &message.envelope, timeout, 0),
"Reading message");
message.valid = true;
try {
process (message);
} catch (...) {
GST_WARNING ("Error processing message");
}
}
void
RabbitMQConnection::sendReply (const amqp_envelope_t &envelope,
const amqp_bytes_t &reply)
{
sendMessage (reply, amqp_empty_bytes, envelope.message.properties.reply_to,
envelope.message.properties.correlation_id);
}
void
RabbitMQConnection::sendMessage (const std::string &message,
const std::string &exchange, const std::string &routingKey,
const std::string &correlationID)
{
sendMessage (amqp_cstring_bytes (message.c_str() ),
amqp_cstring_bytes (exchange.c_str() ),
amqp_cstring_bytes (routingKey.c_str() ),
amqp_cstring_bytes (correlationID.c_str() ) );
}
void
RabbitMQConnection::sendMessage (const amqp_bytes_t &message,
const amqp_bytes_t &exchange, const amqp_bytes_t &routingKey,
const amqp_bytes_t &correlationID)
{
amqp_basic_properties_t props;
int ret;
props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG;
props.content_type = amqp_cstring_bytes ("text/plain");
props.delivery_mode = 2; /* persistent delivery mode */
if (correlationID.len > 0) {
props._flags |= AMQP_BASIC_CORRELATION_ID_FLAG;
props.correlation_id = correlationID;
}
ret = amqp_basic_publish (conn, 1, exchange,
routingKey, /* mandatory */ false, /* inmediate */ false, &props, message);
if (ret != AMQP_STATUS_OK) {
GST_ERROR ("Error ret value: %d", ret);
}
}
RabbitMQMessage::RabbitMQMessage (std::shared_ptr <RabbitMQConnection>
connection) : connection (connection)
{
}
RabbitMQMessage::~RabbitMQMessage()
{
if (!acked && valid) {
GST_WARNING ("Rejecting message because it is not acked");
amqp_basic_reject (connection->conn, 1,
envelope.delivery_tag, /* requeue */ true);
}
amqp_destroy_envelope (&envelope);
}
void
RabbitMQMessage::reply (std::shared_ptr< RabbitMQConnection > conn,
const std::string &response)
{
conn->sendReply (envelope, amqp_cstring_bytes (response.c_str() ) );
}
void
RabbitMQMessage::reply (const std::string &response)
{
reply (connection, response);
}
std::string
RabbitMQMessage::getData()
{
std::string data (reinterpret_cast<char const *>
(envelope.message.body.bytes), envelope.message.body.len );
return data;
}
void
RabbitMQMessage::ack()
{
amqp_basic_ack (connection->conn, 1,
envelope.delivery_tag, /* multiple */ false);
acked = true;
}
RabbitMQConnection::StaticConstructor RabbitMQConnection::staticConstructor;
RabbitMQConnection::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
const std::string RabbitMQConnection::EXCHANGE_TYPE_DIRECT ("direct");
const std::string RabbitMQConnection::EXCHANGE_TYPE_FANOUT ("fanout");
const std::string RabbitMQConnection::EXCHANGE_TYPE_TOPIC ("topic");
} /* kurento */
<|endoftext|> |
<commit_before>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include "PointerDetectorFilter.hpp"
#include "KmsMediaPointerDetectorFilterType_constants.h"
#include "utils/utils.hpp"
#include "utils/marshalling.hpp"
#include "KmsMediaDataType_constants.h"
#include "KmsMediaErrorCodes_constants.h"
#include "protocol/TBinaryProtocol.h"
#include "transport/TBufferTransports.h"
#define GST_CAT_DEFAULT kurento_pointer_detector_filter
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoPointerDetectorFilter"
#define WINDOWS_LAYOUT "windows-layout"
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;
namespace kurento
{
void
pointerDetector_receive_message (GstBus *bus, GstMessage *message, gpointer pointerDetector)
{
const GstStructure *st;
gchar *windowID;
const gchar *type;
std::string windowIDStr, typeStr;
PointerDetectorFilter *filter = (PointerDetectorFilter *) pointerDetector;
if (GST_MESSAGE_SRC (message) != GST_OBJECT (filter->pointerDetector) ||
GST_MESSAGE_TYPE (message) != GST_MESSAGE_ELEMENT)
return;
st = gst_message_get_structure (message);
type = gst_structure_get_name (st);
if ( (g_strcmp0 (type, "window-out") != 0) &&
(g_strcmp0 (type, "window-in") != 0) ) {
GST_WARNING ("The message does not have the correct name");
return;
}
if (!gst_structure_get (st, "window", G_TYPE_STRING , &windowID, NULL) ) {
GST_WARNING ("The message does not contain the window ID");
return;
}
windowIDStr = windowID;
typeStr = type;
g_free (windowID);
filter->raiseEvent (typeStr, windowIDStr);
}
/* default constructor */
PointerDetectorFilter::PointerDetectorFilter (
MediaSet &mediaSet, std::shared_ptr<MediaPipeline> parent,
const std::map<std::string, KmsMediaParam> ¶ms)
: Filter (mediaSet, parent, g_KmsMediaPointerDetectorFilterType_constants.TYPE_NAME, params)
{
const KmsMediaParam *p;
KmsMediaPointerDetectorWindowSet windowSet;
element = gst_element_factory_make ("filterelement", NULL);
g_object_set (element, "filter-factory", "pointerdetector", NULL);
g_object_ref (element);
gst_bin_add (GST_BIN (parent->pipeline), element);
gst_element_sync_state_with_parent (element);
GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (parent->pipeline) );
GstElement *pointerDetector;
g_object_get (G_OBJECT (element), "filter", &pointerDetector, NULL);
this->pointerDetector = pointerDetector;
p = getParam (params,
g_KmsMediaPointerDetectorFilterType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE);
if (p != NULL) {
GstStructure *buttonsLayout;
//there are data about windows
unmarshalStruct (windowSet, p->data);
/* set the window layout list */
buttonsLayout = gst_structure_new_empty ("windowsLayout");
for (auto it = windowSet.windows.begin(); it != windowSet.windows.end(); ++it) {
KmsMediaPointerDetectorWindow windowInfo = *it;
GstStructure *buttonsLayoutAux;
buttonsLayoutAux = gst_structure_new (
windowInfo.id.c_str(),
"upRightCornerX", G_TYPE_INT, windowInfo.topRightCornerX,
"upRightCornerY", G_TYPE_INT, windowInfo.topRightCornerY,
"width", G_TYPE_INT, windowInfo.width,
"height", G_TYPE_INT, windowInfo.height,
"id", G_TYPE_STRING, windowInfo.id.c_str(),
NULL);
gst_structure_set (buttonsLayout,
windowInfo.id.c_str(), GST_TYPE_STRUCTURE, buttonsLayoutAux,
NULL);
gst_structure_free (buttonsLayoutAux);
}
g_object_set (G_OBJECT (this->pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
}
windowSet.windows.clear();
bus_handler_id = g_signal_connect (bus, "message", G_CALLBACK (pointerDetector_receive_message), this);
g_object_unref (bus);
// There is no need to reference pointerdetector because its life cycle is the same as the filter life cycle
g_object_unref (pointerDetector);
}
PointerDetectorFilter::~PointerDetectorFilter() throw ()
{
GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE ( ( (std::shared_ptr<MediaPipeline> &) parent)->pipeline) );
g_signal_handler_disconnect (bus, bus_handler_id);
g_object_unref (bus);
gst_bin_remove (GST_BIN ( ( (std::shared_ptr<MediaPipeline> &) parent)->pipeline), element);
gst_element_set_state (element, GST_STATE_NULL);
g_object_unref (element);
}
void
PointerDetectorFilter::raiseEvent (const std::string &type, const std::string &windowID)
{
KmsMediaEventData eventData;
createStringEventData (eventData, windowID);
if ( type.compare ("window-out") == 0) {
GST_DEBUG ("Raise event. Type: %s, Window ID: %s", type.c_str(),
windowID.c_str() );
sendEvent (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_OUT, eventData);
} else {
GST_DEBUG ("Raise event. Type: %s, Window ID: %s", type.c_str(),
windowID.c_str() );
sendEvent (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_IN, eventData);
}
}
void
PointerDetectorFilter::addWindow (KmsMediaPointerDetectorWindow window)
{
GstStructure *buttonsLayout, *buttonsLayoutAux;
buttonsLayoutAux = gst_structure_new (
window.id.c_str(),
"upRightCornerX", G_TYPE_INT, window.topRightCornerX,
"upRightCornerY", G_TYPE_INT, window.topRightCornerY,
"width", G_TYPE_INT, window.width,
"height", G_TYPE_INT, window.height,
"id", G_TYPE_STRING, window.id.c_str(),
NULL);
/* The function obtains the actual window list */
g_object_get (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, &buttonsLayout, NULL);
gst_structure_set (buttonsLayout,
window.id.c_str(), GST_TYPE_STRUCTURE, buttonsLayoutAux,
NULL);
g_object_set (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
gst_structure_free (buttonsLayoutAux);
}
void
PointerDetectorFilter::removeWindow (std::string id)
{
GstStructure *buttonsLayout;
gint len;
/* The function obtains the actual window list */
g_object_get (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, &buttonsLayout, NULL);
len = gst_structure_n_fields (buttonsLayout);
if (len == 0) {
GST_WARNING ("There are no windows in the layout");
return;
}
for (int i = 0; i < len; i++) {
const gchar *name;
name = gst_structure_nth_field_name (buttonsLayout, i);
if ( g_strcmp0 (name, id.c_str() ) == 0) {
/* this window will be removed */
gst_structure_remove_field (buttonsLayout, name);
}
}
/* Set the buttons layout list without the window with id = id */
g_object_set (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
}
void
PointerDetectorFilter::clearWindows()
{
GstStructure *buttonsLayout;
buttonsLayout = gst_structure_new_empty ("buttonsLayout");
g_object_set (G_OBJECT (this->pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
}
void
PointerDetectorFilter::invoke (KmsMediaInvocationReturn &_return,
const std::string &command,
const std::map< std::string, KmsMediaParam > ¶ms)
throw (KmsMediaServerException)
{
if (g_KmsMediaPointerDetectorFilterType_constants.ADD_NEW_WINDOW.compare (command) == 0) {
KmsMediaPointerDetectorWindow windowInfo;
const KmsMediaParam *p;
/* extract window params from param */
p = getParam (params,
g_KmsMediaPointerDetectorFilterType_constants.ADD_NEW_WINDOW_PARAM_WINDOW);
if (p != NULL) {
unmarshalStruct (windowInfo, p->data);
/* create window */
addWindow (windowInfo);
}
} else if (g_KmsMediaPointerDetectorFilterType_constants.REMOVE_WINDOW.compare (command) == 0) {
std::string id;
getStringParam (id, params, g_KmsMediaPointerDetectorFilterType_constants.REMOVE_WINDOW_PARAM_WINDOW_ID);
removeWindow (id);
} else if (g_KmsMediaPointerDetectorFilterType_constants.CLEAR_WINDOWS.compare (command) == 0) {
clearWindows();
}
}
void
PointerDetectorFilter::subscribe (std::string &_return, const std::string &eventType,
const std::string &handlerAddress,
const int32_t handlerPort)
throw (KmsMediaServerException)
{
if (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_IN == eventType)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress, handlerPort);
else if (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_OUT == eventType)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress, handlerPort);
else
Filter::subscribe (_return, eventType, handlerAddress, handlerPort);
}
PointerDetectorFilter::StaticConstructor PointerDetectorFilter::staticConstructor;
PointerDetectorFilter::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} // kurento
<commit_msg>pointerDetector: Add exception if the filter has not been created<commit_after>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include "PointerDetectorFilter.hpp"
#include "KmsMediaPointerDetectorFilterType_constants.h"
#include "utils/utils.hpp"
#include "utils/marshalling.hpp"
#include "KmsMediaDataType_constants.h"
#include "KmsMediaErrorCodes_constants.h"
#include "protocol/TBinaryProtocol.h"
#include "transport/TBufferTransports.h"
#define GST_CAT_DEFAULT kurento_pointer_detector_filter
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoPointerDetectorFilter"
#define WINDOWS_LAYOUT "windows-layout"
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::protocol::TBinaryProtocol;
namespace kurento
{
void
pointerDetector_receive_message (GstBus *bus, GstMessage *message, gpointer pointerDetector)
{
const GstStructure *st;
gchar *windowID;
const gchar *type;
std::string windowIDStr, typeStr;
PointerDetectorFilter *filter = (PointerDetectorFilter *) pointerDetector;
if (GST_MESSAGE_SRC (message) != GST_OBJECT (filter->pointerDetector) ||
GST_MESSAGE_TYPE (message) != GST_MESSAGE_ELEMENT)
return;
st = gst_message_get_structure (message);
type = gst_structure_get_name (st);
if ( (g_strcmp0 (type, "window-out") != 0) &&
(g_strcmp0 (type, "window-in") != 0) ) {
GST_WARNING ("The message does not have the correct name");
return;
}
if (!gst_structure_get (st, "window", G_TYPE_STRING , &windowID, NULL) ) {
GST_WARNING ("The message does not contain the window ID");
return;
}
windowIDStr = windowID;
typeStr = type;
g_free (windowID);
filter->raiseEvent (typeStr, windowIDStr);
}
/* default constructor */
PointerDetectorFilter::PointerDetectorFilter (
MediaSet &mediaSet, std::shared_ptr<MediaPipeline> parent,
const std::map<std::string, KmsMediaParam> ¶ms)
: Filter (mediaSet, parent, g_KmsMediaPointerDetectorFilterType_constants.TYPE_NAME, params)
{
const KmsMediaParam *p;
KmsMediaPointerDetectorWindowSet windowSet;
element = gst_element_factory_make ("filterelement", NULL);
g_object_set (element, "filter-factory", "pointerdetector", NULL);
g_object_ref (element);
gst_bin_add (GST_BIN (parent->pipeline), element);
gst_element_sync_state_with_parent (element);
GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (parent->pipeline) );
GstElement *pointerDetector;
g_object_get (G_OBJECT (element), "filter", &pointerDetector, NULL);
this->pointerDetector = pointerDetector;
if (this->pointerDetector == NULL) {
g_object_unref (bus);
KmsMediaServerException except;
createKmsMediaServerException (except,
g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_NOT_AVAILAIBLE,
"Media Object not available");
throw except;
}
p = getParam (params,
g_KmsMediaPointerDetectorFilterType_constants.CONSTRUCTOR_PARAMS_DATA_TYPE);
if (p != NULL) {
GstStructure *buttonsLayout;
//there are data about windows
unmarshalStruct (windowSet, p->data);
/* set the window layout list */
buttonsLayout = gst_structure_new_empty ("windowsLayout");
for (auto it = windowSet.windows.begin(); it != windowSet.windows.end(); ++it) {
KmsMediaPointerDetectorWindow windowInfo = *it;
GstStructure *buttonsLayoutAux;
buttonsLayoutAux = gst_structure_new (
windowInfo.id.c_str(),
"upRightCornerX", G_TYPE_INT, windowInfo.topRightCornerX,
"upRightCornerY", G_TYPE_INT, windowInfo.topRightCornerY,
"width", G_TYPE_INT, windowInfo.width,
"height", G_TYPE_INT, windowInfo.height,
"id", G_TYPE_STRING, windowInfo.id.c_str(),
NULL);
gst_structure_set (buttonsLayout,
windowInfo.id.c_str(), GST_TYPE_STRUCTURE, buttonsLayoutAux,
NULL);
gst_structure_free (buttonsLayoutAux);
}
g_object_set (G_OBJECT (this->pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
}
windowSet.windows.clear();
bus_handler_id = g_signal_connect (bus, "message", G_CALLBACK (pointerDetector_receive_message), this);
g_object_unref (bus);
// There is no need to reference pointerdetector because its life cycle is the same as the filter life cycle
g_object_unref (pointerDetector);
}
PointerDetectorFilter::~PointerDetectorFilter() throw ()
{
GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE ( ( (std::shared_ptr<MediaPipeline> &) parent)->pipeline) );
g_signal_handler_disconnect (bus, bus_handler_id);
g_object_unref (bus);
gst_bin_remove (GST_BIN ( ( (std::shared_ptr<MediaPipeline> &) parent)->pipeline), element);
gst_element_set_state (element, GST_STATE_NULL);
g_object_unref (element);
}
void
PointerDetectorFilter::raiseEvent (const std::string &type, const std::string &windowID)
{
KmsMediaEventData eventData;
createStringEventData (eventData, windowID);
if ( type.compare ("window-out") == 0) {
GST_DEBUG ("Raise event. Type: %s, Window ID: %s", type.c_str(),
windowID.c_str() );
sendEvent (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_OUT, eventData);
} else {
GST_DEBUG ("Raise event. Type: %s, Window ID: %s", type.c_str(),
windowID.c_str() );
sendEvent (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_IN, eventData);
}
}
void
PointerDetectorFilter::addWindow (KmsMediaPointerDetectorWindow window)
{
GstStructure *buttonsLayout, *buttonsLayoutAux;
buttonsLayoutAux = gst_structure_new (
window.id.c_str(),
"upRightCornerX", G_TYPE_INT, window.topRightCornerX,
"upRightCornerY", G_TYPE_INT, window.topRightCornerY,
"width", G_TYPE_INT, window.width,
"height", G_TYPE_INT, window.height,
"id", G_TYPE_STRING, window.id.c_str(),
NULL);
/* The function obtains the actual window list */
g_object_get (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, &buttonsLayout, NULL);
gst_structure_set (buttonsLayout,
window.id.c_str(), GST_TYPE_STRUCTURE, buttonsLayoutAux,
NULL);
g_object_set (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
gst_structure_free (buttonsLayoutAux);
}
void
PointerDetectorFilter::removeWindow (std::string id)
{
GstStructure *buttonsLayout;
gint len;
/* The function obtains the actual window list */
g_object_get (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, &buttonsLayout, NULL);
len = gst_structure_n_fields (buttonsLayout);
if (len == 0) {
GST_WARNING ("There are no windows in the layout");
return;
}
for (int i = 0; i < len; i++) {
const gchar *name;
name = gst_structure_nth_field_name (buttonsLayout, i);
if ( g_strcmp0 (name, id.c_str() ) == 0) {
/* this window will be removed */
gst_structure_remove_field (buttonsLayout, name);
}
}
/* Set the buttons layout list without the window with id = id */
g_object_set (G_OBJECT (pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
}
void
PointerDetectorFilter::clearWindows()
{
GstStructure *buttonsLayout;
buttonsLayout = gst_structure_new_empty ("buttonsLayout");
g_object_set (G_OBJECT (this->pointerDetector), WINDOWS_LAYOUT, buttonsLayout, NULL);
gst_structure_free (buttonsLayout);
}
void
PointerDetectorFilter::invoke (KmsMediaInvocationReturn &_return,
const std::string &command,
const std::map< std::string, KmsMediaParam > ¶ms)
throw (KmsMediaServerException)
{
if (g_KmsMediaPointerDetectorFilterType_constants.ADD_NEW_WINDOW.compare (command) == 0) {
KmsMediaPointerDetectorWindow windowInfo;
const KmsMediaParam *p;
/* extract window params from param */
p = getParam (params,
g_KmsMediaPointerDetectorFilterType_constants.ADD_NEW_WINDOW_PARAM_WINDOW);
if (p != NULL) {
unmarshalStruct (windowInfo, p->data);
/* create window */
addWindow (windowInfo);
}
} else if (g_KmsMediaPointerDetectorFilterType_constants.REMOVE_WINDOW.compare (command) == 0) {
std::string id;
getStringParam (id, params, g_KmsMediaPointerDetectorFilterType_constants.REMOVE_WINDOW_PARAM_WINDOW_ID);
removeWindow (id);
} else if (g_KmsMediaPointerDetectorFilterType_constants.CLEAR_WINDOWS.compare (command) == 0) {
clearWindows();
}
}
void
PointerDetectorFilter::subscribe (std::string &_return, const std::string &eventType,
const std::string &handlerAddress,
const int32_t handlerPort)
throw (KmsMediaServerException)
{
if (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_IN == eventType)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress, handlerPort);
else if (g_KmsMediaPointerDetectorFilterType_constants.EVENT_WINDOW_OUT == eventType)
mediaHandlerManager.addMediaHandler (_return, eventType, handlerAddress, handlerPort);
else
Filter::subscribe (_return, eventType, handlerAddress, handlerPort);
}
PointerDetectorFilter::StaticConstructor PointerDetectorFilter::staticConstructor;
PointerDetectorFilter::StaticConstructor::StaticConstructor()
{
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} // kurento
<|endoftext|> |
<commit_before>#include <other/core/python/config.h> // Must be included first
#ifdef USE_OPENEXR
#include <OpenEXR/ImfRgbaFile.h>
#include <OpenEXR/ImfArray.h>
#endif
#include <other/core/image/ExrFile.h>
#include <other/core/image/Image.h>
#include <other/core/array/Array2d.h>
#include <other/core/vector/Vector3d.h>
#include <other/core/utility/Log.h>
namespace other {
#ifndef USE_OPENEXR
template<class T> Array<Vector<T,3>,2> ExrFile<T>::
read(const std::string& filename)
{
OTHER_FATAL_ERROR("Not compiled with USE_OPENEXR. Cannot read exr image.");
}
template<class T> void ExrFile<T>::
write(const std::string& filename,RawArray<const Vector<T,3>,2> image)
{
OTHER_FATAL_ERROR("Not compiled with USE_OPENEXR. Cannot write exr image.");
}
template<class T> bool ExrFile<T>::
is_supported()
{return false;}
#else
using namespace Imf;
template<class T>
Imf::Rgba to_rgba(Vector<T,3> const &v) {
Imf::Rgba rgba;
rgba.r = (float)v.x;
rgba.g = (float)v.y;
rgba.b = (float)v.z;
rgba.a = 1;
return rgba;
}
template<>
Imf::Rgba to_rgba(Vector<unsigned char,3> const &v) {
Imf::Rgba rgba;
rgba.r = v.x/255;
rgba.g = v.y/255;
rgba.b = v.z/255;
rgba.a = 1;
return rgba;
}
template<class T>
Vector<T,3> from_rgba(Imf::Rgba const &rgba) {
return Vector<T,3>(rgba.r,rgba.g,rgba.b);
}
template<>
Vector<unsigned char,3> from_rgba(Imf::Rgba const &rgba) {
return Vector<unsigned char,3>(vec(255*rgba.r,255*rgba.g,255*rgba.b));
}
template<class T> Array<Vector<T,3>,2> ExrFile<T>::
read(const std::string& filename)
{
Imf::RgbaInputFile file(filename.c_str());
Imath::Box2i dw = file.dataWindow();
int width = dw.max.x - dw.min.x + 1;
int height = dw.max.y - dw.min.y + 1;
Imf::Array2D<Imf::Rgba> pixels;
pixels.resizeErase(height, width);
file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * width, 1, width);
file.readPixels(dw.min.y, dw.max.y);
Array<Vector<T,3>,2> image(width, height);
for (int i = 0; i < image.m; ++i) {
for (int j = 0; j < image.n; ++j) {
image(i,j) = from_rgba<T>(pixels[j][i]);
}
}
return image;
}
template<class T> void ExrFile<T>::
write(const std::string& filename, RawArray<const Vector<T,3>,2> image)
{
// convert to array of EXRPixels
Imf::Rgba *pixels = new Imf::Rgba[image.total_size()];
for (int i = 0; i < image.m; ++i) {
for (int j = 0; j < image.n; ++j) {
pixels[j*image.m+i] = to_rgba(image(i,j));
}
}
Imf::RgbaOutputFile file(filename.c_str(), image.m, image.n, Imf::WRITE_RGBA);
file.setFrameBuffer(pixels, 1, image.m);
file.writePixels(image.n);
delete[] pixels;
}
template<class T> bool ExrFile<T>::
is_supported()
{
return true;
}
#endif
template class ExrFile<float>;
template class ExrFile<double>;
template class ExrFile<unsigned char>;
}
<commit_msg>ExrFile: Fix accidental integer division<commit_after>#include <other/core/python/config.h> // Must be included first
#ifdef USE_OPENEXR
#include <OpenEXR/ImfRgbaFile.h>
#include <OpenEXR/ImfArray.h>
#endif
#include <other/core/image/ExrFile.h>
#include <other/core/image/Image.h>
#include <other/core/array/Array2d.h>
#include <other/core/vector/Vector3d.h>
#include <other/core/utility/Log.h>
namespace other {
#ifndef USE_OPENEXR
template<class T> Array<Vector<T,3>,2> ExrFile<T>::
read(const std::string& filename)
{
OTHER_FATAL_ERROR("Not compiled with USE_OPENEXR. Cannot read exr image.");
}
template<class T> void ExrFile<T>::
write(const std::string& filename,RawArray<const Vector<T,3>,2> image)
{
OTHER_FATAL_ERROR("Not compiled with USE_OPENEXR. Cannot write exr image.");
}
template<class T> bool ExrFile<T>::
is_supported()
{return false;}
#else
using namespace Imf;
template<class T>
Imf::Rgba to_rgba(Vector<T,3> const &v) {
Imf::Rgba rgba;
rgba.r = (float)v.x;
rgba.g = (float)v.y;
rgba.b = (float)v.z;
rgba.a = 1;
return rgba;
}
template<>
Imf::Rgba to_rgba(Vector<unsigned char,3> const &v) {
Imf::Rgba rgba;
rgba.r = (float)1./255*v.x;
rgba.g = (float)1./255*v.y;
rgba.b = (float)1./255*v.z;
rgba.a = 1;
return rgba;
}
template<class T>
Vector<T,3> from_rgba(Imf::Rgba const &rgba) {
return Vector<T,3>(rgba.r,rgba.g,rgba.b);
}
template<>
Vector<unsigned char,3> from_rgba(Imf::Rgba const &rgba) {
return Vector<unsigned char,3>(vec(255*rgba.r,255*rgba.g,255*rgba.b));
}
template<class T> Array<Vector<T,3>,2> ExrFile<T>::
read(const std::string& filename)
{
Imf::RgbaInputFile file(filename.c_str());
Imath::Box2i dw = file.dataWindow();
int width = dw.max.x - dw.min.x + 1;
int height = dw.max.y - dw.min.y + 1;
Imf::Array2D<Imf::Rgba> pixels;
pixels.resizeErase(height, width);
file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y * width, 1, width);
file.readPixels(dw.min.y, dw.max.y);
Array<Vector<T,3>,2> image(width, height);
for (int i = 0; i < image.m; ++i) {
for (int j = 0; j < image.n; ++j) {
image(i,j) = from_rgba<T>(pixels[j][i]);
}
}
return image;
}
template<class T> void ExrFile<T>::
write(const std::string& filename, RawArray<const Vector<T,3>,2> image)
{
// convert to array of EXRPixels
Imf::Rgba *pixels = new Imf::Rgba[image.total_size()];
for (int i = 0; i < image.m; ++i) {
for (int j = 0; j < image.n; ++j) {
pixels[j*image.m+i] = to_rgba(image(i,j));
}
}
Imf::RgbaOutputFile file(filename.c_str(), image.m, image.n, Imf::WRITE_RGBA);
file.setFrameBuffer(pixels, 1, image.m);
file.writePixels(image.n);
delete[] pixels;
}
template<class T> bool ExrFile<T>::
is_supported()
{
return true;
}
#endif
template class ExrFile<float>;
template class ExrFile<double>;
template class ExrFile<unsigned char>;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.