<commit_before>
#include <xmppstream.h>
#include <xmppserver.h>
#include <tagbuilder.h>

// for debug only
#include <string>
#include <iostream>

using namespace std;

/**
* Конструктор потока
*/
XMPPStream::XMPPStream(XMPPServer *srv, int sock): AsyncXMLStream(sock), server(srv), XMLWriter(1024)
{
	depth = 0;
	builder = new ATTagBuilder();
}

/**
* Деструктор потока
*/
XMPPStream::~XMPPStream()
{
	delete builder;
}

/**
* Запись XML
*/
void XMPPStream::onWriteXML(const char *data, size_t len)
{
	//cout << string(data, len) << endl;
	int r = write(data, len);
	if ( r != len ) onError("write fault");
	cout << "written: " << string(data, len) << endl;
}

/**
* Событие готовности к записи
*
* Вызывается, когда в поток готов принять
* данные для записи без блокировки
*/
void XMPPStream::onWrite()
{
	cerr << "not implemented XMPPStream::onWrite()" << endl;
}

/**
* Событие закрытие соединения
*
* Вызывается если peer закрыл соединение
*/
void XMPPStream::onShutdown()
{
	AsyncXMLStream::onShutdown();
	XMLWriter::flush();
	cerr << "[TestStream]: peer shutdown connection" << endl;
	if ( shutdown(fd, SHUT_RDWR) != 0 )
	{
		stderror();
	}
	server->daemon->removeObject(this);
	delete this;
}

/**
* Обработчик открытия тега
*/
void XMPPStream::onStartElement(const std::string &name, const attributtes_t &attributes)
{
	depth ++;
	switch ( depth )
	{
	case 1:
		onStartStream(name, attributes);
		break;
	case 2: // начало станзы
		builder->startElement(name, attributes, depth);
	break;
	default: // добавить тег в станзу
		builder->startElement(name, attributes, depth);
		cout << "onStartElement(" << name << ")" << endl;
	}
}

/**
* Обработчик символьных данных
*/
void XMPPStream::onCharacterData(const std::string &cdata)
{
	builder->characterData(cdata);
	cout << "cdata: " << cdata << endl;
}

/**
* Обработчик закрытия тега
*/
void XMPPStream::onEndElement(const std::string &name)
{
	switch (depth)
	{
	case 1:
		onEndStream();
		break;
	case 2:
		builder->endElement(name);
		onStanza(builder->fetchResult());
		if ( name == "auth" )
		{
			startElement("success");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
			endElement("success");
			flush();
			resetWriter();
			state = authorized;
			resetParser();
			depth = 0;
			return;
		}
	default:
		builder->endElement(name);
		cout << "onEndElement(" << name << ")" << endl;
	}
	depth --;
}

/**
* Обработчик станз
*/
void XMPPStream::onStanza(ATXmlTag *tag)
{
	cout << "stanza: " << tag->name() << endl;
}

/**
* Событие: начало потока
*/
void XMPPStream::onStartStream(const std::string &name, const attributes_t &attributes)
{
	cout << "new stream" << endl;
	initXML();
	startElement("stream:stream");
	setAttribute("xmlns", "jabber:client");
	setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
	setAttribute("id", "123456"); // Требования к id — непредсказуемость и уникальность
	setAttribute("from", "localhost");
	setAttribute("version", "1.0");
	setAttribute("xml:lang", "en");

	startElement("stream:features");
	if ( state = init )
	{
		startElement("mechanisms");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
			addElement("mechanism", "PLAIN");
		endElement("mechanisms");
		startElement("register");
			setAttribute("xmlns", "http://jabber.org/features/iq-register");
		endElement("register");
	}
	else
	{
		startElement("bind");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-bind");
		endElement("bind");
		startElement("session");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-session");
		endElement("session");
	}
	endElement("stream:features");
	flush();
}

/**
* Событие: конец потока
*/
void XMPPStream::onEndStream()
{
	cout << "session closed" << endl;
	endElement("stream:stream");
}
<commit_msg>fix segmentation fault<commit_after>
#include <xmppstream.h>
#include <xmppserver.h>
#include <tagbuilder.h>

// for debug only
#include <string>
#include <iostream>

using namespace std;

/**
* Конструктор потока
*/
XMPPStream::XMPPStream(XMPPServer *srv, int sock): AsyncXMLStream(sock), server(srv), XMLWriter(1024)
{
	depth = 0;
	builder = new ATTagBuilder();
}

/**
* Деструктор потока
*/
XMPPStream::~XMPPStream()
{
	delete builder;
}

/**
* Запись XML
*/
void XMPPStream::onWriteXML(const char *data, size_t len)
{
	//cout << string(data, len) << endl;
	int r = write(data, len);
	if ( r != len ) onError("write fault");
	cout << "written: " << string(data, len) << endl;
}

/**
* Событие готовности к записи
*
* Вызывается, когда в поток готов принять
* данные для записи без блокировки
*/
void XMPPStream::onWrite()
{
	cerr << "not implemented XMPPStream::onWrite()" << endl;
}

/**
* Событие закрытие соединения
*
* Вызывается если peer закрыл соединение
*/
void XMPPStream::onShutdown()
{
	AsyncXMLStream::onShutdown();
	XMLWriter::flush();
	cerr << "[TestStream]: peer shutdown connection" << endl;
	if ( shutdown(fd, SHUT_RDWR) != 0 )
	{
		stderror();
	}
	server->daemon->removeObject(this);
	delete this;
}

/**
* Обработчик открытия тега
*/
void XMPPStream::onStartElement(const std::string &name, const attributtes_t &attributes)
{
	depth ++;
	switch ( depth )
	{
	case 1:
		onStartStream(name, attributes);
		break;
	case 2: // начало станзы
		builder->startElement(name, attributes, depth);
	break;
	default: // добавить тег в станзу
		builder->startElement(name, attributes, depth);
		cout << "onStartElement(" << name << ")" << endl;
	}
}

/**
* Обработчик символьных данных
*/
void XMPPStream::onCharacterData(const std::string &cdata)
{
	builder->characterData(cdata);
	cout << "cdata: " << cdata << endl;
}

/**
* Обработчик закрытия тега
*/
void XMPPStream::onEndElement(const std::string &name)
{
	switch (depth)
	{
	case 1:
		onEndStream();
		break;
	case 2:
		builder->endElement(name);
		onStanza(builder->fetchResult());
		if ( name == "auth" )
		{
			startElement("success");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
			endElement("success");
			flush();
			resetWriter();
			state = authorized;
			resetParser();
			depth = 0;
			return;
		}
		break;
	default:
		builder->endElement(name);
		cout << "onEndElement(" << name << ")" << endl;
	}
	depth --;
}

/**
* Обработчик станз
*/
void XMPPStream::onStanza(ATXmlTag *tag)
{
	cout << "stanza: " << tag->name() << endl;
}

/**
* Событие: начало потока
*/
void XMPPStream::onStartStream(const std::string &name, const attributes_t &attributes)
{
	cout << "new stream" << endl;
	initXML();
	startElement("stream:stream");
	setAttribute("xmlns", "jabber:client");
	setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
	setAttribute("id", "123456"); // Требования к id — непредсказуемость и уникальность
	setAttribute("from", "localhost");
	setAttribute("version", "1.0");
	setAttribute("xml:lang", "en");

	startElement("stream:features");
	if ( state = init )
	{
		startElement("mechanisms");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
			addElement("mechanism", "PLAIN");
		endElement("mechanisms");
		startElement("register");
			setAttribute("xmlns", "http://jabber.org/features/iq-register");
		endElement("register");
	}
	else
	{
		startElement("bind");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-bind");
		endElement("bind");
		startElement("session");
			setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-session");
		endElement("session");
	}
	endElement("stream:features");
	flush();
}

/**
* Событие: конец потока
*/
void XMPPStream::onEndStream()
{
	cout << "session closed" << endl;
	endElement("stream:stream");
}
<|endoftext|>


<commit_before>/*********************************
** Tsunagari Tile Engine        **
** world.cpp                    **
** Copyright 2011-2012 OmegaSDG **
*********************************/

#include <Gosu/Image.hpp>
#include <Gosu/Utility.hpp>

#include "area-tmx.h"
#include "log.h"
#include "python.h"
#include "timeout.h"
#include "window.h"
#include "world.h"
#include "xml.h"

#define ASSERT(x)  if (!(x)) return false

static World* globalWorld = NULL;

World* World::instance()
{
	return globalWorld;
}

World::World()
	: lastTime(0), total(0), music(new Music()), redraw(false),
          userPaused(false), paused(0)
{
	globalWorld = this;
	pythonSetGlobal("World", this);
}

World::~World()
{
}

bool World::init()
{
	ASSERT(processDescriptor()); // Try to load in descriptor.
	ASSERT(pauseInfo = rc->getImage("resource/pause_overlay.png"));

	ASSERT(player.init(playerEntity));
	player.setPhase("down");

	pythonSetGlobal("Player", (Entity*)&player);

	view.reset(new Viewport(viewportSz));
	view->trackEntity(&player);

	loadScript.invoke();

	Area* area = getArea(startArea);
	ASSERT(area != NULL);
	focusArea(area, startCoords);

	return true;
}

const std::string& World::getName() const
{
	return name;
}

time_t World::time() const
{
	return total;
}

void World::buttonDown(const Gosu::Button btn)
{
	switch (btn.id()) {
	case Gosu::kbEscape:
		userPaused = !userPaused;
		setPaused(userPaused);
		redraw = true;
		break;
	default:
		if (!paused)
			area->buttonDown(btn);
		break;
	}
}

void World::buttonUp(const Gosu::Button btn)
{
	switch (btn.id()) {
	case Gosu::kbEscape:
		break;
	default:
		if (!paused)
			area->buttonUp(btn);
		break;
	}
}

void World::draw()
{
	redraw = false;

	GameWindow& window = GameWindow::instance();
	Gosu::Graphics& graphics = window.graphics();

	int clips = pushLetterbox();
	graphics.pushTransform(getTransform());

	area->draw();

	graphics.popTransform();
	popLetterbox(clips);

	if (userPaused) {
		unsigned ww = graphics.width();
		unsigned wh = graphics.height();
		unsigned iw = pauseInfo->width();
		unsigned ih = pauseInfo->height();

		Gosu::Color darken(127, 0, 0, 0);
		double top = std::numeric_limits<double>::max();
		drawRect(0, ww, 0, wh, darken, top);
		pauseInfo->draw(ww/2 - iw/2, wh/2 - ih/2, top);
	}
}

bool World::needsRedraw() const
{
	if (redraw)
		return true;
	if (!paused && area->needsRedraw())
		return true;
	return false;
}

void World::update(time_t now)
{
	time_t dt = calculateDt(now);
	if (!paused) {
		total += dt;
		tick(dt);
	}
}

void World::tick(unsigned long dt)
{
	updateTimeouts();
	area->tick(dt);
}

void World::turn()
{
	if (conf.moveMode == TURN) {
		updateTimeouts();
		area->turn();
	}
}

Area* World::getArea(const std::string& filename)
{
	AreaMap::iterator entry = areas.find(filename);
	if (entry != areas.end())
		return entry->second;

	Area* newArea = new AreaTMX(view.get(), &player, music.get(), filename);

	if (!newArea->init())
		newArea = NULL;
	areas[filename] = newArea;
	return newArea;
}

Area* World::getFocusedArea()
{
	return area;
}

void World::focusArea(Area* area, int x, int y, double z)
{
	focusArea(area, vicoord(x, y, z));
}

void World::focusArea(Area* area, vicoord playerPos)
{
	this->area = area;
	player.setArea(area);
	player.setTileCoords(playerPos);
	view->setArea(area);
	area->focus();
}

void World::setPaused(bool b)
{
	paused += b ? 1 : -1;

	if (paused)
		music->setPaused(true);
	else
		music->setPaused(false);
}

void World::runAreaLoadScript(Area* area)
{
	pythonSetGlobal("Area", area);
	areaLoadScript.invoke();
}

time_t World::calculateDt(time_t now)
{
	if (lastTime == 0) {
		lastTime = now;
		return 0;
	}

	time_t dt = now - lastTime;
	lastTime = now;
	return dt;
}

int World::pushLetterbox()
{
	GameWindow& w = GameWindow::instance();
	Gosu::Graphics& g = w.graphics();

	// Aspect ratio correction.
	rvec2 sz = view->getPhysRes();
	rvec2 lb = -1 * view->getLetterboxOffset();

	g.beginClipping(lb.x, lb.y, sz.x - 2 * lb.x, sz.y - 2 * lb.y);
	int clips = 1;

	// Map bounds.
	rvec2 scale = view->getScale();
	rvec2 virtScroll = view->getMapOffset();
	rvec2 padding = view->getLetterboxOffset();

	rvec2 physScroll = -1 * virtScroll * scale + padding;

	bool loopX = area->loopsInX();
	bool loopY = area->loopsInY();

	if (!loopX && physScroll.x > 0) {
		// Boxes on left-right.
		g.beginClipping(physScroll.x, 0, sz.x - 2 * physScroll.x, sz.x);
		clips++;
	}
	if (!loopY && physScroll.y > 0) {
		// Boxes on top-bottom.
		g.beginClipping(0, physScroll.y, sz.x, sz.y - 2 * physScroll.y);
		clips++;
	}

	return clips;
}

void World::popLetterbox(int clips)
{
	GameWindow& w = GameWindow::instance();
	for (; clips; clips--)
		w.graphics().endClipping();
}

void World::drawRect(double x1, double x2, double y1, double y2,
                       Gosu::Color c, double z)
{
	GameWindow& window = GameWindow::instance();
	window.graphics().drawQuad(
		x1, y1, c,
		x2, y1, c,
		x2, y2, c,
		x1, y2, c,
		z
	);
}

Gosu::Transform World::getTransform()
{
	rvec2 scale = view->getScale();
	rvec2 scroll = view->getMapOffset();
	rvec2 padding = view->getLetterboxOffset();
	Gosu::Transform t = { {
		scale.x, 0,       0, 0,
		0,       scale.y, 0, 0,
		0,       0,       1, 0,
		scale.x * -scroll.x - padding.x,
		scale.y * -scroll.y - padding.y, 0, 1
	} };
	return t;
}

bool World::processDescriptor()
{
	XMLRef doc;
	XMLNode root;

	rc = Resourcer::instance();
	ASSERT(doc = rc->getXMLDoc("world.conf", "world.dtd"));
	ASSERT(root = doc->root()); // <world>

	for (XMLNode child = root.childrenNode(); child; child = child.next()) {
		if (child.is("info")) {
			ASSERT(processInfo(child));
		}
		else if (child.is("init")) {
			ASSERT(processInit(child));
		}
		else if (child.is("script")) {
			ASSERT(processScript(child));
		}
		else if (child.is("input")) {
			ASSERT(processInput(child));
		}
	}

	if (conf.moveMode == TURN &&
	   (conf.persistInit == 0 || conf.persistCons == 0)) {
		Log::fatal("world.conf", "\"input->persist\" option required in \"turn\" mode");
		return false;
	}

	return true;
}

bool World::processInfo(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		if (node.is("name")) {
			name = node.content();
			GameWindow::instance().setCaption(Gosu::widen(name));
		} else if (node.is("author")) {
			author = node.content();
		} else if (node.is("version")) {
			version = atof(node.content().c_str());
		}
	}
	return true;
}

bool World::processInit(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		if (node.is("area")) {
			startArea = node.content();
		}
		else if (node.is("player")) {
			playerEntity = node.content();
		}
		else if (node.is("mode")) {
			std::string str = node.content();
			if (str == "turn")
				conf.moveMode = TURN;
			else if (str == "tile")
				conf.moveMode = TILE;
			else if (str == "notile")
				conf.moveMode = NOTILE;
		}
		else if (node.is("coords")) {
			if (!node.intAttr("x", &startCoords.x) ||
			    !node.intAttr("y", &startCoords.y) ||
			    !node.doubleAttr("z", &startCoords.z))
				return false;
		}
		else if (node.is("viewport")) {
			if (!node.intAttr("width", &viewportSz.x) ||
			    !node.intAttr("height", &viewportSz.y))
				return false;
		}
	}
	return true;
}

bool World::processScript(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		std::string filename = node.content();
		ScriptInst script(filename);

		if (node.is("on_init")) {
			if (!script.validate("world.conf"))
				return false;
			loadScript = filename;
		} else if (node.is("on_area_init")) {
			if (!script.validate("world.conf"))
				return false;
			areaLoadScript = filename;
		}
	}
	return true;
}

bool World::processInput(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		if (node.is("persist")) {
			if (!node.intAttr("init", &conf.persistInit) ||
				!node.intAttr("cons", &conf.persistCons))
			    return false;
		}
	}
	return true;
}

void exportWorld()
{
	using namespace boost::python;

	class_<World> ("World", no_init)
		.def("area", &World::getArea,
			return_value_policy<reference_existing_object>())
		.def("focus",
			static_cast<void (World::*) (Area*,int,int,double)>
			(&World::focusArea))
		;
}

<commit_msg>darken whenever paused<commit_after>/*********************************
** Tsunagari Tile Engine        **
** world.cpp                    **
** Copyright 2011-2012 OmegaSDG **
*********************************/

#include <Gosu/Image.hpp>
#include <Gosu/Utility.hpp>

#include "area-tmx.h"
#include "log.h"
#include "python.h"
#include "timeout.h"
#include "window.h"
#include "world.h"
#include "xml.h"

#define ASSERT(x)  if (!(x)) return false

static World* globalWorld = NULL;

World* World::instance()
{
	return globalWorld;
}

World::World()
	: lastTime(0), total(0), music(new Music()), redraw(false),
          userPaused(false), paused(0)
{
	globalWorld = this;
	pythonSetGlobal("World", this);
}

World::~World()
{
}

bool World::init()
{
	ASSERT(processDescriptor()); // Try to load in descriptor.
	ASSERT(pauseInfo = rc->getImage("resource/pause_overlay.png"));

	ASSERT(player.init(playerEntity));
	player.setPhase("down");

	pythonSetGlobal("Player", (Entity*)&player);

	view.reset(new Viewport(viewportSz));
	view->trackEntity(&player);

	loadScript.invoke();

	Area* area = getArea(startArea);
	ASSERT(area != NULL);
	focusArea(area, startCoords);

	return true;
}

const std::string& World::getName() const
{
	return name;
}

time_t World::time() const
{
	return total;
}

void World::buttonDown(const Gosu::Button btn)
{
	switch (btn.id()) {
	case Gosu::kbEscape:
		userPaused = !userPaused;
		setPaused(userPaused);
		redraw = true;
		break;
	default:
		if (!paused)
			area->buttonDown(btn);
		break;
	}
}

void World::buttonUp(const Gosu::Button btn)
{
	switch (btn.id()) {
	case Gosu::kbEscape:
		break;
	default:
		if (!paused)
			area->buttonUp(btn);
		break;
	}
}

void World::draw()
{
	redraw = false;

	GameWindow& window = GameWindow::instance();
	Gosu::Graphics& graphics = window.graphics();

	int clips = pushLetterbox();
	graphics.pushTransform(getTransform());

	area->draw();

	graphics.popTransform();
	popLetterbox(clips);

	if (paused) {
		unsigned ww = graphics.width();
		unsigned wh = graphics.height();
		Gosu::Color darken(127, 0, 0, 0);
		double top = std::numeric_limits<double>::max();

		drawRect(0, ww, 0, wh, darken, top);

		if (userPaused) {
			unsigned iw = pauseInfo->width();
			unsigned ih = pauseInfo->height();

			pauseInfo->draw(ww/2 - iw/2, wh/2 - ih/2, top);
		}
	}

}

bool World::needsRedraw() const
{
	if (redraw)
		return true;
	if (!paused && area->needsRedraw())
		return true;
	return false;
}

void World::update(time_t now)
{
	time_t dt = calculateDt(now);
	if (!paused) {
		total += dt;
		tick(dt);
	}
}

void World::tick(unsigned long dt)
{
	updateTimeouts();
	area->tick(dt);
}

void World::turn()
{
	if (conf.moveMode == TURN) {
		updateTimeouts();
		area->turn();
	}
}

Area* World::getArea(const std::string& filename)
{
	AreaMap::iterator entry = areas.find(filename);
	if (entry != areas.end())
		return entry->second;

	Area* newArea = new AreaTMX(view.get(), &player, music.get(), filename);

	if (!newArea->init())
		newArea = NULL;
	areas[filename] = newArea;
	return newArea;
}

Area* World::getFocusedArea()
{
	return area;
}

void World::focusArea(Area* area, int x, int y, double z)
{
	focusArea(area, vicoord(x, y, z));
}

void World::focusArea(Area* area, vicoord playerPos)
{
	this->area = area;
	player.setArea(area);
	player.setTileCoords(playerPos);
	view->setArea(area);
	area->focus();
}

void World::setPaused(bool b)
{
	paused += b ? 1 : -1;

	if (paused)
		music->setPaused(true);
	else
		music->setPaused(false);
}

void World::runAreaLoadScript(Area* area)
{
	pythonSetGlobal("Area", area);
	areaLoadScript.invoke();
}

time_t World::calculateDt(time_t now)
{
	if (lastTime == 0) {
		lastTime = now;
		return 0;
	}

	time_t dt = now - lastTime;
	lastTime = now;
	return dt;
}

int World::pushLetterbox()
{
	GameWindow& w = GameWindow::instance();
	Gosu::Graphics& g = w.graphics();

	// Aspect ratio correction.
	rvec2 sz = view->getPhysRes();
	rvec2 lb = -1 * view->getLetterboxOffset();

	g.beginClipping(lb.x, lb.y, sz.x - 2 * lb.x, sz.y - 2 * lb.y);
	int clips = 1;

	// Map bounds.
	rvec2 scale = view->getScale();
	rvec2 virtScroll = view->getMapOffset();
	rvec2 padding = view->getLetterboxOffset();

	rvec2 physScroll = -1 * virtScroll * scale + padding;

	bool loopX = area->loopsInX();
	bool loopY = area->loopsInY();

	if (!loopX && physScroll.x > 0) {
		// Boxes on left-right.
		g.beginClipping(physScroll.x, 0, sz.x - 2 * physScroll.x, sz.x);
		clips++;
	}
	if (!loopY && physScroll.y > 0) {
		// Boxes on top-bottom.
		g.beginClipping(0, physScroll.y, sz.x, sz.y - 2 * physScroll.y);
		clips++;
	}

	return clips;
}

void World::popLetterbox(int clips)
{
	GameWindow& w = GameWindow::instance();
	for (; clips; clips--)
		w.graphics().endClipping();
}

void World::drawRect(double x1, double x2, double y1, double y2,
                       Gosu::Color c, double z)
{
	GameWindow& window = GameWindow::instance();
	window.graphics().drawQuad(
		x1, y1, c,
		x2, y1, c,
		x2, y2, c,
		x1, y2, c,
		z
	);
}

Gosu::Transform World::getTransform()
{
	rvec2 scale = view->getScale();
	rvec2 scroll = view->getMapOffset();
	rvec2 padding = view->getLetterboxOffset();
	Gosu::Transform t = { {
		scale.x, 0,       0, 0,
		0,       scale.y, 0, 0,
		0,       0,       1, 0,
		scale.x * -scroll.x - padding.x,
		scale.y * -scroll.y - padding.y, 0, 1
	} };
	return t;
}

bool World::processDescriptor()
{
	XMLRef doc;
	XMLNode root;

	rc = Resourcer::instance();
	ASSERT(doc = rc->getXMLDoc("world.conf", "world.dtd"));
	ASSERT(root = doc->root()); // <world>

	for (XMLNode child = root.childrenNode(); child; child = child.next()) {
		if (child.is("info")) {
			ASSERT(processInfo(child));
		}
		else if (child.is("init")) {
			ASSERT(processInit(child));
		}
		else if (child.is("script")) {
			ASSERT(processScript(child));
		}
		else if (child.is("input")) {
			ASSERT(processInput(child));
		}
	}

	if (conf.moveMode == TURN &&
	   (conf.persistInit == 0 || conf.persistCons == 0)) {
		Log::fatal("world.conf", "\"input->persist\" option required in \"turn\" mode");
		return false;
	}

	return true;
}

bool World::processInfo(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		if (node.is("name")) {
			name = node.content();
			GameWindow::instance().setCaption(Gosu::widen(name));
		} else if (node.is("author")) {
			author = node.content();
		} else if (node.is("version")) {
			version = atof(node.content().c_str());
		}
	}
	return true;
}

bool World::processInit(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		if (node.is("area")) {
			startArea = node.content();
		}
		else if (node.is("player")) {
			playerEntity = node.content();
		}
		else if (node.is("mode")) {
			std::string str = node.content();
			if (str == "turn")
				conf.moveMode = TURN;
			else if (str == "tile")
				conf.moveMode = TILE;
			else if (str == "notile")
				conf.moveMode = NOTILE;
		}
		else if (node.is("coords")) {
			if (!node.intAttr("x", &startCoords.x) ||
			    !node.intAttr("y", &startCoords.y) ||
			    !node.doubleAttr("z", &startCoords.z))
				return false;
		}
		else if (node.is("viewport")) {
			if (!node.intAttr("width", &viewportSz.x) ||
			    !node.intAttr("height", &viewportSz.y))
				return false;
		}
	}
	return true;
}

bool World::processScript(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		std::string filename = node.content();
		ScriptInst script(filename);

		if (node.is("on_init")) {
			if (!script.validate("world.conf"))
				return false;
			loadScript = filename;
		} else if (node.is("on_area_init")) {
			if (!script.validate("world.conf"))
				return false;
			areaLoadScript = filename;
		}
	}
	return true;
}

bool World::processInput(XMLNode node)
{
	for (node = node.childrenNode(); node; node = node.next()) {
		if (node.is("persist")) {
			if (!node.intAttr("init", &conf.persistInit) ||
				!node.intAttr("cons", &conf.persistCons))
			    return false;
		}
	}
	return true;
}

void exportWorld()
{
	using namespace boost::python;

	class_<World> ("World", no_init)
		.def("area", &World::getArea,
			return_value_policy<reference_existing_object>())
		.def("focus",
			static_cast<void (World::*) (Area*,int,int,double)>
			(&World::focusArea))
		;
}

<|endoftext|>


<commit_before>// This macro draws 4 Latex-style formula in a canvas and prints the canvas
// as a Postscript file.
// Note that this macro relies on a first implementation of the TLatex class.
// There are still some discrepancies between the result on the screen
// and the result on Postscript.
{
   gROOT->Reset();
   TCanvas *c1 = new TCanvas("c1");
   TLatex l;
   l.SetTextAlign(23);
   l.SetTextSize(0.1);
   l.DrawLatex(0.5,0.95,"e^{+}e^{-}#rightarrowZ^{0}#rightarrowI#bar{I}, q#bar{q}");
   l.DrawLatex(0.5,0.75,"|#vec{a}#bullet#vec{b}|=#Sigmaa^{i}_{jk}+b^{bj}_{i}");
   l.DrawLatex(0.5,0.5,"i(#partial_{#mu}#bar{#psi}#gamma^{#mu}+m#bar{#psi}=0#Leftrightarrow(#Box+m^{2})#psi=0");
   l.DrawLatex(0.5,0.3,"L_{em}=eJ^{#mu}_{em}A_{#mu} , J^{#mu}_{em}=#bar{I}#gamma_{#mu}I , M^{j}_{i}=#SigmaA_{#alpha}#tau^{#alphaj}_{i}");
   c1->Print("latex2.ps");
}
<commit_msg>Add a missing parenthesis in one expression.<commit_after>// This macro draws 4 Latex-style formula in a canvas and prints the canvas
// as a Postscript file.
// Note that this macro relies on a first implementation of the TLatex class.
// There are still some discrepancies between the result on the screen
// and the result on Postscript.
{
   gROOT->Reset();
   TCanvas *c1 = new TCanvas("c1");
   TLatex l;
   l.SetTextAlign(23);
   l.SetTextSize(0.1);
   l.DrawLatex(0.5,0.95,"e^{+}e^{-}#rightarrowZ^{0}#rightarrowI#bar{I}, q#bar{q}");
   l.DrawLatex(0.5,0.75,"|#vec{a}#bullet#vec{b}|=#Sigmaa^{i}_{jk}+b^{bj}_{i}");
   l.DrawLatex(0.5,0.5,"i(#partial_{#mu}#bar{#psi}#gamma^{#mu}+m#bar{#psi})=0#Leftrightarrow(#Box+m^{2})#psi=0");
   l.DrawLatex(0.5,0.3,"L_{em}=eJ^{#mu}_{em}A_{#mu} , J^{#mu}_{em}=#bar{I}#gamma_{#mu}I , M^{j}_{i}=#SigmaA_{#alpha}#tau^{#alphaj}_{i}");
   c1->Print("latex2.ps");
}
<|endoftext|>


<commit_before>#include "json.h"
#include "misc.h"
#include <sstream>
#include <stdexcept>

namespace snf {
namespace json {

object &
object::add(const std::string &key, const value &val)
{
	insert(std::make_pair(string_unescape(key), val));
	return *this;
}

object &
object::add(const value_type &kvpair)
{
	insert(kvpair);
	return *this;
}

bool
object::contains(const std::string &key) const
{
	return (end() != find(string_unescape(key)));
}

const value &
object::get(const std::string &key) const
{
	auto i = find(string_unescape(key));
	if (i == end()) {
		std::ostringstream oss;
		oss << "key " << key << " not found in JSON object!";
		throw std::runtime_error(oss.str());
	} else {
		return i->second;
	}
}

const value &
object::get(const std::string &key, const value &default_value) const
{
	auto i = find(string_unescape(key));
	if (i == end()) {
		return default_value;
	} else {
		return i->second;
	}
}

std::string
object::str(const value_type &kvpair, bool pretty, int indent) const
{
	std::ostringstream oss;

	oss	<< "\""
		<< string_escape(kvpair.first)
		<< "\" : "
		<< kvpair.second.str(pretty, indent);

	return oss.str();
}

std::string
object::str(bool pretty, int indent) const
{
	std::ostringstream oss;

	oss << "{";

	for (auto i = begin(); i != end(); ++i) {
		if (i != begin()) {
			oss << ",";
		}

		if (pretty)
			oss << std::endl << std::string(indent + 2, ' ');
		else
			oss << " ";

		oss << str(*i, pretty, indent + 2);
	}

	if (pretty)
		oss << std::endl << std::string(indent, ' ');
	else
		oss << " ";

	oss << "}";

	return oss.str();
}

array &
array::add(const value &elem)
{
	emplace_back(elem);
	return *this;
}

const value &
array::get(size_t index) const
{
	return at(index);
}

const value &
array::get(size_t index, const value &default_value) const
{
	if (valid(index)) {
		return at(index);
	} else {
		return default_value;
	}
}

std::string
array::str(bool pretty, int indent) const
{
	std::ostringstream oss;

	oss << "[";

	for (auto i = begin(); i != end(); ++i) {
		if (i != begin()) {
			oss << ",";
		}

		if (pretty)
			oss << std::endl << std::string(indent + 2, ' ');
		else
			oss << " ";

		oss << i->str(pretty, indent + 2);
	}

	if (pretty)
		oss << std::endl << std::string(indent, ' ');
	else
		oss << " ";

	oss << "]";

	return oss.str();
}

void
value::clean(value &v)
{
	switch (v.m_type) {
	case T::T_STRING:
		delete v.m_val.s_val;
		break;

	case T::T_OBJECT:
		delete v.m_val.o_val;
		break;

	case T::T_ARRAY:
		delete v.m_val.a_val;
		break;

	default:
		break;
	}
	v.m_type = T::T_NULL;
	v.m_val.i_val = 0L;
}

void
value::copy(const value &v)
{
	switch (v.m_type) {
	case T::T_BOOLEAN:
		m_val.b_val = v.m_val.b_val;
		break;

	case T::T_INTEGER:
		m_val.i_val = v.m_val.i_val;
		break;

	case T::T_REAL:
		m_val.d_val = v.m_val.d_val;
		break;

	case T::T_STRING:
		m_val.s_val = new std::string(*v.m_val.s_val);
		break;

	case T::T_OBJECT:
		m_val.o_val = new object(*v.m_val.o_val);
		break;

	case T::T_ARRAY:
		m_val.a_val = new array(*v.m_val.a_val);
		break;

	default:
		m_val.i_val = 0;
		break;
	}
	m_type = v.m_type;
}

void
value::move(value &&v)
{
	clean(*this);

	m_type = v.m_type;

	switch (v.m_type) {
	case T::T_BOOLEAN:
		m_val.b_val = v.m_val.b_val;
		break;

	case T::T_INTEGER:
		m_val.i_val = v.m_val.i_val;
		break;

	case T::T_REAL:
		m_val.d_val = v.m_val.d_val;
		break;

	case T::T_STRING:
		m_val.s_val = v.m_val.s_val;
		v.m_val.s_val = nullptr;
		break;

	case T::T_OBJECT:
		m_val.o_val = v.m_val.o_val;
		v.m_val.o_val = nullptr;
		break;

	case T::T_ARRAY:
		m_val.a_val = v.m_val.a_val;
		v.m_val.o_val = nullptr;
		break;

	default:
		m_val.i_val = 0;
		break;
	}

	clean(v);
}

const value &
value::operator= (std::nullptr_t np)
{
	clean(*this);
	return *this;
}

const value &
value::operator= (const object &o)
{
	clean(*this);
	m_type = T::T_OBJECT;
	m_val.o_val = new object(o);
	return *this;
}

const value &
value::operator= (object &&o)
{
	clean(*this);
	m_type = T::T_OBJECT;
	m_val.o_val = new object(std::move(o));
	return *this;
}

const value &
value::operator= (const array &a)
{
	clean(*this);
	m_type = T::T_ARRAY;
	m_val.a_val = new array(a);
	return *this;
}

const value &
value::operator= (array &&a)
{
	clean(*this);
	m_type = T::T_ARRAY;
	m_val.a_val = new array(std::move(a));
	return *this;
}

const value &
value::operator= (const value &v)
{
	if (this != &v)
		copy(v);
	return *this;
}

const value &
value::operator= (value &&v)
{
	if (this != &v)
		move(std::move(v));
	return *this;
}

value &
value::operator[] (const std::string &key)
{
	if (!is_object()) {
		clean(*this);
		m_type = T::T_OBJECT;
		m_val.o_val = new object();
	}
	return m_val.o_val->operator[](key);
}

value &
value::operator[] (size_t index)
{
	if (!is_array()) {
		clean(*this);
		m_type = T::T_ARRAY;
		m_val.a_val = new array();
	}
	return m_val.a_val->operator[](index);
}

bool
value::get_boolean() const
{
	if (is_boolean()) {
		return m_val.b_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

int64_t
value::get_integer() const
{
	if (is_integer()) {
		return m_val.i_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

double
value::get_real() const
{
	if (is_real()) {
		return m_val.d_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

const std::string &
value::get_string() const
{
	if (is_string()) {
		return *m_val.s_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

const object &
value::get_object() const
{
	if (is_object()) {
		return *m_val.o_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

const array &
value::get_array() const
{
	if (is_array()) {
		return *m_val.a_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

std::string
value::str(bool pretty, int indent) const
{
	std::ostringstream oss;

	switch (m_type) {
	case T::T_NULL:
		oss << "null";
		break;

	case T::T_BOOLEAN:
		oss << std::boolalpha << m_val.b_val << std::noboolalpha;
		break;

	case T::T_INTEGER:
		oss << m_val.i_val;
		break;

	case T::T_REAL:
		oss << m_val.d_val;
		break;

	case T::T_STRING:
		oss << "\"" << string_escape(*m_val.s_val) << "\"";
		break;

	case T::T_OBJECT:
		oss << m_val.o_val->str(pretty, indent);
		break;

	case T::T_ARRAY:
		oss << m_val.a_val->str(pretty, indent);
		break;
	}

	return oss.str();
}

} // json
} // snf
<commit_msg>Use out_of_range exception and not runtime_error.<commit_after>#include "json.h"
#include "misc.h"
#include <sstream>
#include <stdexcept>

namespace snf {
namespace json {

object &
object::add(const std::string &key, const value &val)
{
	insert(std::make_pair(string_unescape(key), val));
	return *this;
}

object &
object::add(const value_type &kvpair)
{
	insert(kvpair);
	return *this;
}

bool
object::contains(const std::string &key) const
{
	return (end() != find(string_unescape(key)));
}

const value &
object::get(const std::string &key) const
{
	auto i = find(string_unescape(key));
	if (i == end()) {
		std::ostringstream oss;
		oss << "key " << key << " not found in JSON object!";
		throw std::out_of_range(oss.str());
	} else {
		return i->second;
	}
}

const value &
object::get(const std::string &key, const value &default_value) const
{
	auto i = find(string_unescape(key));
	if (i == end()) {
		return default_value;
	} else {
		return i->second;
	}
}

std::string
object::str(const value_type &kvpair, bool pretty, int indent) const
{
	std::ostringstream oss;

	oss	<< "\""
		<< string_escape(kvpair.first)
		<< "\" : "
		<< kvpair.second.str(pretty, indent);

	return oss.str();
}

std::string
object::str(bool pretty, int indent) const
{
	std::ostringstream oss;

	oss << "{";

	for (auto i = begin(); i != end(); ++i) {
		if (i != begin()) {
			oss << ",";
		}

		if (pretty)
			oss << std::endl << std::string(indent + 2, ' ');
		else
			oss << " ";

		oss << str(*i, pretty, indent + 2);
	}

	if (pretty)
		oss << std::endl << std::string(indent, ' ');
	else
		oss << " ";

	oss << "}";

	return oss.str();
}

array &
array::add(const value &elem)
{
	emplace_back(elem);
	return *this;
}

const value &
array::get(size_t index) const
{
	if (valid(index)) {
		return at(index);
	} else {
		std::ostringstream oss;
		oss << "index " << index << " is out of range in JSON array!";
		throw std::out_of_range(oss.str());
	}
}

const value &
array::get(size_t index, const value &default_value) const
{
	if (valid(index)) {
		return at(index);
	} else {
		return default_value;
	}
}

std::string
array::str(bool pretty, int indent) const
{
	std::ostringstream oss;

	oss << "[";

	for (auto i = begin(); i != end(); ++i) {
		if (i != begin()) {
			oss << ",";
		}

		if (pretty)
			oss << std::endl << std::string(indent + 2, ' ');
		else
			oss << " ";

		oss << i->str(pretty, indent + 2);
	}

	if (pretty)
		oss << std::endl << std::string(indent, ' ');
	else
		oss << " ";

	oss << "]";

	return oss.str();
}

void
value::clean(value &v)
{
	switch (v.m_type) {
	case T::T_STRING:
		delete v.m_val.s_val;
		break;

	case T::T_OBJECT:
		delete v.m_val.o_val;
		break;

	case T::T_ARRAY:
		delete v.m_val.a_val;
		break;

	default:
		break;
	}
	v.m_type = T::T_NULL;
	v.m_val.i_val = 0L;
}

void
value::copy(const value &v)
{
	switch (v.m_type) {
	case T::T_BOOLEAN:
		m_val.b_val = v.m_val.b_val;
		break;

	case T::T_INTEGER:
		m_val.i_val = v.m_val.i_val;
		break;

	case T::T_REAL:
		m_val.d_val = v.m_val.d_val;
		break;

	case T::T_STRING:
		m_val.s_val = new std::string(*v.m_val.s_val);
		break;

	case T::T_OBJECT:
		m_val.o_val = new object(*v.m_val.o_val);
		break;

	case T::T_ARRAY:
		m_val.a_val = new array(*v.m_val.a_val);
		break;

	default:
		m_val.i_val = 0;
		break;
	}
	m_type = v.m_type;
}

void
value::move(value &&v)
{
	clean(*this);

	m_type = v.m_type;

	switch (v.m_type) {
	case T::T_BOOLEAN:
		m_val.b_val = v.m_val.b_val;
		break;

	case T::T_INTEGER:
		m_val.i_val = v.m_val.i_val;
		break;

	case T::T_REAL:
		m_val.d_val = v.m_val.d_val;
		break;

	case T::T_STRING:
		m_val.s_val = v.m_val.s_val;
		v.m_val.s_val = nullptr;
		break;

	case T::T_OBJECT:
		m_val.o_val = v.m_val.o_val;
		v.m_val.o_val = nullptr;
		break;

	case T::T_ARRAY:
		m_val.a_val = v.m_val.a_val;
		v.m_val.o_val = nullptr;
		break;

	default:
		m_val.i_val = 0;
		break;
	}

	clean(v);
}

const value &
value::operator= (std::nullptr_t np)
{
	clean(*this);
	return *this;
}

const value &
value::operator= (const object &o)
{
	clean(*this);
	m_type = T::T_OBJECT;
	m_val.o_val = new object(o);
	return *this;
}

const value &
value::operator= (object &&o)
{
	clean(*this);
	m_type = T::T_OBJECT;
	m_val.o_val = new object(std::move(o));
	return *this;
}

const value &
value::operator= (const array &a)
{
	clean(*this);
	m_type = T::T_ARRAY;
	m_val.a_val = new array(a);
	return *this;
}

const value &
value::operator= (array &&a)
{
	clean(*this);
	m_type = T::T_ARRAY;
	m_val.a_val = new array(std::move(a));
	return *this;
}

const value &
value::operator= (const value &v)
{
	if (this != &v)
		copy(v);
	return *this;
}

const value &
value::operator= (value &&v)
{
	if (this != &v)
		move(std::move(v));
	return *this;
}

value &
value::operator[] (const std::string &key)
{
	if (!is_object()) {
		clean(*this);
		m_type = T::T_OBJECT;
		m_val.o_val = new object();
	}
	return m_val.o_val->operator[](key);
}

value &
value::operator[] (size_t index)
{
	if (!is_array()) {
		clean(*this);
		m_type = T::T_ARRAY;
		m_val.a_val = new array();
	}
	return m_val.a_val->operator[](index);
}

bool
value::get_boolean() const
{
	if (is_boolean()) {
		return m_val.b_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

int64_t
value::get_integer() const
{
	if (is_integer()) {
		return m_val.i_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

double
value::get_real() const
{
	if (is_real()) {
		return m_val.d_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

const std::string &
value::get_string() const
{
	if (is_string()) {
		return *m_val.s_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

const object &
value::get_object() const
{
	if (is_object()) {
		return *m_val.o_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

const array &
value::get_array() const
{
	if (is_array()) {
		return *m_val.a_val;
	} else {
		throw std::logic_error("invalid JSON value type!");
	}
}

std::string
value::str(bool pretty, int indent) const
{
	std::ostringstream oss;

	switch (m_type) {
	case T::T_NULL:
		oss << "null";
		break;

	case T::T_BOOLEAN:
		oss << std::boolalpha << m_val.b_val << std::noboolalpha;
		break;

	case T::T_INTEGER:
		oss << m_val.i_val;
		break;

	case T::T_REAL:
		oss << m_val.d_val;
		break;

	case T::T_STRING:
		oss << "\"" << string_escape(*m_val.s_val) << "\"";
		break;

	case T::T_OBJECT:
		oss << m_val.o_val->str(pretty, indent);
		break;

	case T::T_ARRAY:
		oss << m_val.a_val->str(pretty, indent);
		break;
	}

	return oss.str();
}

} // json
} // snf
<|endoftext|>


<commit_before>#include <iostream>
#include "mpi_fun.h"
using namespace std;

void mpi_fun_test();

int main(int argc, char** argv)
{
    //MPIInit(argc,argv);
    MPIInitFunnel(argc,argv);

#ifdef MPI_HAO
    if(MPIRank()==0) cout<<"Testing mpi_lib_hao mpi version......\n"<<endl;
#else
    if(MPIRank()==0) cout<<"Testing mpi_lib_hao serial version......\n"<<endl;
#endif

    mpi_fun_test();

    MPIBarrier();
    if(MPIRank()==0) cout<<"\n\nIf these is no warning, we have passed all the test!"<<endl;

    MPIFinalize();
    return 0;
}
<commit_msg>Add space in test_all.cpp<commit_after>#include <iostream>
#include "mpi_fun.h"
using namespace std;

void mpi_fun_test();

int main(int argc, char** argv)
{
    //MPIInit(argc,argv);
    MPIInitFunnel(argc,argv);

#ifdef MPI_HAO
    if(MPIRank()==0) cout<<"\n\n\n=======Testing mpi_lib_hao mpi version=======\n"<<endl;
#else
    if(MPIRank()==0) cout<<"\n\n\n=======Testing mpi_lib_hao serial version=======\n"<<endl;
#endif

    mpi_fun_test();

    MPIBarrier();
    if(MPIRank()==0) cout<<"\n\nIf these is no warning, we have passed all the test!"<<endl;

    MPIFinalize();
    return 0;
}
<|endoftext|>


<commit_before>#include "catch.hpp"
#include "lua/lua.hpp"

using namespace lua;

TEST_CASE("val_test/create", "create test") {
	val v = {
		{"int", 10},
		{"bool",true},
		{"string","foo"},
		{"nil", val::nil()}
	};
	val::table_type values;
	CHECK_NOTHROW(values = v.get<val::table_type>());
	CHECK(values["int"] == 10);
	CHECK(values["bool"] == true);
	CHECK(values["string"] == "foo");
	CHECK(values["nil"] == val::nil());
}

TEST_CASE("val_test/get", "get test") {
	val v1(10);
	CHECK(v1.get<int>() == 10);
	CHECK(v1.get<float>() == 10.0f);
	CHECK(v1.get<bool>() == true);
	CHECK(v1.get<std::string>() == "10");
	CHECK_THROWS(v1.get<void*>());

	val v2("foo");
	CHECK(v2.get<std::string>() == "foo");
	CHECK(v2.get<bool>() == true);
	CHECK_THROWS(v2.get<int>());
	CHECK_THROWS(v2.get<void*>());

	val v3("10");
	CHECK(v3.get<std::string>() == "10");
	CHECK(v3.get<int>() == 10);
	CHECK(v3.get<bool>() == true);
	CHECK_THROWS(v3.get<void*>());

	val v4(true);
	CHECK(v4.get<bool>() == true);
	CHECK(v4.get<int>() == 1);
	CHECK_THROWS(v4.get<std::string>());
	CHECK_THROWS(v4.get<void*>());

	auto nil = val::nil();
	CHECK(nil.get<void*>() == (void*)nullptr);
	CHECK(nil.get<bool>() == false);
	CHECK(nil.get<int>() == 0);
	CHECK_THROWS(nil.get<std::string>());
}

TEST_CASE("val_test/equals", "equals test") {
	int ud;
	CHECK(val(10) == val(10));
	CHECK(val(10) == val(10.0f));
	CHECK(val(10) != val("10"));
	CHECK(val(10) != val(9));
	CHECK(val(10) != val(&ud));
	CHECK(val(10) != val::nil());

	CHECK(val("foo") == val("foo"));
	CHECK(val("foo") != val("10"));
	CHECK(val("foo") != val(10));
	CHECK(val("foo") != val(&ud));
	CHECK(val("foo") != val::nil());

	CHECK(val(&ud) == val(&ud));
	CHECK(val(&ud) != val(true));
	CHECK(val(&ud) != val("&ud"));
	CHECK(val(&ud) != val(10));
	CHECK(val(&ud) != val::nil());

	CHECK(val(true) == val(true));
	CHECK(val(true) != val(false));
	CHECK(val(true) != val("true"));
	CHECK(val(true) != val(10));
	CHECK(val(true) != val::nil());
}<commit_msg>assign test<commit_after>#include "catch.hpp"
#include "lua/lua.hpp"

using namespace lua;

TEST_CASE("val_test/create", "create test") {
	val v = {
		{"int", 10},
		{"bool",true},
		{"string","foo"},
		{"nil", val::nil()}
	};
	val::table_type values;
	CHECK_NOTHROW(values = v.get<val::table_type>());
	CHECK(values["int"] == 10);
	CHECK(values["bool"] == true);
	CHECK(values["string"] == "foo");
	CHECK(values["nil"] == val::nil());
}

TEST_CASE("val_test/get", "get test") {
	val v1(10);
	CHECK(v1.get<int>() == 10);
	CHECK(v1.get<float>() == 10.0f);
	CHECK(v1.get<bool>() == true);
	CHECK(v1.get<std::string>() == "10");
	CHECK_THROWS(v1.get<void*>());

	val v2("foo");
	CHECK(v2.get<std::string>() == "foo");
	CHECK(v2.get<bool>() == true);
	CHECK_THROWS(v2.get<int>());
	CHECK_THROWS(v2.get<void*>());

	val v3("10");
	CHECK(v3.get<std::string>() == "10");
	CHECK(v3.get<int>() == 10);
	CHECK(v3.get<bool>() == true);
	CHECK_THROWS(v3.get<void*>());

	val v4(true);
	CHECK(v4.get<bool>() == true);
	CHECK(v4.get<int>() == 1);
	CHECK_THROWS(v4.get<std::string>());
	CHECK_THROWS(v4.get<void*>());

	auto nil = val::nil();
	CHECK(nil.get<void*>() == (void*)nullptr);
	CHECK(nil.get<bool>() == false);
	CHECK(nil.get<int>() == 0);
	CHECK_THROWS(nil.get<std::string>());
}

TEST_CASE("val_test/equals", "equals test") {
	int ud;
	CHECK(val(10) == val(10));
	CHECK(val(10) == val(10.0f));
	CHECK(val(10) != val("10"));
	CHECK(val(10) != val(9));
	CHECK(val(10) != val(&ud));
	CHECK(val(10) != val::nil());

	CHECK(val("foo") == val("foo"));
	CHECK(val("foo") != val("10"));
	CHECK(val("foo") != val(10));
	CHECK(val("foo") != val(&ud));
	CHECK(val("foo") != val::nil());

	CHECK(val(&ud) == val(&ud));
	CHECK(val(&ud) != val(true));
	CHECK(val(&ud) != val("&ud"));
	CHECK(val(&ud) != val(10));
	CHECK(val(&ud) != val::nil());

	CHECK(val(true) == val(true));
	CHECK(val(true) != val(false));
	CHECK(val(true) != val("true"));
	CHECK(val(true) != val(10));
	CHECK(val(true) != val::nil());
}

TEST_CASE("val_test/assign", "assign test") {
	val v1(10);
	auto v2 = v1;
	CHECK(v1 == v2);
}<|endoftext|>


<commit_before>#pragma once
#include "common_defines.hpp"

#ifdef new
#undef new
#endif

#include <boost/array.hpp>

using boost::array;

#ifdef DEBUG_NEW
#define new DEBUG_NEW
#endif
<commit_msg>std::array instead of boost::array.<commit_after>#pragma once
#include "common_defines.hpp"

#ifdef new
#undef new
#endif

#include <array>

using std::array;

#ifdef DEBUG_NEW
#define new DEBUG_NEW
#endif
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: misc_mem.cc,v 1.21 2002/08/17 09:23:42 vruppert Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "bochs.h"
#define LOG_THIS BX_MEM(0)->

#if BX_PROVIDE_CPU_MEMORY
  Bit32u
BX_MEM_C::get_memory_in_k(void)
{
  return(BX_MEM_THIS megabytes * 1024);
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(void)
{
  char mem[6];
  snprintf(mem, 6, "MEM%d", BX_SIM_ID);
  put(mem);
  settype(MEMLOG);

  vector = NULL;
  len    = 0;
  megabytes = 0;
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(size_t memsize)
{
  vector = new Bit8u[memsize];
  len    = memsize;
  megabytes = len / (1024*1024);
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
// BX_MEM_C destructor
BX_MEM_C::~BX_MEM_C(void)
{
  if (this-> vector != NULL) {
    delete [] this->vector;
    }
  else {
    BX_DEBUG(("(%u)   memory not freed as it wasn't allocated!", BX_SIM_ID));
    }
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::init_memory(int memsize)
{
	BX_DEBUG(("Init $Id: misc_mem.cc,v 1.21 2002/08/17 09:23:42 vruppert Exp $"));
  // you can pass 0 if memory has been allocated already through
  // the constructor, or the desired size of memory if it hasn't

  if (BX_MEM_THIS vector == NULL) {
    // memory not already allocated, do now...
    BX_MEM_THIS vector = new Bit8u[memsize];
    BX_MEM_THIS len    = memsize;
    BX_MEM_THIS megabytes = memsize / (1024*1024);
    BX_INFO(("%.2fMB", (float)(BX_MEM_THIS megabytes) ));
    }
  // initialize all memory to 0x00
  memset(BX_MEM_THIS vector, 0x00, BX_MEM_THIS len);

  // initialize ROM area (0xc0000 .. 0xfffff) to 0xff
  memset(BX_MEM_THIS vector + 0xc0000, 0xff, 0x40000);

#if BX_DEBUGGER
  // initialize dirty pages table
  memset(dbg_dirty_pages, 0, sizeof(dbg_dirty_pages));

  if (megabytes > BX_MAX_DIRTY_PAGE_TABLE_MEGS) {
    BX_INFO(("Error: memory larger than dirty page table can handle"));
    BX_PANIC(("Error: increase BX_MAX_DIRTY_PAGE_TABLE_MEGS"));
    }
#endif

}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::load_ROM(const char *path, Bit32u romaddress)
{
  struct stat stat_buf;
  int fd, ret;
  unsigned long size, offset;

  if (*path == '\0')
    return;
  // read in ROM BIOS image file
  fd = open(path, O_RDONLY
#ifdef O_BINARY
            | O_BINARY
#endif
           );
  if (fd < 0) {
    BX_INFO(( "ROM: couldn't open ROM image file '%s'.", path));
    BX_EXIT(1);
    }
  ret = fstat(fd, &stat_buf);
  if (ret) {
    BX_INFO(( "ROM: couldn't stat ROM image file '%s'.", path));
    BX_EXIT(1);
    }

  size = stat_buf.st_size;

  if ( (romaddress + size) > BX_MEM_THIS len ) {
    BX_INFO(( "ROM: ROM address range > physical memsize!"));
    BX_EXIT(1);
    }

  offset = 0;
  while (size > 0) {
#if BX_PCI_SUPPORT
    if (bx_options.Oi440FXSupport->get ())
      ret = BX_PCI_LOAD_ROM(fd, (romaddress - 0xC0000 + offset), size);
    else
#else
      ret = read(fd, (bx_ptr_t) &BX_MEM_THIS vector[romaddress + offset], size);
#endif
    if (ret <= 0) {
      BX_PANIC(( "ROM: read failed on BIOS image: '%s'",path));
      }
    size -= ret;
    offset += ret;
    }
  close(fd);
#if BX_PCI_SUPPORT
  if (bx_options.Oi440FXSupport->get ())
    BX_INFO(("rom in i440FX RAM 0x%06x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
  else
    BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
#else  // #if BX_PCI_SUPPORT
  BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
 			path
		));
#endif // #if BX_PCI_SUPPORT
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if ( BX_DEBUGGER || BX_DISASM )
  Boolean
BX_MEM_C::dbg_fetch_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    BX_INFO(("dbg_fetch_mem out of range. %p > %p",
      addr+len, this->len));
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      *buf = BX_VGA_MEM_READ(addr);
      }
    else {
#endif
#if BX_PCI_SUPPORT == 0
      *buf = vector[addr];
#else
      if ( bx_options.Oi440FXSupport->get () &&
          ((addr >= 0x000C0000) && (addr <= 0x000FFFFF)) ) {
        switch (bx_devices.pci->rd_memType (addr)) {
          case 0x0:  // Fetch from ShadowRAM
            *buf = vector[addr];
//          BX_INFO(("Fetching from ShadowRAM %06x, len %u !", (unsigned)addr, (unsigned)len));
            break;

          case 0x1:  // Fetch from ROM
            *buf = bx_pci.s.i440fx.shadow[(addr - 0xC0000)];
//          BX_INFO(("Fetching from ROM %06x, Data %02x ", (unsigned)addr, *buf));
            break;
          default:
            BX_PANIC(("dbg_fetch_mem: default case"));
          }
        }
      else
        *buf = vector[addr];
#endif  // #if BX_PCI_SUPPORT == 0
      }
    buf++;
    addr++;
    }
  return(1);
}
#endif

#if BX_DEBUGGER
  Boolean
BX_MEM_C::dbg_set_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      BX_VGA_MEM_WRITE(addr, *buf);
      }
    else
#endif
      vector[addr] = *buf;
    buf++;
    addr++;
    }
  return(1);
}
#endif

  Boolean
BX_MEM_C::dbg_crc32(unsigned long (*f)(unsigned char *buf, int len),
    Bit32u addr1, Bit32u addr2, Bit32u *crc)
{
  unsigned len;

  *crc = 0;
  if (addr1 > addr2)
    return(0);

  if (addr2 >= this->len) {
    return(0); // error, specified address past last phy mem addr
    }

  len = 1 + addr2 - addr1;
  *crc = f(vector + addr1, len);

  return(1);
}
<commit_msg>- reverted a change in the 'else' section of the load_ROM() function<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: misc_mem.cc,v 1.22 2002/08/17 09:46:27 vruppert Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2002  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "bochs.h"
#define LOG_THIS BX_MEM(0)->

#if BX_PROVIDE_CPU_MEMORY
  Bit32u
BX_MEM_C::get_memory_in_k(void)
{
  return(BX_MEM_THIS megabytes * 1024);
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(void)
{
  char mem[6];
  snprintf(mem, 6, "MEM%d", BX_SIM_ID);
  put(mem);
  settype(MEMLOG);

  vector = NULL;
  len    = 0;
  megabytes = 0;
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(size_t memsize)
{
  vector = new Bit8u[memsize];
  len    = memsize;
  megabytes = len / (1024*1024);
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
// BX_MEM_C destructor
BX_MEM_C::~BX_MEM_C(void)
{
  if (this-> vector != NULL) {
    delete [] this->vector;
    }
  else {
    BX_DEBUG(("(%u)   memory not freed as it wasn't allocated!", BX_SIM_ID));
    }
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::init_memory(int memsize)
{
	BX_DEBUG(("Init $Id: misc_mem.cc,v 1.22 2002/08/17 09:46:27 vruppert Exp $"));
  // you can pass 0 if memory has been allocated already through
  // the constructor, or the desired size of memory if it hasn't

  if (BX_MEM_THIS vector == NULL) {
    // memory not already allocated, do now...
    BX_MEM_THIS vector = new Bit8u[memsize];
    BX_MEM_THIS len    = memsize;
    BX_MEM_THIS megabytes = memsize / (1024*1024);
    BX_INFO(("%.2fMB", (float)(BX_MEM_THIS megabytes) ));
    }
  // initialize all memory to 0x00
  memset(BX_MEM_THIS vector, 0x00, BX_MEM_THIS len);

  // initialize ROM area (0xc0000 .. 0xfffff) to 0xff
  memset(BX_MEM_THIS vector + 0xc0000, 0xff, 0x40000);

#if BX_DEBUGGER
  // initialize dirty pages table
  memset(dbg_dirty_pages, 0, sizeof(dbg_dirty_pages));

  if (megabytes > BX_MAX_DIRTY_PAGE_TABLE_MEGS) {
    BX_INFO(("Error: memory larger than dirty page table can handle"));
    BX_PANIC(("Error: increase BX_MAX_DIRTY_PAGE_TABLE_MEGS"));
    }
#endif

}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::load_ROM(const char *path, Bit32u romaddress)
{
  struct stat stat_buf;
  int fd, ret;
  unsigned long size, offset;

  if (*path == '\0')
    return;
  // read in ROM BIOS image file
  fd = open(path, O_RDONLY
#ifdef O_BINARY
            | O_BINARY
#endif
           );
  if (fd < 0) {
    BX_INFO(( "ROM: couldn't open ROM image file '%s'.", path));
    BX_EXIT(1);
    }
  ret = fstat(fd, &stat_buf);
  if (ret) {
    BX_INFO(( "ROM: couldn't stat ROM image file '%s'.", path));
    BX_EXIT(1);
    }

  size = stat_buf.st_size;

  if ( (romaddress + size) > BX_MEM_THIS len ) {
    BX_INFO(( "ROM: ROM address range > physical memsize!"));
    BX_EXIT(1);
    }

  offset = 0;
  while (size > 0) {
#if BX_PCI_SUPPORT
    if (bx_options.Oi440FXSupport->get ())
      ret = BX_PCI_LOAD_ROM(fd, (romaddress - 0xC0000 + offset), size);
    else
      ret = read(fd, (bx_ptr_t) &BX_MEM_THIS vector[romaddress + offset], size);
#else
    ret = read(fd, (bx_ptr_t) &BX_MEM_THIS vector[romaddress + offset], size);
#endif
    if (ret <= 0) {
      BX_PANIC(( "ROM: read failed on BIOS image: '%s'",path));
      }
    size -= ret;
    offset += ret;
    }
  close(fd);
#if BX_PCI_SUPPORT
  if (bx_options.Oi440FXSupport->get ())
    BX_INFO(("rom in i440FX RAM 0x%06x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
  else
    BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
#else  // #if BX_PCI_SUPPORT
  BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
 			path
		));
#endif // #if BX_PCI_SUPPORT
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if ( BX_DEBUGGER || BX_DISASM )
  Boolean
BX_MEM_C::dbg_fetch_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    BX_INFO(("dbg_fetch_mem out of range. %p > %p",
      addr+len, this->len));
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      *buf = BX_VGA_MEM_READ(addr);
      }
    else {
#endif
#if BX_PCI_SUPPORT == 0
      *buf = vector[addr];
#else
      if ( bx_options.Oi440FXSupport->get () &&
          ((addr >= 0x000C0000) && (addr <= 0x000FFFFF)) ) {
        switch (bx_devices.pci->rd_memType (addr)) {
          case 0x0:  // Fetch from ShadowRAM
            *buf = vector[addr];
//          BX_INFO(("Fetching from ShadowRAM %06x, len %u !", (unsigned)addr, (unsigned)len));
            break;

          case 0x1:  // Fetch from ROM
            *buf = bx_pci.s.i440fx.shadow[(addr - 0xC0000)];
//          BX_INFO(("Fetching from ROM %06x, Data %02x ", (unsigned)addr, *buf));
            break;
          default:
            BX_PANIC(("dbg_fetch_mem: default case"));
          }
        }
      else
        *buf = vector[addr];
#endif  // #if BX_PCI_SUPPORT == 0
      }
    buf++;
    addr++;
    }
  return(1);
}
#endif

#if BX_DEBUGGER
  Boolean
BX_MEM_C::dbg_set_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      BX_VGA_MEM_WRITE(addr, *buf);
      }
    else
#endif
      vector[addr] = *buf;
    buf++;
    addr++;
    }
  return(1);
}
#endif

  Boolean
BX_MEM_C::dbg_crc32(unsigned long (*f)(unsigned char *buf, int len),
    Bit32u addr1, Bit32u addr2, Bit32u *crc)
{
  unsigned len;

  *crc = 0;
  if (addr1 > addr2)
    return(0);

  if (addr2 >= this->len) {
    return(0); // error, specified address past last phy mem addr
    }

  len = 1 + addr2 - addr1;
  *crc = f(vector + addr1, len);

  return(1);
}
<|endoftext|>


<commit_before>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "metadataheaders.h"

#include "custombinaryreader.h"

namespace google_cloud_debugger_portable_pdb {

using std::vector;
using std::string;
using std::array;

bool ParseFrom(CustomBinaryStream *binary_reader,
               MetadataRootHeader *root_header) {
  if (!binary_reader && !root_header) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&root_header->signature)) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->major_version) ||
      root_header->major_version != 1) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->minor_version) ||
      root_header->minor_version != 1) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&root_header->reserved) ||
      root_header->reserved != 0) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&root_header->version_string_length) &&
      root_header->version_string_length > 0) {
    return false;
  }

  vector<uint8_t> version_string_bytes(root_header->version_string_length, 0);

  uint32_t bytes_read = 0;
  if (!binary_reader->ReadBytes(version_string_bytes.data(),
                                root_header->version_string_length,
                                &bytes_read)) {
    return false;
  }

  string temp_vers_string(version_string_bytes.begin(),
                          version_string_bytes.end());
  root_header->version_string = temp_vers_string;

  // TODO(quoct): check this.
  // Not sure why these values are being set. Removing them.
  // header.version = header.version.Trim(new char[] { '\0' });

  // We have to advance to the next 4 byte boundary.
  uint32_t bytes_to_skipped = 4 - (root_header->version_string_length % 4);
  if (bytes_to_skipped != 4 &&
      !binary_reader->SeekFromCurrent(bytes_to_skipped)) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->flags)) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->number_streams)) {
    return false;
  }

  return true;
}

bool ParseFrom(CustomBinaryStream *binary_reader, StreamHeader *stream_header) {
  if (!binary_reader && !stream_header) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&stream_header->offset)) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&stream_header->size)) {
    return false;
  }

  vector<uint8_t> header_name;
  uint8_t bytes_read = 0;
  uint8_t character;
  while (binary_reader->ReadByte(&character)) {
    ++bytes_read;
    if (character == 0) {
      break;
    }

    header_name.push_back(character);
    // Name cannot be longer than 32 characters.
    if (bytes_read > 32) {
      return false;
    }
  }

  // Pad until 4 boundary.
  uint32_t bytes_to_skipped = 4 - (bytes_read % 4);
  if (bytes_to_skipped % 4 != 0 &&
      !binary_reader->SeekFromCurrent(bytes_to_skipped)) {
    return false;
  }

  string name_string(header_name.begin(), header_name.end());
  stream_header->name = name_string;

  return true;
}

bool ParseFrom(CustomBinaryStream *binary_reader,
               PortablePdbMetadataSectionHeader *pdb_metadata_header) {
  if (!binary_reader && !pdb_metadata_header) {
    return false;
  }

  uint32_t bytes_read = 0;
  if (!binary_reader->ReadBytes(pdb_metadata_header->pdb_id.data(),
                                pdb_metadata_header->pdb_id.size(),
                                &bytes_read)) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&pdb_metadata_header->entry_point)) {
    return false;
  }

  array<uint8_t, 8> system_tables_bits;
  if (!binary_reader->ReadBytes(system_tables_bits.data(),
                                system_tables_bits.size(), &bytes_read)) {
    return false;
  }

  uint32_t num_referenced_type_system_tables =
      CountAndSetBits<64, array<uint8_t, 8>>(
          &pdb_metadata_header->referenced_type_system_tables,
          system_tables_bits);

  pdb_metadata_header->type_system_table_rows.resize(
      num_referenced_type_system_tables);
  for (size_t i = 0; i < num_referenced_type_system_tables; ++i) {
    if (!binary_reader->ReadUInt32(
            &pdb_metadata_header->type_system_table_rows[i])) {
      return false;
    }
  }

  return true;
}

bool ParseFrom(CustomBinaryStream *binary_reader,
               CompressedMetadataTableHeader *table_header) {
  if (!binary_reader && !table_header) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&table_header->reserved) &&
      table_header->reserved != 0) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->major_version) &&
      table_header->major_version != 2) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->minor_version) &&
      table_header->minor_version != 0) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->heap_sizes)) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->reserved_2) &&
      table_header->reserved_2 != 1) {
    return false;
  }

  array<uint8_t, 8> bits_array;
  uint32_t bytes_read;
  if (!binary_reader->ReadBytes(bits_array.data(), bits_array.size(),
                                &bytes_read)) {
    return false;
  }
  uint32_t num_valids = CountAndSetBits<64, array<uint8_t, 8>>(
      &table_header->valid_mask, bits_array);

  if (!binary_reader->ReadBytes(bits_array.data(), bits_array.size(),
                                &bytes_read)) {
    return false;
  }
  uint32_t num_sorted = CountAndSetBits<64, array<uint8_t, 8>>(
      &table_header->sorted_mask, bits_array);

  table_header->num_rows.resize(num_valids);
  for (size_t i = 0; i < num_valids; ++i) {
    if (!binary_reader->ReadUInt32(&table_header->num_rows[i])) {
      return false;
    }
  }

  return true;
}

}  // namespace google_cloud_debugger_portable_pdb
<commit_msg>Add assert<commit_after>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "metadataheaders.h"

#include <assert.h>

#include "custombinaryreader.h"

namespace google_cloud_debugger_portable_pdb {

using std::vector;
using std::string;
using std::array;

bool ParseFrom(CustomBinaryStream *binary_reader,
               MetadataRootHeader *root_header) {
  assert(binary_reader != nullptr);
  assert(root_header != nullptr);

  if (!binary_reader->ReadUInt32(&root_header->signature)) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->major_version) ||
      root_header->major_version != 1) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->minor_version) ||
      root_header->minor_version != 1) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&root_header->reserved) ||
      root_header->reserved != 0) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&root_header->version_string_length) &&
      root_header->version_string_length > 0) {
    return false;
  }

  vector<uint8_t> version_string_bytes(root_header->version_string_length, 0);

  uint32_t bytes_read = 0;
  if (!binary_reader->ReadBytes(version_string_bytes.data(),
                                root_header->version_string_length,
                                &bytes_read)) {
    return false;
  }

  string temp_vers_string(version_string_bytes.begin(),
                          version_string_bytes.end());
  root_header->version_string = temp_vers_string;

  // TODO(quoct): check this.
  // Not sure why these values are being set. Removing them.
  // header.version = header.version.Trim(new char[] { '\0' });

  // We have to advance to the next 4 byte boundary.
  uint32_t bytes_to_skipped = 4 - (root_header->version_string_length % 4);
  if (bytes_to_skipped != 4 &&
      !binary_reader->SeekFromCurrent(bytes_to_skipped)) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->flags)) {
    return false;
  }

  if (!binary_reader->ReadUInt16(&root_header->number_streams)) {
    return false;
  }

  return true;
}

bool ParseFrom(CustomBinaryStream *binary_reader, StreamHeader *stream_header) {
  assert(binary_reader != nullptr);
  assert(stream_header != nullptr);

  if (!binary_reader->ReadUInt32(&stream_header->offset)) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&stream_header->size)) {
    return false;
  }

  vector<uint8_t> header_name;
  uint8_t bytes_read = 0;
  uint8_t character;
  while (binary_reader->ReadByte(&character)) {
    ++bytes_read;
    if (character == 0) {
      break;
    }

    header_name.push_back(character);
    // Name cannot be longer than 32 characters.
    if (bytes_read > 32) {
      return false;
    }
  }

  // Pad until 4 boundary.
  uint32_t bytes_to_skipped = 4 - (bytes_read % 4);
  if (bytes_to_skipped % 4 != 0 &&
      !binary_reader->SeekFromCurrent(bytes_to_skipped)) {
    return false;
  }

  string name_string(header_name.begin(), header_name.end());
  stream_header->name = name_string;

  return true;
}

bool ParseFrom(CustomBinaryStream *binary_reader,
               PortablePdbMetadataSectionHeader *pdb_metadata_header) {
  assert(binary_reader != nullptr);
  assert(pdb_metadata_header != nullptr);

  uint32_t bytes_read = 0;
  if (!binary_reader->ReadBytes(pdb_metadata_header->pdb_id.data(),
                                pdb_metadata_header->pdb_id.size(),
                                &bytes_read)) {
    return false;
  }

  if (!binary_reader->ReadUInt32(&pdb_metadata_header->entry_point)) {
    return false;
  }

  array<uint8_t, 8> system_tables_bits;
  if (!binary_reader->ReadBytes(system_tables_bits.data(),
                                system_tables_bits.size(), &bytes_read)) {
    return false;
  }

  uint32_t num_referenced_type_system_tables =
      CountAndSetBits<64, array<uint8_t, 8>>(
          &pdb_metadata_header->referenced_type_system_tables,
          system_tables_bits);

  pdb_metadata_header->type_system_table_rows.resize(
      num_referenced_type_system_tables);
  for (size_t i = 0; i < num_referenced_type_system_tables; ++i) {
    if (!binary_reader->ReadUInt32(
            &pdb_metadata_header->type_system_table_rows[i])) {
      return false;
    }
  }

  return true;
}

bool ParseFrom(CustomBinaryStream *binary_reader,
               CompressedMetadataTableHeader *table_header) {
  assert(binary_reader != nullptr);
  assert(table_header != nullptr);

  if (!binary_reader->ReadUInt32(&table_header->reserved) &&
      table_header->reserved != 0) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->major_version) &&
      table_header->major_version != 2) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->minor_version) &&
      table_header->minor_version != 0) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->heap_sizes)) {
    return false;
  }

  if (!binary_reader->ReadByte(&table_header->reserved_2) &&
      table_header->reserved_2 != 1) {
    return false;
  }

  array<uint8_t, 8> bits_array;
  uint32_t bytes_read;
  if (!binary_reader->ReadBytes(bits_array.data(), bits_array.size(),
                                &bytes_read)) {
    return false;
  }
  uint32_t num_valids = CountAndSetBits<64, array<uint8_t, 8>>(
      &table_header->valid_mask, bits_array);

  if (!binary_reader->ReadBytes(bits_array.data(), bits_array.size(),
                                &bytes_read)) {
    return false;
  }
  uint32_t num_sorted = CountAndSetBits<64, array<uint8_t, 8>>(
      &table_header->sorted_mask, bits_array);

  table_header->num_rows.resize(num_valids);
  for (size_t i = 0; i < num_valids; ++i) {
    if (!binary_reader->ReadUInt32(&table_header->num_rows[i])) {
      return false;
    }
  }

  return true;
}

}  // namespace google_cloud_debugger_portable_pdb
<|endoftext|>


<commit_before>#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch/catch.hpp"

#include "TestFixture.hpp"
#include "OpenCLManager.hpp"

// TODO Make tests for:
// OpenCL 1.1 device available

namespace test
{

//Helper functions
std::vector<cl::Device> getDevices(oul::DeviceType type){
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(type);

    return oul::opencl()->getDevices(criteria);
}

std::vector<cl::Device> getCPUDevices(){
    return getDevices(oul::DEVICE_TYPE_CPU);
}

std::vector<cl::Device> getGPUDevices(){
    return getDevices(oul::DEVICE_TYPE_GPU);
}

std::vector<cl::Device> getAllDevices(){
    return getDevices(oul::DEVICE_TYPE_ANY);
}
//------------------------------------------------------------------------------------------------
//Tests
TEST_CASE("Can create instance of the manager.","[OpenCLManager]"){
    CHECK(oul::opencl() != NULL);
}

TEST_CASE("Can set debug mode.","[OpenCLManager]"){
    CHECK(oul::opencl()->getDebugMode() == false);
    oul::opencl()->setDebugMode(true);
    CHECK(oul::opencl()->getDebugMode() == true);
}

TEST_CASE("Can create a oul::Context with defaul oul::DeviceCriteria.","[OpenCLManager]"){
    oul::DeviceCriteria criteria;

    CHECK_NOTHROW(oul::opencl()->createContext(criteria));
}

TEST_CASE("OpenCL platform(s) installed.","[OpenCLManager]"){
    oul::DeviceCriteria criteria;

    CHECK(oul::opencl()->getPlatforms(oul::DEVICE_PLATFORM_ANY).size() != 0);
}

TEST_CASE("OpenCL device(s) available.","[OpenCLManager]"){
    CHECK(getAllDevices().size() != 0);
}

TEST_CASE("OpenCL CPU device(s) available.","[OpenCLManager]"){
    CHECK(getCPUDevices().size() != 0);
}

TEST_CASE("OpenCL GPU device(s) available.","[OpenCLManager]"){
    CHECK(getGPUDevices().size() != 0);
}

//This test fails on Apple
TEST_CASE("At least one OpenCL device has OpenGL interop capability.","[OpenCLManage][OpenGL]"){
    bool foundOpenGLInteropCapableDevice  = false;

    std::vector<cl::Device> devices = getAllDevices();
    for(unsigned int i=0; i< devices.size(); i++){
        foundOpenGLInteropCapableDevice = foundOpenGLInteropCapableDevice or oul::OpenCLManager::deviceHasOpenGLInteropCapability(devices[i]);
    }

    CHECK(foundOpenGLInteropCapableDevice);
}

TEST_CASE("Default construction gives expected values.","[DeviceCriteria]"){
    oul::DeviceCriteria criteria;

    CHECK(criteria.getTypeCriteria() == oul::DEVICE_TYPE_ANY);
    CHECK(criteria.getDeviceCountMinCriteria() == 0);
    CHECK(criteria.getDeviceCountMaxCriteria() == 100);
    CHECK(criteria.getPlatformCriteria() == oul::DEVICE_PLATFORM_ANY);
    CHECK(criteria.getDevicePreference() == oul::DEVICE_PREFERENCE_NONE);
}

}//namespace test
<commit_msg>added a hack to make the lib compile with other projects v2.0<commit_after>#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch/catch.hpp"

#include "TestFixture.hpp"
// TODO: a non elegant hack here to make this work:
#include "../OpenCLManager.hpp"

// TODO Make tests for:
// OpenCL 1.1 device available

namespace test
{

//Helper functions
std::vector<cl::Device> getDevices(oul::DeviceType type){
    oul::DeviceCriteria criteria;
    criteria.setTypeCriteria(type);

    return oul::opencl()->getDevices(criteria);
}

std::vector<cl::Device> getCPUDevices(){
    return getDevices(oul::DEVICE_TYPE_CPU);
}

std::vector<cl::Device> getGPUDevices(){
    return getDevices(oul::DEVICE_TYPE_GPU);
}

std::vector<cl::Device> getAllDevices(){
    return getDevices(oul::DEVICE_TYPE_ANY);
}
//------------------------------------------------------------------------------------------------
//Tests
TEST_CASE("Can create instance of the manager.","[OpenCLManager]"){
    CHECK(oul::opencl() != NULL);
}

TEST_CASE("Can set debug mode.","[OpenCLManager]"){
    CHECK(oul::opencl()->getDebugMode() == false);
    oul::opencl()->setDebugMode(true);
    CHECK(oul::opencl()->getDebugMode() == true);
}

TEST_CASE("Can create a oul::Context with defaul oul::DeviceCriteria.","[OpenCLManager]"){
    oul::DeviceCriteria criteria;

    CHECK_NOTHROW(oul::opencl()->createContext(criteria));
}

TEST_CASE("OpenCL platform(s) installed.","[OpenCLManager]"){
    oul::DeviceCriteria criteria;

    CHECK(oul::opencl()->getPlatforms(oul::DEVICE_PLATFORM_ANY).size() != 0);
}

TEST_CASE("OpenCL device(s) available.","[OpenCLManager]"){
    CHECK(getAllDevices().size() != 0);
}

TEST_CASE("OpenCL CPU device(s) available.","[OpenCLManager]"){
    CHECK(getCPUDevices().size() != 0);
}

TEST_CASE("OpenCL GPU device(s) available.","[OpenCLManager]"){
    CHECK(getGPUDevices().size() != 0);
}

//This test fails on Apple
TEST_CASE("At least one OpenCL device has OpenGL interop capability.","[OpenCLManage][OpenGL]"){
    bool foundOpenGLInteropCapableDevice  = false;

    std::vector<cl::Device> devices = getAllDevices();
    for(unsigned int i=0; i< devices.size(); i++){
        foundOpenGLInteropCapableDevice = foundOpenGLInteropCapableDevice or oul::OpenCLManager::deviceHasOpenGLInteropCapability(devices[i]);
    }

    CHECK(foundOpenGLInteropCapableDevice);
}

TEST_CASE("Default construction gives expected values.","[DeviceCriteria]"){
    oul::DeviceCriteria criteria;

    CHECK(criteria.getTypeCriteria() == oul::DEVICE_TYPE_ANY);
    CHECK(criteria.getDeviceCountMinCriteria() == 0);
    CHECK(criteria.getDeviceCountMaxCriteria() == 100);
    CHECK(criteria.getPlatformCriteria() == oul::DEVICE_PLATFORM_ANY);
    CHECK(criteria.getDevicePreference() == oul::DEVICE_PREFERENCE_NONE);
}

}//namespace test
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::exception;
using std::ofstream;
using std::fixed;
using std::setprecision;
using std::numeric_limits;

#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <ReadData.hpp>
#include <InitializeOpenCL.hpp>
#include <GPUData.hpp>
#include <utils.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
#include <Folding.hpp>
#include <kernels/Memset.hpp>
using isa::utils::ArgumentList;
using isa::utils::same;
using AstroData::Observation;
using AstroData::readLOFAR;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::GPUData;
using isa::OpenCL::Memset;
using PulsarSearch::getShifts;
using PulsarSearch::dedisperse;
using PulsarSearch::fold;
using PulsarSearch::Folding;

typedef float dataType;
const string typeName("float");
const unsigned int nrBins = 256;

int main(int argc, char *argv[]) {
	unsigned int firstSecond = 0;
	unsigned int nrSeconds = 0;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	long long unsigned int wrongValues = 0;
	long long unsigned int wrongCounts = 0;
	string headerFileName;
	string dataFileName;
	Observation< dataType > observation("FoldingTest", typeName);

	try {
		ArgumentList args(argc, argv);

		firstSecond = args.getSwitchArgument< unsigned int >("-fs");
		nrSeconds = args.getSwitchArgument< unsigned int >("-ns");

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

		headerFileName = args.getSwitchArgument< string >("-header");
		dataFileName = args.getSwitchArgument< string >("-data");

		observation.setFirstDM(args.getSwitchArgument< float >("-dm_first"));
		observation.setDMStep(args.getSwitchArgument< float >("-dm_step"));
		observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dm_number"));
		observation.setFirstPeriod(args.getSwitchArgument< unsigned int >("-period_first"));
		observation.setPeriodStep(args.getSwitchArgument< unsigned int >("-period_step"));
		observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-period_number"));
		observation.setNrBins(nrBins);
	}
	catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Load the observation data
	vector< GPUData< dataType > * > *input = new vector< GPUData< dataType > * >(1);
	readLOFAR(headerFileName, dataFileName, observation, *input, nrSeconds, firstSecond);

	// Print some statistics
	cout << fixed << setprecision(3) << endl;
	cout << "Total seconds: \t\t" << observation.getNrSeconds() << endl;
	cout << "Min frequency: \t\t" << observation.getMinFreq() << " MHz" << endl;
	cout << "Max frequency: \t\t" << observation.getMaxFreq() << " MHz" << endl;
	cout << "Nr. channels: \t\t" << observation.getNrChannels() << endl;
	cout << "Channel bandwidth: \t" << observation.getChannelBandwidth() << " MHz" << endl;
	cout << "Samples/second: \t" << observation.getNrSamplesPerSecond() << endl;
	cout << "Min sample: \t\t" << observation.getMinValue() << endl;
	cout << "Max sample: \t\t" << observation.getMaxValue() << endl;
	cout << endl;

	// Test
	cl::Context *clContext = new cl::Context();
	vector< cl::Platform > *clPlatforms = new vector< cl::Platform >();
	vector< cl::Device > *clDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > *clQueues = new vector< vector < cl::CommandQueue > >();

	unsigned int nrSamplesPerChannel = 0;
	unsigned int secondsToBuffer = 0;
	GPUData< unsigned int > *shifts = getShifts(observation);
	GPUData< unsigned int > *globalCount = new GPUData< unsigned int >("GlobalCount", true);
	GPUData< unsigned int > *clGlobalCount = new GPUData< unsigned int >("CLGlobalCount", true);
	GPUData< dataType > *dispersedData = new GPUData< dataType >("DispersedData", true, true);
	GPUData< dataType > *dedispersedData = new GPUData< dataType >("DedispersedData", true);
	GPUData< dataType > *foldedData = new GPUData< dataType >("FoldedData", true);
	GPUData< dataType > *clFoldedData = new GPUData< dataType >("CLFoldedData", true);

	initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);

	if ( ((observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]) % 4) != 0 ) {
		nrSamplesPerChannel = (observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]) + (4 - ((observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]) % 4));
	}
	else {
		nrSamplesPerChannel = (observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]);
	}
	secondsToBuffer = static_cast< unsigned int >(ceil(static_cast< float >(nrSamplesPerChannel) / observation.getNrSamplesPerPaddedSecond()));
	if ( nrSeconds < secondsToBuffer ) {
		cerr << "Not enough seconds." << endl;
		return 1;
	}

	// Allocate memory
	globalCount->allocateHostData(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins());
	clGlobalCount->allocateHostData(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins());
	clGlobalCount->setCLContext(clContext);
	clGlobalCount->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	clGlobalCount->allocateDeviceData();
	dispersedData->allocateHostData(secondsToBuffer * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());
	dedispersedData->allocateHostData(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
	dedispersedData->setCLContext(clContext);
	dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	dedispersedData->allocateDeviceData();
	foldedData->allocateHostData(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins());
	clFoldedData->allocateHostData(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins());
	clFoldedData->setCLContext(clContext);
	clFoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	clFoldedData->allocateDeviceData();

	// Generate kernel
	Memset< dataType > *memsetDT = new Memset< dataType>(typeName);
	memsetDT->bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
	memsetDT->setNrThreads(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins());
	memsetDT->setNrRows(observation.getNrDMs() * observation.getNrPeriods());
	memsetDT->setNrThreadsPerBlock(observation.getNrBins());
	memsetDT->generateCode();
	(*memsetDT)(static_cast< dataType >(0), clFoldedData);
	delete memsetDT;
	Memset< unsigned int > *memsetUI = new Memset< unsigned int >("unsigned int");
	memsetUI->bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
	memsetUI->setNrThreads(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrPaddedBins());
	memsetUI->setNrRows(observation.getNrDMs() * observation.getNrPeriods());
	memsetUI->setNrThreadsPerBlock(observation.getNrBins());
	memsetUI->generateCode();
	(*memsetUI)(0, clGlobalCount);
	delete memsetUI;
	Folding< dataType > clFold("clFold", typeName);
	clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
	clFold.setObservation(&observation);
	clFold.setNrPeriodsPerBlock(256);
	clFold.setNrPeriodsPerThread(1);
	clFold.generateCode();

	cout << clFold.getCode() << endl;
	cout << endl;

	// Dedispersion and Folding loop
	for ( unsigned int second = 0; second < nrSeconds - (secondsToBuffer - 1); second++ ) {
		for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
			for ( unsigned int chunk = 0; chunk < secondsToBuffer; chunk++ ) {
				memcpy(dispersedData->getRawHostDataAt((channel * secondsToBuffer * observation.getNrSamplesPerPaddedSecond()) + (chunk * observation.getNrSamplesPerSecond())), (input->at(second + chunk))->getRawHostDataAt(channel * observation.getNrSamplesPerPaddedSecond()), observation.getNrSamplesPerSecond() * sizeof(dataType));
			}
		}

		dedisperse(secondsToBuffer * observation.getNrSamplesPerPaddedSecond(), observation, dispersedData, dedispersedData, shifts);
		fold(second, observation, dedispersedData, foldedData, globalCount);

		dedispersedData->copyHostToDevice();
		clFold(second, dedispersedData, clFoldedData, clGlobalCount);
	}

	clFoldedData->copyDeviceToHost();
	clGlobalCount->copyDeviceToHost();
	for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {
		for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
			for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
				if ( !same((*foldedData)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin], (*clFoldedData)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin]) ) {
					wrongValues++;

					cout << dm << " " << period << " " << bin << " " << (*foldedData)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] << " " << (*clFoldedData)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] << " " << (*foldedData)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] - (*clFoldedData)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] << endl;
				}
				if ( (*globalCount)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] != (*clGlobalCount)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] ) {
					wrongCounts++;

					cout << dm << " " << period << " " << bin << " " << (*globalCount)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] << " " << (*clGlobalCount)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin] << " " << static_cast< int >((*globalCount)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin]) - static_cast< int >((*clGlobalCount)[(((dm * observation.getNrPeriods()) + period) * observation.getNrPaddedBins()) + bin]) << endl;
				}

			}
		}
	}
	cout << endl;

	cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
	cout << "Wrong counters: " << wrongCounts << " (" << (wrongCounts * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
	cout << endl;
	cout << fixed << setprecision(6);
	cout << "Kernel timing: " << clFold.getTime() << " (total), " << clFold.getTime() / (nrSeconds - (secondsToBuffer - 1)) << " (average)" << endl;
	cout << endl;

	return 0;
}

<commit_msg>Updating the test.<commit_after>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <ctime>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::exception;
using std::ofstream;
using std::fixed;
using std::setprecision;
using std::numeric_limits;

#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <utils.hpp>
#include <Dedispersion.hpp>
#include <Folding.hpp>
#include <FoldingCPU.hpp>
using isa::utils::ArgumentList;
using isa::utils::same;
using AstroData::Observation;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using PulsarSearch::folding;
using PulsarSearch::Folding;

typedef float dataType;
const string typeName("float");
const unsigned int padding = 32;

// Common parameters
const unsigned int nrBeams = 1;
const unsigned int nrStations = 64;
// LOFAR
/*const float minFreq = 138.965f;
const float channelBandwidth = 0.195f;
const unsigned int nrSamplesPerSecond = 200000;
const unsigned int nrChannels = 32;*/
// Apertif
const float minFreq = 1425.0f;
const float channelBandwidth = 0.2929f;
const unsigned int nrSamplesPerSecond = 20000;
const unsigned int nrChannels = 1024;
// DMs
const unsigned int nrDMs = 256;
// Periods
const unsigned int nrPeriods = 128;
const unsigned int nrBins = 256;

int main(int argc, char *argv[]) {
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	long long unsigned int wrongValues = 0;
	Observation< dataType > observation("FoldingTest", typeName);
	CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true);
	CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true);
	CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true);

	try {
		ArgumentList args(argc, argv);

		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");

	} catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Setup of the observation
	observation.setPadding(padding);
	observation.setNrSamplesPerSecond(nrSamplesPerSecond);
	observation.setNrDMs(nrDMs);
	observation.setNrPeriods(nrPeriods);
	observation.setFirstPeriod(nrBins);
	observation.setPeriodStep(nrBins);
	observation.setNrBins(nrBins);

	cl::Context * clContext = new cl::Context();
	vector< cl::Platform > * clPlatforms = new vector< cl::Platform >();
	vector< cl::Device > * clDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();

	initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);

	// Allocate memory
	dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
	foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
	foldedData->blankHostData();
	counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());
	counterData->blankHostData();

	dedispersedData->setCLContext(clContext);
	dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	foldedData->setCLContext(clContext);
	foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));
	counterData->setCLContext(clContext);
	counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));

	try {
		dedispersedData->allocateDeviceData();
		foldedData->allocateDeviceData();
		foldedData->copyHostToDevice();
		counterData->allocateDeviceData();
		counterData->copyHostToDevice();
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}

	srand(time(NULL));
	for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
		for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
			dedispersedData->setHostDataItem((sample * observation.getNrPaddedDMs()) + DM, rand() % 100);
		}
	}

	// Test
	try {
		// Generate kernel
		Folding< dataType > clFold("clFold", typeName);
		clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));
		clFold.setObservation(&observation);
		clFold.setNrDMsPerBlock(128);
		clFold.setNrPeriodsPerBlock(2);
		clFold.setNrBinsPerBlock(1);
		clFold.setNrDMsPerThread(2);
		clFold.setNrPeriodsPerThread(2);
		clFold.setNrBinsPerThread(4);
		clFold.generateCode();

		dedispersedData->copyHostToDevice();
		clFold(dedispersedData, foldedData, counterData);
		foldedData->copyDeviceToHost();
	} catch ( OpenCLError err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Check
	CLData< dataType > * CPUFolded = new CLData<dataType >("CPUFolded", true);
	CLData< unsigned int > * CPUCounter = new CLData< unsigned int >("CPUCounter", true);
	folding(0, observation, dedispersedData->getHostData(), CPUFolded->getHostData(), CPUCounter->getHostData());
	for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {
		for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {
			for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
				const unsigned int dataItem = (bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM;
				if ( !same(CPUFolded->getHostDataItem(dataItem), foldedData->getHostDataItem(dataItem)) ) {
					wrongValues++;
				}
			}
		}
	}

	cout << "Wrong samples: " << wrongValues << " (" << (wrongValues * 100) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrBins()) << "%)." << endl;
	cout << endl;

	return 0;
}

<|endoftext|>