<commit_before>#include <node/v8.h>
#include <node/node.h>
#include <string>
#include <stdexcept>

#include "async_player.h"
#include "../action/action.h"
#include "../action/card.h"
#include "../game/async_game.h"
#include "../event/event.h"

namespace Uno { namespace Player {

using namespace v8;
using ::Uno::Game::AsyncGame;
using ::Uno::Player::Player;
using ::Uno::Action::Action;
//Card, CARD_COLOR/VALUE
using namespace ::Uno::Action;
namespace Event = ::Uno::Event;

#define REQ_INT_ARG(I)                                                  \
    if (args.Length() <= (I) || !args[I]->IsInt32()) {                  \
        return ThrowException(Exception::TypeError(                     \
            String::New("Argument " #I " must be an integer")));        \
    }

#define REQ_OBJ_ARG(I)                                                  \
    if (args.Length() <= (I) || !args[I]->IsObject()) {                 \
        return ThrowException(Exception::TypeError(                     \
            String::New("Argument " #I " must be an object")));         \
    }

AsyncPlayer::AsyncPlayer(Handle<Object> jsplayer) {
	HandleScope scope;
	session_id = *String::AsciiValue(jsplayer->Get(String::New("session_id"))->ToString());
	this->jsplayer = Persistent<Object>::New(jsplayer);
}

void AsyncPlayer::setGame(AsyncGame* game) {
	this->game = game;
}

Local<Function> AsyncPlayer::getCallback(const char* cbname) {
	HandleScope scope;
	Local<Function> cb = Local<Function>::Cast(
		jsplayer->Get(String::New(cbname))
	);

	if (!cb->IsFunction()) {
		std::string error("callback not found: ");
		error.append(cbname);
		throw std::invalid_argument(error.c_str());
	}

	return scope.Close(cb);
}

void AsyncPlayer::addCard(Card *card) {
	Player::addCard(card);

	Handle<Value> argument = createCardObject(card);

	Local<Function> addaction_cb = getCallback("addAction");
	TryCatch try_catch;
	addaction_cb->Call(Context::GetCurrent()->Global(), 1, &argument);
	if (try_catch.HasCaught()) {
		node::FatalException(try_catch);
	}
}

void AsyncPlayer::playCard(const Arguments &args) {
	HandleScope scope;

    if (args.Length() <= 0 || !args[0]->IsObject()) {
        throw std::invalid_argument("Argument 0 must be an object");
    }

	Local<Object> picked_card = args[0]->ToObject();

	Local<String> key_color = String::NewSymbol("color");
	Local<String> key_value = String::NewSymbol("value");

	if (picked_card->Has(key_color) == false) {
		throw std::invalid_argument("Malformed card object, no color property.");
	}

	if (picked_card->Has(key_value) == false) {
		throw std::invalid_argument("Malformed card object, no value property.");
	}

	Local<Value> property_color = picked_card->Get(key_color);
	if (property_color->IsString() == false) {
		throw std::invalid_argument("Card color must be string.");
	}

	Local<Value> property_value = picked_card->Get(key_value);
	if (property_value->IsString() == false) {
		throw std::invalid_argument("Card value must be string.");
	}

	CARD_COLOR picked_color;
	try {
		picked_color = Card::stringToColor(
			*String::AsciiValue(property_color->ToString())
		);
	} catch (std::invalid_argument &e) {
		throw;
	}

	CARD_VALUE picked_value;
	try {
		picked_value = Card::stringToValue(
			*String::AsciiValue(property_value->ToString())
		);
	} catch (std::invalid_argument &e) {
		throw;
	}

	card_iterator card;
	for (card = hand.begin(); card < hand.end(); card++) {

		// same color and value
		if ((*card)->getColor() == picked_color
		&&  (*card)->getValue() == picked_value
		) {
			try {
				game->takeAction(this, *card);
			} catch (std::invalid_argument &message) {
				throw std::domain_error(message.what());
			}
		}
	}

}

void AsyncPlayer::draw() {
	try {
		game->takeDraw(this);
	} catch (std::invalid_argument &message) {
		throw;
	}
}

Local<Object> AsyncPlayer::createCardObject(Card* card) {
	HandleScope scope;
	Local<Object> jscard = Object::New();

	// set color
	const char* color = NULL;

	switch (card->getColor()) {
	case CARD_COLOR_RED:
		color = "red";
		break;
	case CARD_COLOR_GREEN:
		color = "green";
		break;
	case CARD_COLOR_BLUE:
		color = "blue";
		break;
	case CARD_COLOR_YELLOW:
		color = "yellow";
		break;
	case CARD_COLOR_BLACK:
		color = "black";
		break;
	default:
		color = "?";
		break;
	}

	jscard->Set(
		String::New("color"),
		String::NewSymbol(color)
	);

	// set value
	const char* value = NULL;
#define CASE_CARD_VALUE(V,O) 	\
	case CARD_VALUE_##V: 		\
		value = O; 				\
		break;

	switch (card->getValue()) {
		CASE_CARD_VALUE(0,"0");
		CASE_CARD_VALUE(1,"1");
		CASE_CARD_VALUE(2,"2");
		CASE_CARD_VALUE(3,"3");
		CASE_CARD_VALUE(4,"4");
		CASE_CARD_VALUE(5,"5");
		CASE_CARD_VALUE(6,"6");
		CASE_CARD_VALUE(7,"7");
		CASE_CARD_VALUE(8,"8");
		CASE_CARD_VALUE(9,"9");
		CASE_CARD_VALUE(BLOCK, "block");
		CASE_CARD_VALUE(REVERSE, "reverse");
		CASE_CARD_VALUE(PLUSTWO, "+2");
		CASE_CARD_VALUE(COLORPICK, "colorpicker");
		CASE_CARD_VALUE(PLUSFOUR, "+4");

		default:
			value = "?";
			break;
	}

#undef CASE_CARD_VALUE

	jscard->Set(
		String::New("value"),
		String::NewSymbol(value)
	);

	return scope.Close(jscard);
}

Local<Object> AsyncPlayer::createPlayerObject(Player* player) {
	HandleScope scope;
	Local<Object> jsplayer = Object::New();

	jsplayer->Set(
		String::NewSymbol("name"),
		String::New(player->getName().c_str())
	);

	return scope.Close(jsplayer);
}

void AsyncPlayer::notify(Event::EVENT event_type, void* event) {
	HandleScope scope;

	Local<Object> jsevent = Object::New();
	const char* jstype = "";

	switch (event_type) {
	case Event::EVENT_GAME_START:
	{
		jstype = "game_start";

		jsevent->Set(
			String::NewSymbol("first_card"),
			createCardObject(
				reinterpret_cast<Event::game_start*>(event)->first_card
			)
		);
	}
		break;
	case Event::EVENT_CARD_PLAYED:
	{
		jstype = "card_played";

		Event::card_played* e = reinterpret_cast<Event::card_played*>(event);
		jsevent->Set(
			String::NewSymbol("played_by"),
			createPlayerObject(e->played_by)
		);

		jsevent->Set(
			String::NewSymbol("played_card"),
			createCardObject(e->played_card)
		);
	}
		break;

	case Event::EVENT_GAME_END:
	{
		jstype = "game_end";

		Event::game_end* e = reinterpret_cast<Event::game_end*>(event);
		jsevent->Set(
			String::NewSymbol("winner"),
			createPlayerObject(e->winner)
		);
	}
		break;

	case Event::EVENT_COLORPICK:
	{
		jstype = "colorpick";

		Event::colorpick* e = reinterpret_cast<Event::colorpick*>(event);

		jsevent->Set(
			String::NewSymbol("picked_by"),
			createPlayerObject(e->picked_by)
		);

		const char* color;
		switch (e->color) {
		case CARD_COLOR_RED:
			color = "red";
			break;
		case CARD_COLOR_GREEN:
			color = "green";
			break;
		case CARD_COLOR_BLUE:
			color = "blue";
			break;
		case CARD_COLOR_YELLOW:
			color = "yellow";
			break;
		default:
			color = "?";
			break;
		}

		jsevent->Set(
			String::NewSymbol("color"),
			String::NewSymbol(color)
		);
	}
		break;

	case Event::EVENT_DRAW_CARD:
	{
		jstype = "draw_card";

		Event::draw_card* e = reinterpret_cast<Event::draw_card*>(event);

		jsevent->Set(
			String::NewSymbol("player"),
			createPlayerObject(e->player)
		);

		jsevent->Set(
			String::NewSymbol("card_count"),
			Int32::New(e->card_count)
		);

		break;
	}

	case Event::EVENT_GETS_BLOCKED:
	{
		jstype = "gets_blocked";
		Event::gets_blocked* e = reinterpret_cast<Event::gets_blocked*>(event);

		jsevent->Set(
			String::NewSymbol("gets_blocked"),
			createPlayerObject(e->gets_blocked)
		);

		jsevent->Set(
			String::NewSymbol("blocked_by"),
			createPlayerObject(e->blocked_by)
		);

		break;
	}

	case Event::EVENT_UNO_SAID:
	{
		jstype = "uno_said";
		Event::uno_said* e = reinterpret_cast<Event::uno_said*>(event);

		jsevent->Set(
			String::NewSymbol("said_by"),
			createPlayerObject(e->said_by)
		);

		const char* type = "";
		switch (e->type) {
		case Event::uno_said::GOOD:
			type = "good";
			break;
		case Event::uno_said::BAD:
			type = "bad";
			break;
		case Event::uno_said::FORGOTTEN:
			type = "forgotten";
			break;
		}

		jsevent->Set(
			String::NewSymbol("type"),
			String::NewSymbol(type)
		);

		break;
	}

	case Event::EVENT_PLAYER_JOINED:
	{
		jstype = "player_joined";
		Event::player_joined* e = reinterpret_cast<Event::player_joined*>(event);

		jsevent->Set(
			String::NewSymbol("player"),
			createPlayerObject(e->player)
		);

		break;
	}

	case Event::EVENT_PLAYERS_TURN:
	{
		jstype = "players_turn";
		Event::players_turn* e = reinterpret_cast<Event::players_turn*>(event);

		jsevent->Set(
			String::NewSymbol("player"),
			createPlayerObject(e->player)
		);
		break;
	}

	default:
		/**
		 * @todo fix typo: unknown.
		 */
		jstype = "unknow_event";
		break;

	}

	jsevent->Set(
			String::NewSymbol("event_type"),
			String::New(jstype)
	);

	Handle<Value> argument = jsevent;

	{   // call notify_cb
		Local<Function> notify_cb = getCallback("notify");
		TryCatch try_catch;
		notify_cb->Call(Context::GetCurrent()->Global(), 1, &argument);
		if (try_catch.HasCaught()) {
			node::FatalException(try_catch);
		}
	}
}

#undef REQ_INT_ARG

}} //namespace
<commit_msg>AsyncPlayer uses Card:: color/value <-> string mapper methods<commit_after>#include <node/v8.h>
#include <node/node.h>
#include <string>
#include <stdexcept>

#include "async_player.h"
#include "../action/action.h"
#include "../action/card.h"
#include "../game/async_game.h"
#include "../event/event.h"

namespace Uno { namespace Player {

using namespace v8;
using ::Uno::Game::AsyncGame;
using ::Uno::Player::Player;
using ::Uno::Action::Action;
//Card, CARD_COLOR/VALUE
using namespace ::Uno::Action;
namespace Event = ::Uno::Event;

#define REQ_INT_ARG(I)                                                  \
    if (args.Length() <= (I) || !args[I]->IsInt32()) {                  \
        return ThrowException(Exception::TypeError(                     \
            String::New("Argument " #I " must be an integer")));        \
    }

#define REQ_OBJ_ARG(I)                                                  \
    if (args.Length() <= (I) || !args[I]->IsObject()) {                 \
        return ThrowException(Exception::TypeError(                     \
            String::New("Argument " #I " must be an object")));         \
    }

AsyncPlayer::AsyncPlayer(Handle<Object> jsplayer) {
	HandleScope scope;
	session_id = *String::AsciiValue(jsplayer->Get(String::New("session_id"))->ToString());
	this->jsplayer = Persistent<Object>::New(jsplayer);
}

void AsyncPlayer::setGame(AsyncGame* game) {
	this->game = game;
}

Local<Function> AsyncPlayer::getCallback(const char* cbname) {
	HandleScope scope;
	Local<Function> cb = Local<Function>::Cast(
		jsplayer->Get(String::New(cbname))
	);

	if (!cb->IsFunction()) {
		std::string error("callback not found: ");
		error.append(cbname);
		throw std::invalid_argument(error.c_str());
	}

	return scope.Close(cb);
}

void AsyncPlayer::addCard(Card *card) {
	Player::addCard(card);

	Handle<Value> argument = createCardObject(card);

	Local<Function> addaction_cb = getCallback("addAction");
	TryCatch try_catch;
	addaction_cb->Call(Context::GetCurrent()->Global(), 1, &argument);
	if (try_catch.HasCaught()) {
		node::FatalException(try_catch);
	}
}

void AsyncPlayer::playCard(const Arguments &args) {
	HandleScope scope;

    if (args.Length() <= 0 || !args[0]->IsObject()) {
        throw std::invalid_argument("Argument 0 must be an object");
    }

	Local<Object> picked_card = args[0]->ToObject();

	Local<String> key_color = String::NewSymbol("color");
	Local<String> key_value = String::NewSymbol("value");

	if (picked_card->Has(key_color) == false) {
		throw std::invalid_argument("Malformed card object, no color property.");
	}

	if (picked_card->Has(key_value) == false) {
		throw std::invalid_argument("Malformed card object, no value property.");
	}

	Local<Value> property_color = picked_card->Get(key_color);
	if (property_color->IsString() == false) {
		throw std::invalid_argument("Card color must be string.");
	}

	Local<Value> property_value = picked_card->Get(key_value);
	if (property_value->IsString() == false) {
		throw std::invalid_argument("Card value must be string.");
	}

	CARD_COLOR picked_color;
	try {
		picked_color = Card::stringToColor(
			*String::AsciiValue(property_color->ToString())
		);
	} catch (std::invalid_argument &e) {
		throw;
	}

	CARD_VALUE picked_value;
	try {
		picked_value = Card::stringToValue(
			*String::AsciiValue(property_value->ToString())
		);
	} catch (std::invalid_argument &e) {
		throw;
	}

	card_iterator card;
	for (card = hand.begin(); card < hand.end(); card++) {

		// same color and value
		if ((*card)->getColor() == picked_color
		&&  (*card)->getValue() == picked_value
		) {
			try {
				game->takeAction(this, *card);
			} catch (std::invalid_argument &message) {
				throw std::domain_error(message.what());
			}
		}
	}

}

void AsyncPlayer::draw() {
	try {
		game->takeDraw(this);
	} catch (std::invalid_argument &message) {
		throw;
	}
}

Local<Object> AsyncPlayer::createCardObject(Card* card) {
	HandleScope scope;
	Local<Object> jscard = Object::New();

	// get color and value string
	const char* color = Card::colorToString(card->getColor());
	const char* value = Card::valueToString(card->getValue());

	// set color and value property on a js object
	jscard->Set(
		String::New("color"),
		String::NewSymbol(color)
	);

	jscard->Set(
		String::New("value"),
		String::NewSymbol(value)
	);

	return scope.Close(jscard);
}

Local<Object> AsyncPlayer::createPlayerObject(Player* player) {
	HandleScope scope;
	Local<Object> jsplayer = Object::New();

	jsplayer->Set(
		String::NewSymbol("name"),
		String::New(player->getName().c_str())
	);

	return scope.Close(jsplayer);
}

void AsyncPlayer::notify(Event::EVENT event_type, void* event) {
	HandleScope scope;

	Local<Object> jsevent = Object::New();
	const char* jstype = "";

	switch (event_type) {
	case Event::EVENT_GAME_START:
	{
		jstype = "game_start";

		jsevent->Set(
			String::NewSymbol("first_card"),
			createCardObject(
				reinterpret_cast<Event::game_start*>(event)->first_card
			)
		);
	}
		break;
	case Event::EVENT_CARD_PLAYED:
	{
		jstype = "card_played";

		Event::card_played* e = reinterpret_cast<Event::card_played*>(event);
		jsevent->Set(
			String::NewSymbol("played_by"),
			createPlayerObject(e->played_by)
		);

		jsevent->Set(
			String::NewSymbol("played_card"),
			createCardObject(e->played_card)
		);
	}
		break;

	case Event::EVENT_GAME_END:
	{
		jstype = "game_end";

		Event::game_end* e = reinterpret_cast<Event::game_end*>(event);
		jsevent->Set(
			String::NewSymbol("winner"),
			createPlayerObject(e->winner)
		);
	}
		break;

	case Event::EVENT_COLORPICK:
	{
		jstype = "colorpick";

		Event::colorpick* e = reinterpret_cast<Event::colorpick*>(event);

		jsevent->Set(
			String::NewSymbol("picked_by"),
			createPlayerObject(e->picked_by)
		);

		const char* color = NULL;
		try {
			color = Card::colorToString(e->color);
		} catch (std::invalid_argument &e) {
			color = "?";
		}

		jsevent->Set(
			String::NewSymbol("color"),
			String::NewSymbol(color)
		);
	}
		break;

	case Event::EVENT_DRAW_CARD:
	{
		jstype = "draw_card";

		Event::draw_card* e = reinterpret_cast<Event::draw_card*>(event);

		jsevent->Set(
			String::NewSymbol("player"),
			createPlayerObject(e->player)
		);

		jsevent->Set(
			String::NewSymbol("card_count"),
			Int32::New(e->card_count)
		);

		break;
	}

	case Event::EVENT_GETS_BLOCKED:
	{
		jstype = "gets_blocked";
		Event::gets_blocked* e = reinterpret_cast<Event::gets_blocked*>(event);

		jsevent->Set(
			String::NewSymbol("gets_blocked"),
			createPlayerObject(e->gets_blocked)
		);

		jsevent->Set(
			String::NewSymbol("blocked_by"),
			createPlayerObject(e->blocked_by)
		);

		break;
	}

	case Event::EVENT_UNO_SAID:
	{
		jstype = "uno_said";
		Event::uno_said* e = reinterpret_cast<Event::uno_said*>(event);

		jsevent->Set(
			String::NewSymbol("said_by"),
			createPlayerObject(e->said_by)
		);

		const char* type = "";
		switch (e->type) {
		case Event::uno_said::GOOD:
			type = "good";
			break;
		case Event::uno_said::BAD:
			type = "bad";
			break;
		case Event::uno_said::FORGOTTEN:
			type = "forgotten";
			break;
		}

		jsevent->Set(
			String::NewSymbol("type"),
			String::NewSymbol(type)
		);

		break;
	}

	case Event::EVENT_PLAYER_JOINED:
	{
		jstype = "player_joined";
		Event::player_joined* e = reinterpret_cast<Event::player_joined*>(event);

		jsevent->Set(
			String::NewSymbol("player"),
			createPlayerObject(e->player)
		);

		break;
	}

	case Event::EVENT_PLAYERS_TURN:
	{
		jstype = "players_turn";
		Event::players_turn* e = reinterpret_cast<Event::players_turn*>(event);

		jsevent->Set(
			String::NewSymbol("player"),
			createPlayerObject(e->player)
		);
		break;
	}

	default:
		/**
		 * @todo fix typo: unknown.
		 */
		jstype = "unknow_event";
		break;

	}

	jsevent->Set(
			String::NewSymbol("event_type"),
			String::New(jstype)
	);

	Handle<Value> argument = jsevent;

	{   // call notify_cb
		Local<Function> notify_cb = getCallback("notify");
		TryCatch try_catch;
		notify_cb->Call(Context::GetCurrent()->Global(), 1, &argument);
		if (try_catch.HasCaught()) {
			node::FatalException(try_catch);
		}
	}
}

#undef REQ_INT_ARG

}} //namespace
<|endoftext|>


<commit_before>#include "textfile.ih"

vector<unsigned char> indexedcorpus::readFile(string const &filename)
{
	QFileInfo p(filename.c_str());
	if (p.isFile())
          throw runtime_error(string("readFile: '") + filename + "' is not a regular file!");

	vector<unsigned char> data;

	ifstream dataStream(filename.c_str());
	if (!dataStream)
          throw runtime_error(string("readFile: '") + filename + "' could be read!");

	dataStream >> noskipws;

	copy(istream_iterator<char>(dataStream), istream_iterator<char>(),
		back_inserter(data));

	return data;
}
<commit_msg>Fix a flawed check in indexedcorpus::readFile.<commit_after>#include "textfile.ih"

vector<unsigned char> indexedcorpus::readFile(string const &filename)
{
	QFileInfo p(filename.c_str());
	if (!p.isFile())
          throw runtime_error(string("readFile: '") + filename + "' is not a regular file!");

	vector<unsigned char> data;

	ifstream dataStream(filename.c_str());
	if (!dataStream)
          throw runtime_error(string("readFile: '") + filename + "' could be read!");

	dataStream >> noskipws;

	copy(istream_iterator<char>(dataStream), istream_iterator<char>(),
		back_inserter(data));

	return data;
}
<|endoftext|>


<commit_before>#ifndef ELECRELATION_CPP
#define ELECRELATION_CPP

#include "elecRelation.h"

#include "circuit.h"

elecRelation::elecRelation():
  FirstOrderType2R()
{
}

void elecRelation::initialize(SP::Interaction inter)
{
  FirstOrderType2R::initialize(inter);
  unsigned int sizeY = interaction()->getSizeOfY();
  unsigned int sizeDS = interaction()->getSizeOfDS();
  SP::SiconosVector y = interaction()->y(0);
  SP::SiconosVector lambda = interaction()->lambda(0);

  double t0 = 0;

  _workL.reset(new SimpleVector(interaction()->getSizeOfY()));
  Jachx->resize(sizeY, sizeDS);
  Jachlambda->resize(sizeY, sizeY);

  jacgx->resize(sizeDS, sizeDS);
  Jacglambda->resize(sizeDS, sizeY);

#ifdef CLSC_CIRCUIT
  _workX->setValue(0, 0);
  _workL->setValue(0, 20.0 / (sR2 + sR1s));
  _workL->setValue(1, -20.0 / (sR2 + sR1d));
  _workL->setValue(2, 20 - 20 * ((sR1s) / (sR2 + sR1s)));
  _workL->setValue(3, 0);
  _workL->setValue(4, sE_plus);
  _workL->setValue(5, 0);
  _workL->setValue(6, 0);
  _workL->setValue(7, 20 - 20 * ((sR1s) / (sR2 + sR1s)));
  _workL->setValue(8, sR2 - sR1d);
  y->setValue(0, 0);
  y->setValue(1, 0);
  y->setValue(2, 0);
  y->setValue(3, 0);
  y->setValue(4, 0);
  y->setValue(5, sR2 - sR1s);
  y->setValue(6, sE_plus);
  y->setValue(7, 0);
  y->setValue(8, 0);

#else
  _workX->setValue(0, 0);
  _workL->setValue(0, 0);
  _workL->setValue(1, 0);
  _workL->setValue(2, 0);
  _workL->setValue(3, 0);
#endif

  *lambda = *_workL;

  //  computeH(t0);
  computeg(t0);
  computeJach(t0);
  computeJacg(t0);
  *data[r] = *data[g_alpha];
#ifdef SICONOS_DEBUG
  std::cout << "data[r (g_alpha)] init\n";
  data[r]->display();
#endif

}

double elecRelation::source(double t)
{
  double daux = 0;
#ifdef CLSC_CIRCUIT
  double numT = t / sT;
  int aux = (int) floor(numT);
  daux = sE_plus - ((sE_plus - sE_moins) / sT) * t + (sE_plus - sE_moins) * aux;
#ifdef SICONOS_DEBUG
  std::cout << "source(" << t << ")=" << daux << std::endl;
#endif
  return daux;

#else
  daux =  sin(sW * t);
#ifdef SICONOS_DEBUG
  std::cout << "source(" << t << ")=" << daux << std::endl;
#endif
  return daux;
#endif
}

/*y = h(X,lambda)*/
void elecRelation::computeh(double t)
{

  *_workX = *data[x];
  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;

#ifdef SICONOS_DEBUGc
  std::cout << "********         computeh at " << t << std::endl;
#endif
  SP::SiconosVector Heval = interaction()->relation()->Halpha();
#ifdef CLSC_CIRCUIT
  Heval->setValue(0, _workL->getValue(4) - source(t));
  Heval->setValue(1, _workX->getValue(0) - (_workL->getValue(3)) / sR);
  Heval->setValue(2, _workL->getValue(2) - 20 + _workL->getValue(0) * (_workL->getValue(6) + sR1s));
  Heval->setValue(3, _workL->getValue(2) + _workL->getValue(1) * (_workL->getValue(8) + sR1d));
  Heval->setValue(4, _workX->getValue(0) - _workL->getValue(0) - _workL->getValue(1));
  Heval->setValue(5, sR2 - _workL->getValue(6) - sR1s);
  Heval->setValue(6, sAmpli * (_workL->getValue(4) - _workL->getValue(3)) + _workL->getValue(5));
  Heval->setValue(7, sR2 - _workL->getValue(8) - sR1d);
  Heval->setValue(8, -_workL->getValue(2) + _workL->getValue(7));
#else
  Heval->setValue(0, - _workL->getValue(0) + source(t));
  Heval->setValue(1, -_workL->getValue(0) + _workX->getValue(0) + (_workL->getValue(3) + sR1)* _workL->getValue(1));
  Heval->setValue(2, sR2 - _workL->getValue(3) - sR1);
  Heval->setValue(3, _workL->getValue(0) + _workL->getValue(2));
#endif

#ifdef SICONOS_DEBUG
  std::cout << "modif heval : \n";
  Heval->display();
#endif

}

void elecRelation::computeg(double t)
{
  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;

#ifdef SICONOS_DEBUG
  std::cout << "************      computeg at: " << t << std::endl;
#endif

#ifdef CLSC_CIRCUIT
  (*data[g_alpha]).setValue(0, (_workL->getValue(2) - _workL->getValue(3)) / sL);
#else
  (*data[g_alpha]).setValue(0, (_workL->getValue(1)) / sC);
#endif

#ifdef SICONOS_DEBUG
  std::cout << "modif g_alpha : \n";
  data[g_alpha]->display();
#endif
}

/** default function to compute jacobianH
 *  \param double : current time
 *  \param index for jacobian (0: jacobian according to x, 1 according to lambda)
 */
void elecRelation::computeJachx(double t)
{

  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;
  double *h = &(*Jachx)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJachx " << " at " << " " << t << std::endl;
#endif

#ifdef CLSC_CIRCUIT
  h[0] = 0;
  h[1] = 1;
  h[2] = 0;
  h[3] = 0;
  h[4] = 1;
  h[5] = 0;
  h[6] = 0;
  h[7] = 0;
  h[8] = 0;
#else
  h[0] = 0;
  h[1] = 1;
  h[2] = 0;
  h[3] = 0;
#endif

}
void elecRelation::computeJachlambda(double t)
{

  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;
  double *h = &(*Jachlambda)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJachlambda " << " at " << " " << t << std::endl;
#endif

#ifdef CLSC_CIRCUIT
  h[0] = 0;
  h[9] = 0;
  h[18] = 0;
  h[27] = 0;
  h[36] = 1;
  h[45] = 0;
  h[54] = 0;
  h[63] = 0;
  h[72] = 0;
  h[1] = 0;
  h[10] = 0;
  h[19] = 0;
  h[28] = -1 / sR;
  h[37] = 0;
  h[46] = 0;
  h[55] = 0;
  h[64] = 0;
  h[73] = 0;
  h[2] = _workL->getValue(6) + sR1s;
  h[11] = 0;
  h[20] = 1;
  h[29] = 0;
  h[38] = 0;
  h[47] = 0;
  h[56] = _workL->getValue(0);
  h[65] = 0;
  h[74] = 0;
  h[3] = 0;
  h[12] = _workL->getValue(8) + sR1d;
  h[21] = 1;
  h[30] = 0;
  h[39] = 0;
  h[48] = 0;
  h[57] = 0;
  h[66] = 0;
  h[75] = _workL->getValue(1);
  h[4] = -1;
  h[13] = -1;
  h[22] = 0;
  h[31] = 0;
  h[40] = 0;
  h[49] = 0;
  h[58] = 0;
  h[67] = 0;
  h[76] = 0;
  h[5] = 0;
  h[14] = 0;
  h[23] = 0;
  h[32] = 0;
  h[41] = 0;
  h[50] = 0;
  h[59] = -1;
  h[68] = 0;
  h[77] = 0;
  h[6] = 0;
  h[15] = 0;
  h[24] = 0;
  h[33] = -sAmpli;
  h[42] = sAmpli;
  h[51] = 1;
  h[60] = 0;
  h[69] = 0;
  h[78] = 0;
  h[7] = 0;
  h[16] = 0;
  h[25] = 0;
  h[34] = 0;
  h[43] = 0;
  h[52] = 0;
  h[61] = 0;
  h[70] = 0;
  h[79] = -1;
  h[8] = 0;
  h[17] = 0;
  h[26] = -1;
  h[35] = 0;
  h[44] = 0;
  h[53] = 0;
  h[62] = 0;
  h[71] = 1;
  h[80] = 0;
#else
  h[0] = -1;
  h[4] = 0;
  h[8] = 0;
  h[12] = 0;
  h[1] = -1;
  h[5] = _workL->getValue(3) + sR1;
  h[9] = 0;
  h[13] = _workL->getValue(1);
  h[2] = 0;
  h[6] = 0;
  h[10] = 0;
  h[14] = -1;
  h[3] = 1;
  h[7] = 0;
  h[11] = 1;
  h[15] = 0;
#endif

}
/** default function to compute jacobianG according to lambda
 *  \param double : current time
 *  \param index for jacobian: at the time only one possible jacobian => i = 0 is the default value .
 */
void elecRelation::computeJacgx(double t)
{

  double *g = &(*jacgx)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJacgx " << " at " << " " << t << std::endl;
#endif
#ifdef CLSC_CIRCUIT
  g[0] = 0;
#else
  g[0] = 0;
#endif
}
void elecRelation::computeJacglambda(double t)
{

  double *g = &(*Jacglambda)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJacglambda " << " at " << " " << t << std::endl;
#endif
#ifdef CLSC_CIRCUIT
  g[0] = 0;
  g[1] = 0;
  g[2] = 1 / sL;
  g[3] = -1 / sL;
  g[4] = 0;
  g[5] = 0;
  g[6] = 0;
  g[7] = 0;
  g[8] = 0;
#else
  g[0] = 0;
  g[1] = 1 / sC;
  g[2] = 0;
  g[3] = 0;
#endif
}
#endif
<commit_msg>update with the new member name<commit_after>#ifndef ELECRELATION_CPP
#define ELECRELATION_CPP

#include "elecRelation.h"

#include "circuit.h"

elecRelation::elecRelation():
  FirstOrderType2R()
{
}

void elecRelation::initialize(SP::Interaction inter)
{
  FirstOrderType2R::initialize(inter);
  unsigned int sizeY = interaction()->getSizeOfY();
  unsigned int sizeDS = interaction()->getSizeOfDS();
  SP::SiconosVector y = interaction()->y(0);
  SP::SiconosVector lambda = interaction()->lambda(0);

  double t0 = 0;

  _workL.reset(new SimpleVector(interaction()->getSizeOfY()));
  Jachx->resize(sizeY, sizeDS);
  _jachlambda->resize(sizeY, sizeY);

  jacgx->resize(sizeDS, sizeDS);
  Jacglambda->resize(sizeDS, sizeY);

#ifdef CLSC_CIRCUIT
  _workX->setValue(0, 0);
  _workL->setValue(0, 20.0 / (sR2 + sR1s));
  _workL->setValue(1, -20.0 / (sR2 + sR1d));
  _workL->setValue(2, 20 - 20 * ((sR1s) / (sR2 + sR1s)));
  _workL->setValue(3, 0);
  _workL->setValue(4, sE_plus);
  _workL->setValue(5, 0);
  _workL->setValue(6, 0);
  _workL->setValue(7, 20 - 20 * ((sR1s) / (sR2 + sR1s)));
  _workL->setValue(8, sR2 - sR1d);
  y->setValue(0, 0);
  y->setValue(1, 0);
  y->setValue(2, 0);
  y->setValue(3, 0);
  y->setValue(4, 0);
  y->setValue(5, sR2 - sR1s);
  y->setValue(6, sE_plus);
  y->setValue(7, 0);
  y->setValue(8, 0);

#else
  _workX->setValue(0, 0);
  _workL->setValue(0, 0);
  _workL->setValue(1, 0);
  _workL->setValue(2, 0);
  _workL->setValue(3, 0);
#endif

  *lambda = *_workL;

  //  computeH(t0);
  computeg(t0);
  computeJach(t0);
  computeJacg(t0);
  *data[r] = *data[g_alpha];
#ifdef SICONOS_DEBUG
  std::cout << "data[r (g_alpha)] init\n";
  data[r]->display();
#endif

}

double elecRelation::source(double t)
{
  double daux = 0;
#ifdef CLSC_CIRCUIT
  double numT = t / sT;
  int aux = (int) floor(numT);
  daux = sE_plus - ((sE_plus - sE_moins) / sT) * t + (sE_plus - sE_moins) * aux;
#ifdef SICONOS_DEBUG
  std::cout << "source(" << t << ")=" << daux << std::endl;
#endif
  return daux;

#else
  daux =  sin(sW * t);
#ifdef SICONOS_DEBUG
  std::cout << "source(" << t << ")=" << daux << std::endl;
#endif
  return daux;
#endif
}

/*y = h(X,lambda)*/
void elecRelation::computeh(double t)
{

  *_workX = *data[x];
  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;

#ifdef SICONOS_DEBUGc
  std::cout << "********         computeh at " << t << std::endl;
#endif
  SP::SiconosVector Heval = interaction()->relation()->Halpha();
#ifdef CLSC_CIRCUIT
  Heval->setValue(0, _workL->getValue(4) - source(t));
  Heval->setValue(1, _workX->getValue(0) - (_workL->getValue(3)) / sR);
  Heval->setValue(2, _workL->getValue(2) - 20 + _workL->getValue(0) * (_workL->getValue(6) + sR1s));
  Heval->setValue(3, _workL->getValue(2) + _workL->getValue(1) * (_workL->getValue(8) + sR1d));
  Heval->setValue(4, _workX->getValue(0) - _workL->getValue(0) - _workL->getValue(1));
  Heval->setValue(5, sR2 - _workL->getValue(6) - sR1s);
  Heval->setValue(6, sAmpli * (_workL->getValue(4) - _workL->getValue(3)) + _workL->getValue(5));
  Heval->setValue(7, sR2 - _workL->getValue(8) - sR1d);
  Heval->setValue(8, -_workL->getValue(2) + _workL->getValue(7));
#else
  Heval->setValue(0, - _workL->getValue(0) + source(t));
  Heval->setValue(1, -_workL->getValue(0) + _workX->getValue(0) + (_workL->getValue(3) + sR1)* _workL->getValue(1));
  Heval->setValue(2, sR2 - _workL->getValue(3) - sR1);
  Heval->setValue(3, _workL->getValue(0) + _workL->getValue(2));
#endif

#ifdef SICONOS_DEBUG
  std::cout << "modif heval : \n";
  Heval->display();
#endif

}

void elecRelation::computeg(double t)
{
  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;

#ifdef SICONOS_DEBUG
  std::cout << "************      computeg at: " << t << std::endl;
#endif

#ifdef CLSC_CIRCUIT
  (*data[g_alpha]).setValue(0, (_workL->getValue(2) - _workL->getValue(3)) / sL);
#else
  (*data[g_alpha]).setValue(0, (_workL->getValue(1)) / sC);
#endif

#ifdef SICONOS_DEBUG
  std::cout << "modif g_alpha : \n";
  data[g_alpha]->display();
#endif
}

/** default function to compute jacobianH
 *  \param double : current time
 *  \param index for jacobian (0: jacobian according to x, 1 according to lambda)
 */
void elecRelation::computeJachx(double t)
{

  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;
  double *h = &(*Jachx)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJachx " << " at " << " " << t << std::endl;
#endif

#ifdef CLSC_CIRCUIT
  h[0] = 0;
  h[1] = 1;
  h[2] = 0;
  h[3] = 0;
  h[4] = 1;
  h[5] = 0;
  h[6] = 0;
  h[7] = 0;
  h[8] = 0;
#else
  h[0] = 0;
  h[1] = 1;
  h[2] = 0;
  h[3] = 0;
#endif

}
void elecRelation::computeJachlambda(double t)
{

  SP::SiconosVector lambda = interaction()->lambda(0);
  *_workL = *lambda;
  double *h = &(*_jachlambda)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJachlambda " << " at " << " " << t << std::endl;
#endif

#ifdef CLSC_CIRCUIT
  h[0] = 0;
  h[9] = 0;
  h[18] = 0;
  h[27] = 0;
  h[36] = 1;
  h[45] = 0;
  h[54] = 0;
  h[63] = 0;
  h[72] = 0;
  h[1] = 0;
  h[10] = 0;
  h[19] = 0;
  h[28] = -1 / sR;
  h[37] = 0;
  h[46] = 0;
  h[55] = 0;
  h[64] = 0;
  h[73] = 0;
  h[2] = _workL->getValue(6) + sR1s;
  h[11] = 0;
  h[20] = 1;
  h[29] = 0;
  h[38] = 0;
  h[47] = 0;
  h[56] = _workL->getValue(0);
  h[65] = 0;
  h[74] = 0;
  h[3] = 0;
  h[12] = _workL->getValue(8) + sR1d;
  h[21] = 1;
  h[30] = 0;
  h[39] = 0;
  h[48] = 0;
  h[57] = 0;
  h[66] = 0;
  h[75] = _workL->getValue(1);
  h[4] = -1;
  h[13] = -1;
  h[22] = 0;
  h[31] = 0;
  h[40] = 0;
  h[49] = 0;
  h[58] = 0;
  h[67] = 0;
  h[76] = 0;
  h[5] = 0;
  h[14] = 0;
  h[23] = 0;
  h[32] = 0;
  h[41] = 0;
  h[50] = 0;
  h[59] = -1;
  h[68] = 0;
  h[77] = 0;
  h[6] = 0;
  h[15] = 0;
  h[24] = 0;
  h[33] = -sAmpli;
  h[42] = sAmpli;
  h[51] = 1;
  h[60] = 0;
  h[69] = 0;
  h[78] = 0;
  h[7] = 0;
  h[16] = 0;
  h[25] = 0;
  h[34] = 0;
  h[43] = 0;
  h[52] = 0;
  h[61] = 0;
  h[70] = 0;
  h[79] = -1;
  h[8] = 0;
  h[17] = 0;
  h[26] = -1;
  h[35] = 0;
  h[44] = 0;
  h[53] = 0;
  h[62] = 0;
  h[71] = 1;
  h[80] = 0;
#else
  h[0] = -1;
  h[4] = 0;
  h[8] = 0;
  h[12] = 0;
  h[1] = -1;
  h[5] = _workL->getValue(3) + sR1;
  h[9] = 0;
  h[13] = _workL->getValue(1);
  h[2] = 0;
  h[6] = 0;
  h[10] = 0;
  h[14] = -1;
  h[3] = 1;
  h[7] = 0;
  h[11] = 1;
  h[15] = 0;
#endif

}
/** default function to compute jacobianG according to lambda
 *  \param double : current time
 *  \param index for jacobian: at the time only one possible jacobian => i = 0 is the default value .
 */
void elecRelation::computeJacgx(double t)
{

  double *g = &(*jacgx)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJacgx " << " at " << " " << t << std::endl;
#endif
#ifdef CLSC_CIRCUIT
  g[0] = 0;
#else
  g[0] = 0;
#endif
}
void elecRelation::computeJacglambda(double t)
{

  double *g = &(*Jacglambda)(0, 0);
#ifdef SICONOS_DEBUG
  std::cout << "computeJacglambda " << " at " << " " << t << std::endl;
#endif
#ifdef CLSC_CIRCUIT
  g[0] = 0;
  g[1] = 0;
  g[2] = 1 / sL;
  g[3] = -1 / sL;
  g[4] = 0;
  g[5] = 0;
  g[6] = 0;
  g[7] = 0;
  g[8] = 0;
#else
  g[0] = 0;
  g[1] = 1 / sC;
  g[2] = 0;
  g[3] = 0;
#endif
}
#endif
<|endoftext|>


<commit_before>#include<bits/stdc++.h>
#define FOR(i,m,n) for(int i=m;i<(n);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(x) (x).begin(),(x).end()
using namespace std;
typedef long long ll;
const ll inf = INT_MAX;
const double eps = 1e-8;
const double pi = acos(-1.0);

int dp[10000000];

int main(void){
  int g;
  const int w[6]={200,300,500,1000,1200,1500};
  const int c[6]={380,550,850,380*5*80/100,550*4*85/100,850*3*88/100};
  memset(dp,100000,sizeof dp);
  dp[0]=0;
  REP(i,5000)REP(j,6){
    dp[i+w[j]]=min(dp[i],dp[i+w[j]]+c[j]);
  }
  // REP(i,10000000)cout<<dp[i]<<endl;
  while(cin>>g,g){
    cout<<dp[g]<<endl;
  }
  return 0;
}
<commit_msg>AC AOJ/0106<commit_after>#include<bits/stdc++.h>
#define FOR(i,m,n) for(int i=m;i<(n);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(x) (x).begin(),(x).end()
using namespace std;
typedef long long ll;
const ll inf = INT_MAX;
const double eps = 1e-8;
const double pi = acos(-1.0);

int main(void){
  int g;
  while(cin>>g,g){
    int ans=inf;
    REP(i,51){
      REP(j,51){
        REP(k,51){
          if(200*i+300*j+500*k!=g)continue;
          int wi=i/5,wj=j/4,wk=k/3;
          int nwi=max(0,i-wi*5),nwj=max(0,j-wj*4),nwk=max(0,k-wk*3);
          ans=min(ans,wi*1520+wj*1870+wk*2244+nwi*380+nwj*550+nwk*850);
          // cout<<i<<","<<j<<","<<k<<","<<ans<<endl;
        }
      }
    }
    cout<<ans<<endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "cpplocalsymbols.h"
#include "cppsemanticinfo.h"

#include <cplusplus/CppDocument.h>
#include <ASTVisitor.h>
#include <AST.h>
#include <Scope.h>
#include <Symbols.h>
#include <CoreTypes.h>
#include <Names.h>
#include <Literals.h>

using namespace CPlusPlus;
using namespace CppEditor::Internal;

namespace {

class FindLocalSymbols: protected ASTVisitor
{
    Scope *_functionScope;
    Document::Ptr _doc;

public:
    FindLocalSymbols(Document::Ptr doc)
        : ASTVisitor(doc->translationUnit()), _doc(doc), hasD(false), hasQ(false)
    { }

    // local and external uses.
    SemanticInfo::LocalUseMap localUses;
    bool hasD;
    bool hasQ;

    void operator()(DeclarationAST *ast)
    {
        localUses.clear();

        if (!ast)
            return;

        if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) {
            if (def->symbol) {
                _functionScope = def->symbol;
                accept(ast);
            }
        } else if (ObjCMethodDeclarationAST *decl = ast->asObjCMethodDeclaration()) {
            if (decl->method_prototype->symbol) {
                _functionScope = decl->method_prototype->symbol;
                accept(ast);
            }
        }
    }

protected:
    using ASTVisitor::visit;
    using ASTVisitor::endVisit;

    void enterScope(Scope *scope)
    {
        _scopeStack.append(scope);

        for (unsigned i = 0; i < scope->memberCount(); ++i) {
            if (Symbol *member = scope->memberAt(i)) {
                if (member->isTypedef())
                    continue;
                else if (! member->isGenerated() && (member->isDeclaration() || member->isArgument())) {
                    if (member->name() && member->name()->isNameId()) {
                        const Identifier *id = member->identifier();
                        unsigned line, column;
                        getTokenStartPosition(member->sourceLocation(), &line, &column);
                        localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::Use::Local));
                    }
                }
            }
        }
    }

    virtual bool visit(IdExpressionAST *ast)
    {
        if (SimpleNameAST *simpleName = ast->name->asSimpleName()) {
            const Identifier *id = identifier(simpleName->identifier_token);
            for (int i = _scopeStack.size() - 1; i != -1; --i) {
                if (Symbol *member = _scopeStack.at(i)->find(id)) {
                    if (member->isTypedef())
                        continue;
                    else if (!member->isGenerated() && (member->sourceLocation() < ast->firstToken() || member->scope()->isFunction())) {
                        unsigned line, column;
                        getTokenStartPosition(simpleName->identifier_token, &line, &column);
                        localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::Use::Local));
                        return false;
                    }
                }
            }
        }

        return true;
    }

    virtual bool visit(QtMemberDeclarationAST *ast)
    {
        if (tokenKind(ast->q_token) == T_Q_D)
            hasD = true;
        else
            hasQ = true;

        return true;
    }

    virtual bool visit(FunctionDefinitionAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(FunctionDefinitionAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(CompoundStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(CompoundStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(IfStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(IfStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(WhileStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(WhileStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(ForStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(ForStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(ForeachStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(ForeachStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(SwitchStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(SwitchStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(CatchClauseAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(CatchClauseAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(ExpressionOrDeclarationStatementAST *ast)
    {
        accept(ast->declaration);
        return false;
    }

private:
    QList<Scope *> _scopeStack;
};

} // end of anonymous namespace

LocalSymbols::LocalSymbols(CPlusPlus::Document::Ptr doc, CPlusPlus::DeclarationAST *ast)
{
    FindLocalSymbols FindLocalSymbols(doc);
    FindLocalSymbols(ast);
    hasD = FindLocalSymbols.hasD;
    hasQ = FindLocalSymbols.hasQ;
    uses = FindLocalSymbols.localUses;
}
<commit_msg>Renamed the local declaration of FindLocalSymbols.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "cpplocalsymbols.h"
#include "cppsemanticinfo.h"

#include <cplusplus/CppDocument.h>
#include <ASTVisitor.h>
#include <AST.h>
#include <Scope.h>
#include <Symbols.h>
#include <CoreTypes.h>
#include <Names.h>
#include <Literals.h>

using namespace CPlusPlus;
using namespace CppEditor::Internal;

namespace {

class FindLocalSymbols: protected ASTVisitor
{
    Scope *_functionScope;
    Document::Ptr _doc;

public:
    FindLocalSymbols(Document::Ptr doc)
        : ASTVisitor(doc->translationUnit()), _doc(doc), hasD(false), hasQ(false)
    { }

    // local and external uses.
    SemanticInfo::LocalUseMap localUses;
    bool hasD;
    bool hasQ;

    void operator()(DeclarationAST *ast)
    {
        localUses.clear();

        if (!ast)
            return;

        if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) {
            if (def->symbol) {
                _functionScope = def->symbol;
                accept(ast);
            }
        } else if (ObjCMethodDeclarationAST *decl = ast->asObjCMethodDeclaration()) {
            if (decl->method_prototype->symbol) {
                _functionScope = decl->method_prototype->symbol;
                accept(ast);
            }
        }
    }

protected:
    using ASTVisitor::visit;
    using ASTVisitor::endVisit;

    void enterScope(Scope *scope)
    {
        _scopeStack.append(scope);

        for (unsigned i = 0; i < scope->memberCount(); ++i) {
            if (Symbol *member = scope->memberAt(i)) {
                if (member->isTypedef())
                    continue;
                else if (! member->isGenerated() && (member->isDeclaration() || member->isArgument())) {
                    if (member->name() && member->name()->isNameId()) {
                        const Identifier *id = member->identifier();
                        unsigned line, column;
                        getTokenStartPosition(member->sourceLocation(), &line, &column);
                        localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::Use::Local));
                    }
                }
            }
        }
    }

    virtual bool visit(IdExpressionAST *ast)
    {
        if (SimpleNameAST *simpleName = ast->name->asSimpleName()) {
            const Identifier *id = identifier(simpleName->identifier_token);
            for (int i = _scopeStack.size() - 1; i != -1; --i) {
                if (Symbol *member = _scopeStack.at(i)->find(id)) {
                    if (member->isTypedef())
                        continue;
                    else if (!member->isGenerated() && (member->sourceLocation() < ast->firstToken() || member->scope()->isFunction())) {
                        unsigned line, column;
                        getTokenStartPosition(simpleName->identifier_token, &line, &column);
                        localUses[member].append(SemanticInfo::Use(line, column, id->size(), SemanticInfo::Use::Local));
                        return false;
                    }
                }
            }
        }

        return true;
    }

    virtual bool visit(QtMemberDeclarationAST *ast)
    {
        if (tokenKind(ast->q_token) == T_Q_D)
            hasD = true;
        else
            hasQ = true;

        return true;
    }

    virtual bool visit(FunctionDefinitionAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(FunctionDefinitionAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(CompoundStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(CompoundStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(IfStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(IfStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(WhileStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(WhileStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(ForStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(ForStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(ForeachStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(ForeachStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(SwitchStatementAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(SwitchStatementAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(CatchClauseAST *ast)
    {
        if (ast->symbol)
            enterScope(ast->symbol);
        return true;
    }

    virtual void endVisit(CatchClauseAST *ast)
    {
        if (ast->symbol)
            _scopeStack.removeLast();
    }

    virtual bool visit(ExpressionOrDeclarationStatementAST *ast)
    {
        accept(ast->declaration);
        return false;
    }

private:
    QList<Scope *> _scopeStack;
};

} // end of anonymous namespace

LocalSymbols::LocalSymbols(CPlusPlus::Document::Ptr doc, CPlusPlus::DeclarationAST *ast)
{
    FindLocalSymbols findLocalSymbols(doc);
    findLocalSymbols(ast);
    hasD = findLocalSymbols.hasD;
    hasQ = findLocalSymbols.hasQ;
    uses = findLocalSymbols.localUses;
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.

#include <hpp/core/problem-target/goal-configurations.hh>

#include <stdexcept>

#include <hpp/util/debug.hh>

#include <hpp/core/problem.hh>
#include <hpp/core/roadmap.hh>
#include <hpp/core/connected-component.hh>
#include <hpp/core/config-validations.hh>

#include "../astar.hh"

namespace hpp {
  namespace core {
    namespace problemTarget {
      GoalConfigurationsPtr_t GoalConfigurations::create
        (const ProblemPtr_t& problem)
      {
        GoalConfigurations* gc = new GoalConfigurations (problem);
        GoalConfigurationsPtr_t shPtr (gc);
        gc->init (shPtr);
        return shPtr;
      }

      void GoalConfigurations::check (const RoadmapPtr_t& /*roadmap*/) const
      {
      }

      bool GoalConfigurations::reached (const RoadmapPtr_t& roadmap) const
      {
        const ConnectedComponentPtr_t ccInit = roadmap->initNode ()->connectedComponent ();
        const NodeVector_t& goals = roadmap->goalNodes();
        for (NodeVector_t::const_iterator _goal = goals.begin (); _goal != goals.end (); ++_goal) {
          if (ccInit->canReach ((*_goal)->connectedComponent ())) {
            return true;
          }
        }
        return false;
      }

      PathVectorPtr_t GoalConfigurations::computePath(const RoadmapPtr_t& roadmap) const
      {
        ProblemPtr_t problem (problem_.lock());
        assert (problem);
        Astar astar (roadmap, problem->distance ());
        PathVectorPtr_t sol = PathVector::create (
            problem->robot()->configSize(), problem->robot()->numberDof());
        astar.solution (sol);
        // This happens when q_init == q_goal
        if (sol->numberPaths() == 0) {
          ConfigurationPtr_t q (roadmap->initNode()->configuration ());
          sol->appendPath(
              (*problem->steeringMethod()) (*q, *q)
              );
        }
        return sol;
      }
    } // namespace problemTarget
  } // namespace core
} // namespace hpp
<commit_msg>Make GoalConfigurations problem target safer.<commit_after>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.

#include <hpp/core/problem-target/goal-configurations.hh>

#include <stdexcept>

#include <hpp/util/debug.hh>

#include <hpp/core/problem.hh>
#include <hpp/core/roadmap.hh>
#include <hpp/core/connected-component.hh>
#include <hpp/core/config-validations.hh>

#include "../astar.hh"

namespace hpp {
  namespace core {
    namespace problemTarget {
      GoalConfigurationsPtr_t GoalConfigurations::create
        (const ProblemPtr_t& problem)
      {
        GoalConfigurations* gc = new GoalConfigurations (problem);
        GoalConfigurationsPtr_t shPtr (gc);
        gc->init (shPtr);
        return shPtr;
      }

      void GoalConfigurations::check (const RoadmapPtr_t& /*roadmap*/) const
      {
      }

      bool GoalConfigurations::reached (const RoadmapPtr_t& roadmap) const
      {
        if (!roadmap->initNode ()) return false;
        const ConnectedComponentPtr_t ccInit = roadmap->initNode ()->connectedComponent ();
        const NodeVector_t& goals = roadmap->goalNodes();
        for (NodeVector_t::const_iterator _goal = goals.begin (); _goal != goals.end (); ++_goal) {
          if (ccInit->canReach ((*_goal)->connectedComponent ())) {
            return true;
          }
        }
        return false;
      }

      PathVectorPtr_t GoalConfigurations::computePath(const RoadmapPtr_t& roadmap) const
      {
        ProblemPtr_t problem (problem_.lock());
        assert (problem);
        Astar astar (roadmap, problem->distance ());
        PathVectorPtr_t sol = PathVector::create (
            problem->robot()->configSize(), problem->robot()->numberDof());
        astar.solution (sol);
        // This happens when q_init == q_goal
        if (sol->numberPaths() == 0) {
          ConfigurationPtr_t q (roadmap->initNode()->configuration ());
          sol->appendPath(
              (*problem->steeringMethod()) (*q, *q)
              );
        }
        return sol;
      }
    } // namespace problemTarget
  } // namespace core
} // namespace hpp
<|endoftext|>


<commit_before><commit_msg>More fear of blue<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mapmod.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-11-01 10:32:20 $
 *
 *  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 _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _VCOMPAT_HXX
#include <tools/vcompat.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_MAPMOD_HXX
#include <mapmod.hxx>
#endif

// =======================================================================

DBG_NAME( MapMode );

// -----------------------------------------------------------------------

ImplMapMode::ImplMapMode() :
    maOrigin( 0, 0 ),
    maScaleX( 1, 1 ),
    maScaleY( 1, 1 )
{
    mnRefCount  = 1;
    meUnit      = MAP_PIXEL;
    mbSimple    = FALSE;
}

// -----------------------------------------------------------------------

ImplMapMode::ImplMapMode( const ImplMapMode& rImplMapMode ) :
    maOrigin( rImplMapMode.maOrigin ),
    maScaleX( rImplMapMode.maScaleX ),
    maScaleY( rImplMapMode.maScaleY )
{
    mnRefCount      = 1;
    meUnit          = rImplMapMode.meUnit;
    mbSimple        = FALSE;
}

// -----------------------------------------------------------------------

SvStream& operator>>( SvStream& rIStm, ImplMapMode& rImplMapMode )
{
    VersionCompat   aCompat( rIStm, STREAM_READ );
    UINT16          nTmp16;

    rIStm >> nTmp16; rImplMapMode.meUnit = (MapUnit) nTmp16;
    rIStm >> rImplMapMode.maOrigin >> rImplMapMode.maScaleX >>
             rImplMapMode.maScaleY >> rImplMapMode.mbSimple;

    return rIStm;
}

// -----------------------------------------------------------------------

SvStream& operator<<( SvStream& rOStm, const ImplMapMode& rImplMapMode )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rOStm << (UINT16) rImplMapMode.meUnit <<
             rImplMapMode.maOrigin <<
             rImplMapMode.maScaleX <<
             rImplMapMode.maScaleY <<
             rImplMapMode.mbSimple;

    return rOStm;
}

// -----------------------------------------------------------------------

ImplMapMode* ImplMapMode::ImplGetStaticMapMode( MapUnit eUnit )
{
    static long aStaticImplMapModeAry[(MAP_LASTENUMDUMMY)*sizeof(ImplMapMode)/sizeof(long)];

    // #i19496 check for out-of-bounds
     if( eUnit >= MAP_LASTENUMDUMMY )
        return (ImplMapMode*)aStaticImplMapModeAry;

    ImplMapMode* pImplMapMode = ((ImplMapMode*)aStaticImplMapModeAry)+eUnit;
    if ( !pImplMapMode->mbSimple )
    {
        Fraction aDefFraction( 1, 1 );
        pImplMapMode->maScaleX  = aDefFraction;
        pImplMapMode->maScaleY  = aDefFraction;
        pImplMapMode->meUnit    = eUnit;
        pImplMapMode->mbSimple  = TRUE;
    }

    return pImplMapMode;
}

// -----------------------------------------------------------------------

inline void MapMode::ImplMakeUnique()
{
    // Falls noch andere Referenzen bestehen, dann kopieren
    if ( mpImplMapMode->mnRefCount != 1 )
    {
        if ( mpImplMapMode->mnRefCount )
            mpImplMapMode->mnRefCount--;
        mpImplMapMode = new ImplMapMode( *mpImplMapMode );
    }
}

// -----------------------------------------------------------------------

MapMode::MapMode()
{
    DBG_CTOR( MapMode, NULL );

    mpImplMapMode = ImplMapMode::ImplGetStaticMapMode( MAP_PIXEL );
}

// -----------------------------------------------------------------------

MapMode::MapMode( const MapMode& rMapMode )
{
    DBG_CTOR( MapMode, NULL );
    DBG_CHKOBJ( &rMapMode, MapMode, NULL );
    DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" );

    // shared Instance Daten uebernehmen und Referenzcounter erhoehen
    mpImplMapMode = rMapMode.mpImplMapMode;
    // RefCount == 0 fuer statische Objekte
    if ( mpImplMapMode->mnRefCount )
        mpImplMapMode->mnRefCount++;
}

// -----------------------------------------------------------------------

MapMode::MapMode( MapUnit eUnit )
{
    DBG_CTOR( MapMode, NULL );

    mpImplMapMode = ImplMapMode::ImplGetStaticMapMode( eUnit );
}

// -----------------------------------------------------------------------

MapMode::MapMode( MapUnit eUnit, const Point& rLogicOrg,
                  const Fraction& rScaleX, const Fraction& rScaleY )
{
    DBG_CTOR( MapMode, NULL );

    mpImplMapMode           = new ImplMapMode;
    mpImplMapMode->meUnit   = eUnit;
    mpImplMapMode->maOrigin = rLogicOrg;
    mpImplMapMode->maScaleX = rScaleX;
    mpImplMapMode->maScaleY = rScaleY;
}

// -----------------------------------------------------------------------

MapMode::~MapMode()
{
    DBG_DTOR( MapMode, NULL );

    // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es
    // die letzte Referenz ist, sonst Referenzcounter decrementieren
    if ( mpImplMapMode->mnRefCount )
    {
        if ( mpImplMapMode->mnRefCount == 1 )
            delete mpImplMapMode;
        else
            mpImplMapMode->mnRefCount--;
    }
}

// -----------------------------------------------------------------------

void MapMode::SetMapUnit( MapUnit eUnit )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->meUnit = eUnit;
}

// -----------------------------------------------------------------------

void MapMode::SetOrigin( const Point& rLogicOrg )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->maOrigin = rLogicOrg;
}

// -----------------------------------------------------------------------

void MapMode::SetScaleX( const Fraction& rScaleX )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->maScaleX = rScaleX;
}

// -----------------------------------------------------------------------

void MapMode::SetScaleY( const Fraction& rScaleY )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->maScaleY = rScaleY;
}

// -----------------------------------------------------------------------

MapMode& MapMode::operator=( const MapMode& rMapMode )
{
    DBG_CHKTHIS( MapMode, NULL );
    DBG_CHKOBJ( &rMapMode, MapMode, NULL );
    DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" );

    // Zuerst Referenzcounter erhoehen, damit man sich selbst zuweisen kann
    // RefCount == 0 fuer statische Objekte
    if ( rMapMode.mpImplMapMode->mnRefCount )
        rMapMode.mpImplMapMode->mnRefCount++;

    // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es
    // die letzte Referenz ist, sonst Referenzcounter decrementieren
    if ( mpImplMapMode->mnRefCount )
    {
        if ( mpImplMapMode->mnRefCount == 1 )
            delete mpImplMapMode;
        else
            mpImplMapMode->mnRefCount--;
    }

    mpImplMapMode = rMapMode.mpImplMapMode;

    return *this;
}

// -----------------------------------------------------------------------

BOOL MapMode::operator==( const MapMode& rMapMode ) const
{
    DBG_CHKTHIS( MapMode, NULL );
    DBG_CHKOBJ( &rMapMode, MapMode, NULL );

    if ( mpImplMapMode == rMapMode.mpImplMapMode )
        return TRUE;

    if ( (mpImplMapMode->meUnit   == rMapMode.mpImplMapMode->meUnit)   &&
         (mpImplMapMode->maOrigin == rMapMode.mpImplMapMode->maOrigin) &&
         (mpImplMapMode->maScaleX == rMapMode.mpImplMapMode->maScaleX) &&
         (mpImplMapMode->maScaleY == rMapMode.mpImplMapMode->maScaleY) )
        return TRUE;
    else
        return FALSE;
}

// -----------------------------------------------------------------------

BOOL MapMode::IsDefault() const
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMapMode* pDefMapMode = ImplMapMode::ImplGetStaticMapMode( MAP_PIXEL );
    if ( mpImplMapMode == pDefMapMode )
        return TRUE;

    if ( (mpImplMapMode->meUnit   == pDefMapMode->meUnit)   &&
         (mpImplMapMode->maOrigin == pDefMapMode->maOrigin) &&
         (mpImplMapMode->maScaleX == pDefMapMode->maScaleX) &&
         (mpImplMapMode->maScaleY == pDefMapMode->maScaleY) )
        return TRUE;
    else
        return FALSE;
}

// -----------------------------------------------------------------------

SvStream& operator>>( SvStream& rIStm, MapMode& rMapMode )
{
    rMapMode.ImplMakeUnique();
    return (rIStm >> *rMapMode.mpImplMapMode);
}

// -----------------------------------------------------------------------

SvStream& operator<<( SvStream& rOStm, const MapMode& rMapMode )
{
    return (rOStm << *rMapMode.mpImplMapMode);
}
<commit_msg>INTEGRATION: CWS warnings01 (1.5.2); FILE MERGED 2005/11/04 17:25:01 pl 1.5.2.1: #i55991# removed warnings for linux/solaris<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mapmod.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 19:26:32 $
 *
 *  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 _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _VCOMPAT_HXX
#include <tools/vcompat.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_MAPMOD_HXX
#include <mapmod.hxx>
#endif

// =======================================================================

DBG_NAME( MapMode )

// -----------------------------------------------------------------------

ImplMapMode::ImplMapMode() :
    maOrigin( 0, 0 ),
    maScaleX( 1, 1 ),
    maScaleY( 1, 1 )
{
    mnRefCount  = 1;
    meUnit      = MAP_PIXEL;
    mbSimple    = FALSE;
}

// -----------------------------------------------------------------------

ImplMapMode::ImplMapMode( const ImplMapMode& rImplMapMode ) :
    maOrigin( rImplMapMode.maOrigin ),
    maScaleX( rImplMapMode.maScaleX ),
    maScaleY( rImplMapMode.maScaleY )
{
    mnRefCount      = 1;
    meUnit          = rImplMapMode.meUnit;
    mbSimple        = FALSE;
}

// -----------------------------------------------------------------------

SvStream& operator>>( SvStream& rIStm, ImplMapMode& rImplMapMode )
{
    VersionCompat   aCompat( rIStm, STREAM_READ );
    UINT16          nTmp16;

    rIStm >> nTmp16; rImplMapMode.meUnit = (MapUnit) nTmp16;
    rIStm >> rImplMapMode.maOrigin >> rImplMapMode.maScaleX >>
             rImplMapMode.maScaleY >> rImplMapMode.mbSimple;

    return rIStm;
}

// -----------------------------------------------------------------------

SvStream& operator<<( SvStream& rOStm, const ImplMapMode& rImplMapMode )
{
    VersionCompat aCompat( rOStm, STREAM_WRITE, 1 );

    rOStm << (UINT16) rImplMapMode.meUnit <<
             rImplMapMode.maOrigin <<
             rImplMapMode.maScaleX <<
             rImplMapMode.maScaleY <<
             rImplMapMode.mbSimple;

    return rOStm;
}

// -----------------------------------------------------------------------

ImplMapMode* ImplMapMode::ImplGetStaticMapMode( MapUnit eUnit )
{
    static long aStaticImplMapModeAry[(MAP_LASTENUMDUMMY)*sizeof(ImplMapMode)/sizeof(long)];

    // #i19496 check for out-of-bounds
     if( eUnit >= MAP_LASTENUMDUMMY )
        return (ImplMapMode*)aStaticImplMapModeAry;

    ImplMapMode* pImplMapMode = ((ImplMapMode*)aStaticImplMapModeAry)+eUnit;
    if ( !pImplMapMode->mbSimple )
    {
        Fraction aDefFraction( 1, 1 );
        pImplMapMode->maScaleX  = aDefFraction;
        pImplMapMode->maScaleY  = aDefFraction;
        pImplMapMode->meUnit    = eUnit;
        pImplMapMode->mbSimple  = TRUE;
    }

    return pImplMapMode;
}

// -----------------------------------------------------------------------

inline void MapMode::ImplMakeUnique()
{
    // Falls noch andere Referenzen bestehen, dann kopieren
    if ( mpImplMapMode->mnRefCount != 1 )
    {
        if ( mpImplMapMode->mnRefCount )
            mpImplMapMode->mnRefCount--;
        mpImplMapMode = new ImplMapMode( *mpImplMapMode );
    }
}

// -----------------------------------------------------------------------

MapMode::MapMode()
{
    DBG_CTOR( MapMode, NULL );

    mpImplMapMode = ImplMapMode::ImplGetStaticMapMode( MAP_PIXEL );
}

// -----------------------------------------------------------------------

MapMode::MapMode( const MapMode& rMapMode )
{
    DBG_CTOR( MapMode, NULL );
    DBG_CHKOBJ( &rMapMode, MapMode, NULL );
    DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" );

    // shared Instance Daten uebernehmen und Referenzcounter erhoehen
    mpImplMapMode = rMapMode.mpImplMapMode;
    // RefCount == 0 fuer statische Objekte
    if ( mpImplMapMode->mnRefCount )
        mpImplMapMode->mnRefCount++;
}

// -----------------------------------------------------------------------

MapMode::MapMode( MapUnit eUnit )
{
    DBG_CTOR( MapMode, NULL );

    mpImplMapMode = ImplMapMode::ImplGetStaticMapMode( eUnit );
}

// -----------------------------------------------------------------------

MapMode::MapMode( MapUnit eUnit, const Point& rLogicOrg,
                  const Fraction& rScaleX, const Fraction& rScaleY )
{
    DBG_CTOR( MapMode, NULL );

    mpImplMapMode           = new ImplMapMode;
    mpImplMapMode->meUnit   = eUnit;
    mpImplMapMode->maOrigin = rLogicOrg;
    mpImplMapMode->maScaleX = rScaleX;
    mpImplMapMode->maScaleY = rScaleY;
}

// -----------------------------------------------------------------------

MapMode::~MapMode()
{
    DBG_DTOR( MapMode, NULL );

    // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es
    // die letzte Referenz ist, sonst Referenzcounter decrementieren
    if ( mpImplMapMode->mnRefCount )
    {
        if ( mpImplMapMode->mnRefCount == 1 )
            delete mpImplMapMode;
        else
            mpImplMapMode->mnRefCount--;
    }
}

// -----------------------------------------------------------------------

void MapMode::SetMapUnit( MapUnit eUnit )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->meUnit = eUnit;
}

// -----------------------------------------------------------------------

void MapMode::SetOrigin( const Point& rLogicOrg )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->maOrigin = rLogicOrg;
}

// -----------------------------------------------------------------------

void MapMode::SetScaleX( const Fraction& rScaleX )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->maScaleX = rScaleX;
}

// -----------------------------------------------------------------------

void MapMode::SetScaleY( const Fraction& rScaleY )
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMakeUnique();
    mpImplMapMode->maScaleY = rScaleY;
}

// -----------------------------------------------------------------------

MapMode& MapMode::operator=( const MapMode& rMapMode )
{
    DBG_CHKTHIS( MapMode, NULL );
    DBG_CHKOBJ( &rMapMode, MapMode, NULL );
    DBG_ASSERT( rMapMode.mpImplMapMode->mnRefCount < 0xFFFE, "MapMode: RefCount overflow" );

    // Zuerst Referenzcounter erhoehen, damit man sich selbst zuweisen kann
    // RefCount == 0 fuer statische Objekte
    if ( rMapMode.mpImplMapMode->mnRefCount )
        rMapMode.mpImplMapMode->mnRefCount++;

    // Wenn es keine statischen ImpDaten sind, dann loeschen, wenn es
    // die letzte Referenz ist, sonst Referenzcounter decrementieren
    if ( mpImplMapMode->mnRefCount )
    {
        if ( mpImplMapMode->mnRefCount == 1 )
            delete mpImplMapMode;
        else
            mpImplMapMode->mnRefCount--;
    }

    mpImplMapMode = rMapMode.mpImplMapMode;

    return *this;
}

// -----------------------------------------------------------------------

BOOL MapMode::operator==( const MapMode& rMapMode ) const
{
    DBG_CHKTHIS( MapMode, NULL );
    DBG_CHKOBJ( &rMapMode, MapMode, NULL );

    if ( mpImplMapMode == rMapMode.mpImplMapMode )
        return TRUE;

    if ( (mpImplMapMode->meUnit   == rMapMode.mpImplMapMode->meUnit)   &&
         (mpImplMapMode->maOrigin == rMapMode.mpImplMapMode->maOrigin) &&
         (mpImplMapMode->maScaleX == rMapMode.mpImplMapMode->maScaleX) &&
         (mpImplMapMode->maScaleY == rMapMode.mpImplMapMode->maScaleY) )
        return TRUE;
    else
        return FALSE;
}

// -----------------------------------------------------------------------

BOOL MapMode::IsDefault() const
{
    DBG_CHKTHIS( MapMode, NULL );

    ImplMapMode* pDefMapMode = ImplMapMode::ImplGetStaticMapMode( MAP_PIXEL );
    if ( mpImplMapMode == pDefMapMode )
        return TRUE;

    if ( (mpImplMapMode->meUnit   == pDefMapMode->meUnit)   &&
         (mpImplMapMode->maOrigin == pDefMapMode->maOrigin) &&
         (mpImplMapMode->maScaleX == pDefMapMode->maScaleX) &&
         (mpImplMapMode->maScaleY == pDefMapMode->maScaleY) )
        return TRUE;
    else
        return FALSE;
}

// -----------------------------------------------------------------------

SvStream& operator>>( SvStream& rIStm, MapMode& rMapMode )
{
    rMapMode.ImplMakeUnique();
    return (rIStm >> *rMapMode.mpImplMapMode);
}

// -----------------------------------------------------------------------

SvStream& operator<<( SvStream& rOStm, const MapMode& rMapMode )
{
    return (rOStm << *rMapMode.mpImplMapMode);
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
#ifndef _Stroika_Foundation_Common_Compare_inl_
#define _Stroika_Foundation_Common_Compare_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include "../Debug/Assertions.h"

namespace Stroika::Foundation::Common {

    /*
     ********************************************************************************
     ************************* ThreeWayCompare<LT, RT> ******************************
     ********************************************************************************
     */
    template <typename LT, typename RT>
    constexpr Common::strong_ordering ThreeWayCompare (LT&& lhs, RT&& rhs)
    {
        return ThreeWayComparer<LT, RT>{}(forward<LT> (lhs), forward<RT> (rhs));
    }

    /*
     ********************************************************************************
     *************** OptionalThreeWayCompare<T, TCOMPARER> **************************
     ********************************************************************************
     */
    template <typename T, typename TCOMPARER>
    constexpr OptionalThreeWayComparer<T, TCOMPARER>::OptionalThreeWayComparer (const TCOMPARER& comparer)
        : fTComparer_{comparer}
    {
    }
    template <typename T, typename TCOMPARER>
    constexpr strong_ordering OptionalThreeWayComparer<T, TCOMPARER>::operator() (const optional<T>& lhs, const optional<T>& rhs) const
    {
        if (lhs and rhs) {
            return fTComparer_ (*lhs, *rhs);
        }
        if (not lhs and not rhs) {
            return kEqual;
        }
        // treat missing as less than present
        if (lhs) {
            return kGreater;
        }
        else {
            return kLess;
        }
    }

    /*
     ********************************************************************************
     *************************** CompareResultNormalizer ****************************
     ********************************************************************************
     */
    template <typename FROM_INT_TYPE>
    inline strong_ordering CompareResultNormalizer (FROM_INT_TYPE f)
    {
        if (f == 0) {
            return Common::kEqual;
        }
        else {
            Assert (f < 0 or f > 0);
            return f < 0 ? Common::kLess : Common::kGreater;
        }
    }

    /*
     ********************************************************************************
     ****************** IsPotentiallyComparerRelation<FUNCTOR> **********************
     ********************************************************************************
     */
    namespace PRIVATE_ {
        template <typename FUNCTOR_ARG, typename FUNCTOR, typename RESULT = invoke_result_t<FUNCTOR, FUNCTOR_ARG, FUNCTOR_ARG>>
        constexpr bool IsPotentiallyComparerRelation_Helper_ (nullptr_t)
        {
            return Configuration::is_callable<FUNCTOR>::value and is_convertible_v<RESULT, bool>;
        }
        template <typename FUNCTOR_ARG, typename FUNCTOR>
        constexpr bool IsPotentiallyComparerRelation_Helper_ (...)
        {
            return false;
        }
    }
    template <typename FUNCTOR_ARG, typename FUNCTOR>
    constexpr bool IsPotentiallyComparerRelation ()
    {
        return PRIVATE_::IsPotentiallyComparerRelation_Helper_<FUNCTOR_ARG, FUNCTOR> (nullptr);
    }
    template <typename FUNCTOR_ARG, typename FUNCTOR>
    constexpr bool IsPotentiallyComparerRelation (const FUNCTOR&)
    {
        return IsPotentiallyComparerRelation<FUNCTOR_ARG, FUNCTOR> ();
    }

    /*
     ********************************************************************************
     ********************* IsEqualsComparer<COMPARER> *******************************
     ********************************************************************************
     */
    template <typename COMPARER>
    constexpr bool IsEqualsComparer ()
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals;
    }
    template <typename COMPARER>
    constexpr bool IsEqualsComparer (const COMPARER&)
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals;
    }

    /*
     ********************************************************************************
     ********************* IsStrictInOrderComparer<COMPARER> ************************
     ********************************************************************************
     */
    template <typename COMPARER>
    constexpr bool IsStrictInOrderComparer ()
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder;
    }
    template <typename COMPARER>
    constexpr bool IsStrictInOrderComparer (const COMPARER&)
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder;
    }

    /*
     ********************************************************************************
     ********** ComparisonRelationDeclaration<TYPE, ACTUAL_COMPARER> ****************
     ********************************************************************************
     */
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    constexpr ComparisonRelationType ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::kComparisonRelationKind;
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (const ACTUAL_COMPARER& actualComparer)
        : fActualComparer{actualComparer}
    {
    }
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (ACTUAL_COMPARER&& actualComparer)
        : fActualComparer{move (actualComparer)}
    {
    }
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    template <typename LT, typename RT>
    inline constexpr bool ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::operator() (LT&& lhs, RT&& rhs) const
    {
        return fActualComparer (forward<LT> (lhs), forward<RT> (rhs));
    }

    /*
     ********************************************************************************
     **************************** DeclareEqualsComparer *****************************
     ********************************************************************************
     */
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (const FUNCTOR& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{f};
    }
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (FUNCTOR&& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{move (f)};
    }

    /*
     ********************************************************************************
     ********************************* DeclareInOrderComparer ***********************
     ********************************************************************************
     */
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (const FUNCTOR& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{f};
    }
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (FUNCTOR&& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{move (f)};
    }

    /*
     ********************************************************************************
     ********************* InOrderComparerAdapter<BASE_COMPARER> ********************
     ********************************************************************************
     */
    template <typename BASE_COMPARER>
    constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (const BASE_COMPARER& baseComparer)
        : fBASE_COMPARER_{baseComparer}
    {
    }
    template <typename BASE_COMPARER>
    constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (BASE_COMPARER&& baseComparer)
        : fBASE_COMPARER_{move (baseComparer)}
    {
    }
    template <typename BASE_COMPARER>
    template <typename T>
    constexpr inline bool InOrderComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const
    {
        /*
         *  It would  be nice to be able to use switch statement but use constexpr if because
         *  inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05
         */
        constexpr auto kRelationKind  = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind;
        auto           baseComparison = fBASE_COMPARER_ (lhs, rhs);
        if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) {
            return kRelationKind;
        }
        if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) {
            return baseComparison and not fBASE_COMPARER_ (rhs, lhs);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) {
            return baseComparison < 0;
        }
        AssertNotReached ();
        return false;
    }

    /*
     ********************************************************************************
     ********************* EqualsComparerAdapter<BASE_COMPARER> *********************
     ********************************************************************************
     */
    template <typename BASE_COMPARER>
    constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (const BASE_COMPARER& baseComparer)
        : fBASE_COMPARER_{baseComparer}
    {
    }
    template <typename BASE_COMPARER>
    constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (BASE_COMPARER&& baseComparer)
        : fBASE_COMPARER_{move (baseComparer)}
    {
    }
    template <typename BASE_COMPARER>
    template <typename T>
    constexpr bool EqualsComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const
    {
        /*
         *  It would  be nice to be able to use switch statement but use constexpr if because
         *  inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05
         */
        constexpr auto kRelationKind  = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind;
        auto           baseComparison = fBASE_COMPARER_ (lhs, rhs);
        if constexpr (kRelationKind == ComparisonRelationType::eEquals) {
            return baseComparison;
        }
        if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) {
            return not baseComparison and not fBASE_COMPARER_ (rhs, lhs);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) {
            return baseComparison and fBASE_COMPARER_ (rhs, lhs);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) {
            return baseComparison == kEqual;
        }
        AssertNotReached ();
        return false;
    }

    /*
     ********************************************************************************
     ********************* ThreeWayComparerAdapter<BASE_COMPARER> *******************
     ********************************************************************************
     */
    template <typename BASE_COMPARER>
    constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (const BASE_COMPARER& baseComparer)
        : fBASE_COMPARER_{baseComparer}
    {
    }
    template <typename BASE_COMPARER>
    constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (BASE_COMPARER&& baseComparer)
        : fBASE_COMPARER_{move (baseComparer)}
    {
    }
    template <typename BASE_COMPARER>
    template <typename T>
    constexpr strong_ordering ThreeWayComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const
    {
        /*
         *  It would  be nice to be able to use switch statement but use constexpr if because
         *  inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05
         */
        constexpr auto kRelationKind  = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind;
        auto           baseComparison = fBASE_COMPARER_ (lhs, rhs);
        if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) {
            return baseComparison ? kLess : (fBASE_COMPARER_ (rhs, lhs) ? kGreater : kEqual);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) {
            return baseComparison;
        }
        AssertNotReached ();
        return kEqual;
    }

}

#endif /*_Stroika_Foundation_Common_Compare_inl_*/
<commit_msg>rewrote     constexpr bool IsPotentiallyComparerRelation (const FUNCTOR&)<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
#ifndef _Stroika_Foundation_Common_Compare_inl_
#define _Stroika_Foundation_Common_Compare_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include "../Debug/Assertions.h"

namespace Stroika::Foundation::Common {

    /*
     ********************************************************************************
     ************************* ThreeWayCompare<LT, RT> ******************************
     ********************************************************************************
     */
    template <typename LT, typename RT>
    constexpr Common::strong_ordering ThreeWayCompare (LT&& lhs, RT&& rhs)
    {
        return ThreeWayComparer<LT, RT>{}(forward<LT> (lhs), forward<RT> (rhs));
    }

    /*
     ********************************************************************************
     *************** OptionalThreeWayCompare<T, TCOMPARER> **************************
     ********************************************************************************
     */
    template <typename T, typename TCOMPARER>
    constexpr OptionalThreeWayComparer<T, TCOMPARER>::OptionalThreeWayComparer (const TCOMPARER& comparer)
        : fTComparer_{comparer}
    {
    }
    template <typename T, typename TCOMPARER>
    constexpr strong_ordering OptionalThreeWayComparer<T, TCOMPARER>::operator() (const optional<T>& lhs, const optional<T>& rhs) const
    {
        if (lhs and rhs) {
            return fTComparer_ (*lhs, *rhs);
        }
        if (not lhs and not rhs) {
            return kEqual;
        }
        // treat missing as less than present
        if (lhs) {
            return kGreater;
        }
        else {
            return kLess;
        }
    }

    /*
     ********************************************************************************
     *************************** CompareResultNormalizer ****************************
     ********************************************************************************
     */
    template <typename FROM_INT_TYPE>
    inline strong_ordering CompareResultNormalizer (FROM_INT_TYPE f)
    {
        if (f == 0) {
            return Common::kEqual;
        }
        else {
            Assert (f < 0 or f > 0);
            return f < 0 ? Common::kLess : Common::kGreater;
        }
    }

    /*
     ********************************************************************************
     ****************** IsPotentiallyComparerRelation<FUNCTOR> **********************
     ********************************************************************************
     */
    template <typename FUNCTOR_ARG, typename FUNCTOR>
    constexpr bool IsPotentiallyComparerRelation (const FUNCTOR&)
    {
        return std::is_convertible_v<std::invoke_result_t<FUNCTOR, FUNCTOR_ARG, FUNCTOR_ARG>, bool>;
    }

    /*
     ********************************************************************************
     ********************* IsEqualsComparer<COMPARER> *******************************
     ********************************************************************************
     */
    template <typename COMPARER>
    constexpr bool IsEqualsComparer ()
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals;
    }
    template <typename COMPARER>
    constexpr bool IsEqualsComparer (const COMPARER&)
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals;
    }

    /*
     ********************************************************************************
     ********************* IsStrictInOrderComparer<COMPARER> ************************
     ********************************************************************************
     */
    template <typename COMPARER>
    constexpr bool IsStrictInOrderComparer ()
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder;
    }
    template <typename COMPARER>
    constexpr bool IsStrictInOrderComparer (const COMPARER&)
    {
        return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder;
    }

    /*
     ********************************************************************************
     ********** ComparisonRelationDeclaration<TYPE, ACTUAL_COMPARER> ****************
     ********************************************************************************
     */
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    constexpr ComparisonRelationType ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::kComparisonRelationKind;
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (const ACTUAL_COMPARER& actualComparer)
        : fActualComparer{actualComparer}
    {
    }
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (ACTUAL_COMPARER&& actualComparer)
        : fActualComparer{move (actualComparer)}
    {
    }
    template <ComparisonRelationType KIND, typename ACTUAL_COMPARER>
    template <typename LT, typename RT>
    inline constexpr bool ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::operator() (LT&& lhs, RT&& rhs) const
    {
        return fActualComparer (forward<LT> (lhs), forward<RT> (rhs));
    }

    /*
     ********************************************************************************
     **************************** DeclareEqualsComparer *****************************
     ********************************************************************************
     */
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (const FUNCTOR& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{f};
    }
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (FUNCTOR&& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{move (f)};
    }

    /*
     ********************************************************************************
     ********************************* DeclareInOrderComparer ***********************
     ********************************************************************************
     */
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (const FUNCTOR& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{f};
    }
    template <typename FUNCTOR>
    constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (FUNCTOR&& f)
    {
        return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{move (f)};
    }

    /*
     ********************************************************************************
     ********************* InOrderComparerAdapter<BASE_COMPARER> ********************
     ********************************************************************************
     */
    template <typename BASE_COMPARER>
    constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (const BASE_COMPARER& baseComparer)
        : fBASE_COMPARER_{baseComparer}
    {
    }
    template <typename BASE_COMPARER>
    constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (BASE_COMPARER&& baseComparer)
        : fBASE_COMPARER_{move (baseComparer)}
    {
    }
    template <typename BASE_COMPARER>
    template <typename T>
    constexpr inline bool InOrderComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const
    {
        /*
         *  It would  be nice to be able to use switch statement but use constexpr if because
         *  inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05
         */
        constexpr auto kRelationKind  = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind;
        auto           baseComparison = fBASE_COMPARER_ (lhs, rhs);
        if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) {
            return kRelationKind;
        }
        if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) {
            return baseComparison and not fBASE_COMPARER_ (rhs, lhs);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) {
            return baseComparison < 0;
        }
        AssertNotReached ();
        return false;
    }

    /*
     ********************************************************************************
     ********************* EqualsComparerAdapter<BASE_COMPARER> *********************
     ********************************************************************************
     */
    template <typename BASE_COMPARER>
    constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (const BASE_COMPARER& baseComparer)
        : fBASE_COMPARER_{baseComparer}
    {
    }
    template <typename BASE_COMPARER>
    constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (BASE_COMPARER&& baseComparer)
        : fBASE_COMPARER_{move (baseComparer)}
    {
    }
    template <typename BASE_COMPARER>
    template <typename T>
    constexpr bool EqualsComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const
    {
        /*
         *  It would  be nice to be able to use switch statement but use constexpr if because
         *  inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05
         */
        constexpr auto kRelationKind  = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind;
        auto           baseComparison = fBASE_COMPARER_ (lhs, rhs);
        if constexpr (kRelationKind == ComparisonRelationType::eEquals) {
            return baseComparison;
        }
        if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) {
            return not baseComparison and not fBASE_COMPARER_ (rhs, lhs);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) {
            return baseComparison and fBASE_COMPARER_ (rhs, lhs);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) {
            return baseComparison == kEqual;
        }
        AssertNotReached ();
        return false;
    }

    /*
     ********************************************************************************
     ********************* ThreeWayComparerAdapter<BASE_COMPARER> *******************
     ********************************************************************************
     */
    template <typename BASE_COMPARER>
    constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (const BASE_COMPARER& baseComparer)
        : fBASE_COMPARER_{baseComparer}
    {
    }
    template <typename BASE_COMPARER>
    constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (BASE_COMPARER&& baseComparer)
        : fBASE_COMPARER_{move (baseComparer)}
    {
    }
    template <typename BASE_COMPARER>
    template <typename T>
    constexpr strong_ordering ThreeWayComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const
    {
        /*
         *  It would  be nice to be able to use switch statement but use constexpr if because
         *  inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05
         */
        constexpr auto kRelationKind  = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind;
        auto           baseComparison = fBASE_COMPARER_ (lhs, rhs);
        if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) {
            return baseComparison ? kLess : (fBASE_COMPARER_ (rhs, lhs) ? kGreater : kEqual);
        }
        if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) {
            return baseComparison;
        }
        AssertNotReached ();
        return kEqual;
    }

}

#endif /*_Stroika_Foundation_Common_Compare_inl_*/
<|endoftext|>