<commit_before>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <malloc.h>
#include <assert.h>

#include <QApplication>
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QString>
#include <QMessageBox>

#include <boost/foreach.hpp>

#include "PlayConfigTab.hpp"
#include "MainWindow.hpp"
//#include "debug.hpp"
#include "Configuration.hpp"

using namespace std;

////BEGIN memory debugging
//static void *(*old_malloc_hook)(size_t, const void *) = 0;
//static void *(*old_realloc_hook)(void *, size_t, const void *) = 0;
//static void (*old_free_hook)(void *, const void *) = 0;
//
//static void *md_malloc(size_t size, const void *caller);
//static void *md_realloc(void *ptr, size_t size, const void *caller);
//static void md_free(void *ptr, const void *caller);
//
//pthread_mutex_t md_mutex = PTHREAD_MUTEX_INITIALIZER;
//
//volatile bool barrier = false;
//
//static void *md_malloc(size_t size, const void *caller)
//{
//	pthread_mutex_lock(&md_mutex);
//	__malloc_hook = old_malloc_hook;
//	__realloc_hook = old_realloc_hook;
//	__free_hook = old_free_hook;
//	assert(!barrier);
//	barrier = true;
//	void *result = malloc(size);
//	old_malloc_hook = __malloc_hook;
//	__malloc_hook = md_malloc;
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	barrier = false;
//	pthread_mutex_unlock(&md_mutex);
//	return result;
//}
//
//static void *md_realloc(void *ptr, size_t size, const void *caller)
//{
//	pthread_mutex_lock(&md_mutex);
//	__malloc_hook = old_malloc_hook;
//	__realloc_hook = old_realloc_hook;
//	__free_hook = old_free_hook;
//	assert(!barrier);
//	barrier = true;
//	assert(size < 1048576 * 100);
//	void *result = realloc(ptr, size);
//	__malloc_hook = md_malloc;a
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	barrier = false;
//	pthread_mutex_unlock(&md_mutex);
//	return result;
//}
//
//static void md_free(void *ptr, const void *caller)
//{
//	pthread_mutex_lock(&md_mutex);
//	__malloc_hook = old_malloc_hook;
//	__realloc_hook = old_realloc_hook;
//	__free_hook = old_free_hook;
//	assert(!barrier);
//	barrier = true;
//	if (!ptr)
//	{
//// 		printf("Free zero from %p\n", caller);
//	} else {
//		free(ptr);
//	}
//	__malloc_hook = md_malloc;
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	barrier = false;
//	pthread_mutex_unlock(&md_mutex);
//}
//
//static void md_init_hook()
//{
//	old_malloc_hook = __malloc_hook;
//	old_realloc_hook = __realloc_hook;
//	old_free_hook = __free_hook;
//	__malloc_hook = md_malloc;
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	fprintf(stderr, "Memory debugging initialized: %p %p %p\n", old_malloc_hook, old_realloc_hook, old_free_hook);
//}
//
//void (*__malloc_initialize_hook)(void) = md_init_hook;
////END memory debugging

void usage(const char* prog)
{
	fprintf(stderr, "usage: %s [options...]\n", prog);
	fprintf(stderr, "\t-y:         run as the yellow team\n");
	fprintf(stderr, "\t-b:         run as the blue team\n");
	fprintf(stderr, "\t-c <file>:  specify the configuration file\n");
	fprintf(stderr, "\t-s <seed>:  set random seed (hexadecimal)\n");
	fprintf(stderr, "\t-p <file>:  load playbook\n");
	fprintf(stderr, "\t-pp <play>: enable named play\n");
	fprintf(stderr, "\t-ng:        no goalie\n");
	fprintf(stderr, "\t-sim:       use simulator\n");
	fprintf(stderr, "\t-freq:      specify radio frequency (906 or 904)\n");
	fprintf(stderr, "\t-nolog:     don't write log files\n");
	exit(1);
}

int main (int argc, char* argv[])
{
	printf("Starting Soccer...\n");

//	debugInit(argv[0]);  // FIXME: re-enable debugging

	// Seed the large random number generator
	long int seed = 0;
	int fd = open("/dev/random", O_RDONLY);
	if (fd >= 0)
	{
		if (read(fd, &seed, sizeof(seed)) != sizeof(seed))
		{
			fprintf(stderr, "Can't read /dev/random, using zero seed: %m\n");
		}
		close(fd);
	} else {
		fprintf(stderr, "Can't open /dev/random, using zero seed: %m\n");
	}

	QApplication app(argc, argv);

	bool blueTeam = false;
	QString cfgFile;
	QString playbook;
	vector<const char *> playDirs;
	vector<QString> extraPlays;
	bool goalie = true;
	bool sim = false;
	bool log = true;
    QString radioFreq;

	for (int i=1 ; i<argc; ++i)
	{
		const char* var = argv[i];

		if (strcmp(var, "--help") == 0)
		{
			usage(argv[0]);
		} else if (strcmp(var, "-y") == 0)
		{
			blueTeam = false;
		}
		else if (strcmp(var, "-b") == 0)
		{
			blueTeam = true;
		}
		else if (strcmp(var, "-ng") == 0)
		{
			goalie = false;
		}
		else if (strcmp(var, "-sim") == 0)
		{
			sim = true;
		}
		else if (strcmp(var, "-nolog") == 0)
		{
			log = false;
		}
        else if(strcmp(var, "-freq") == 0)
        {
            if(i+1 >= argc)
            {
                printf("No radio frequency specified after -freq");
                usage(argv[0]);
            }

            i++;
            radioFreq = argv[i];
        }
		else if(strcmp(var, "-c") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no config file specified after -c");
				usage(argv[0]);
			}

			i++;
			cfgFile = argv[i];
		}
		else if(strcmp(var, "-s") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no seed specified after -s");
				usage(argv[0]);
			}

			i++;
			seed = strtol(argv[i], 0, 16);
		}
		else if(strcmp(var, "-pp") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no play specified after -pp");
				usage(argv[0]);
			}

			i++;
			extraPlays.push_back(argv[i]);
		}
		else if(strcmp(var, "-p") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no playbook file specified after -p");
				usage(argv[0]);
			}

			i++;
			playbook = argv[i];
        }
		else
		{
			printf("Not a valid flag: %s\n", argv[i]);
			usage(argv[0]);
		}
	}

	printf("Running on %s\n", sim ? "simulation" : "real hardware");

	printf("seed %016lx\n", seed);
	srand48(seed);

	// Default config file name
	if (cfgFile.isNull())
	{
		cfgFile = sim ? "soccer-sim.cfg" : "soccer-real.cfg";
	}

	Configuration config;

	Processor *processor = new Processor(sim);
	processor->blueTeam(blueTeam);

	BOOST_FOREACH(Configurable *obj, Configurable::configurables())
	{
		obj->createConfiguration(&config);
	}

	// Load config file
	QString error;
	if (!config.load(cfgFile, error))
	{
		QMessageBox::critical(0, "Soccer",
			QString("Can't read initial configuration %1:\n%2").arg(cfgFile, error));
	}

	MainWindow *win = new MainWindow;
	win->configuration(&config);
	win->processor(processor);

	if (!playbook.isNull())
	{
		win->playConfigTab()->load(playbook);
	} else if (extraPlays.empty())
	{
		// Try to load a default playbook
		win->playConfigTab()->load("default.pbk");
	}

	BOOST_FOREACH(const QString &str, extraPlays)
	{
		win->playConfigTab()->enable(str);
	}

	if (!QDir("logs").exists())
	{
		fprintf(stderr, "No logs/ directory - not writing log file\n");
	} else if (!log)
	{
		fprintf(stderr, "Not writing log file\n");
	} else {
		QString logFile = QString("logs/") + QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss.log");
		if (!processor->openLog(logFile))
		{
			printf("Failed to open %s: %m\n", (const char *)logFile.toAscii());
		}
	}

    if(!radioFreq.isEmpty())
    {
        if(radioFreq == "904")
            win->setRadioChannel(RadioChannels::MHz_904);
        else if(radioFreq == "906")
            win->setRadioChannel(RadioChannels::MHz_906);
        else
            printf("Cannot recognize radio frequency : %s\n", radioFreq.toStdString().c_str());
    }

	win->logFileChanged();

	processor->start();

	win->showMaximized();

	int ret = app.exec();
	processor->stop();

	delete win;
	delete processor;

	return ret;
}
<commit_msg>REVERTME - added some test stuff to main.cpp<commit_after>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <malloc.h>
#include <assert.h>

#include <QApplication>
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QString>
#include <QMessageBox>

#include <boost/foreach.hpp>

#include "PlayConfigTab.hpp"
#include "MainWindow.hpp"
//#include "debug.hpp"
#include "Configuration.hpp"

#include "python/EmbeddedInstance.hpp"	//	TODO: remove

using namespace std;

////BEGIN memory debugging
//static void *(*old_malloc_hook)(size_t, const void *) = 0;
//static void *(*old_realloc_hook)(void *, size_t, const void *) = 0;
//static void (*old_free_hook)(void *, const void *) = 0;
//
//static void *md_malloc(size_t size, const void *caller);
//static void *md_realloc(void *ptr, size_t size, const void *caller);
//static void md_free(void *ptr, const void *caller);
//
//pthread_mutex_t md_mutex = PTHREAD_MUTEX_INITIALIZER;
//
//volatile bool barrier = false;
//
//static void *md_malloc(size_t size, const void *caller)
//{
//	pthread_mutex_lock(&md_mutex);
//	__malloc_hook = old_malloc_hook;
//	__realloc_hook = old_realloc_hook;
//	__free_hook = old_free_hook;
//	assert(!barrier);
//	barrier = true;
//	void *result = malloc(size);
//	old_malloc_hook = __malloc_hook;
//	__malloc_hook = md_malloc;
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	barrier = false;
//	pthread_mutex_unlock(&md_mutex);
//	return result;
//}
//
//static void *md_realloc(void *ptr, size_t size, const void *caller)
//{
//	pthread_mutex_lock(&md_mutex);
//	__malloc_hook = old_malloc_hook;
//	__realloc_hook = old_realloc_hook;
//	__free_hook = old_free_hook;
//	assert(!barrier);
//	barrier = true;
//	assert(size < 1048576 * 100);
//	void *result = realloc(ptr, size);
//	__malloc_hook = md_malloc;a
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	barrier = false;
//	pthread_mutex_unlock(&md_mutex);
//	return result;
//}
//
//static void md_free(void *ptr, const void *caller)
//{
//	pthread_mutex_lock(&md_mutex);
//	__malloc_hook = old_malloc_hook;
//	__realloc_hook = old_realloc_hook;
//	__free_hook = old_free_hook;
//	assert(!barrier);
//	barrier = true;
//	if (!ptr)
//	{
//// 		printf("Free zero from %p\n", caller);
//	} else {
//		free(ptr);
//	}
//	__malloc_hook = md_malloc;
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	barrier = false;
//	pthread_mutex_unlock(&md_mutex);
//}
//
//static void md_init_hook()
//{
//	old_malloc_hook = __malloc_hook;
//	old_realloc_hook = __realloc_hook;
//	old_free_hook = __free_hook;
//	__malloc_hook = md_malloc;
//	__realloc_hook = md_realloc;
//	__free_hook = md_free;
//	fprintf(stderr, "Memory debugging initialized: %p %p %p\n", old_malloc_hook, old_realloc_hook, old_free_hook);
//}
//
//void (*__malloc_initialize_hook)(void) = md_init_hook;
////END memory debugging

void usage(const char* prog)
{
	fprintf(stderr, "usage: %s [options...]\n", prog);
	fprintf(stderr, "\t-y:         run as the yellow team\n");
	fprintf(stderr, "\t-b:         run as the blue team\n");
	fprintf(stderr, "\t-c <file>:  specify the configuration file\n");
	fprintf(stderr, "\t-s <seed>:  set random seed (hexadecimal)\n");
	fprintf(stderr, "\t-p <file>:  load playbook\n");
	fprintf(stderr, "\t-pp <play>: enable named play\n");
	fprintf(stderr, "\t-ng:        no goalie\n");
	fprintf(stderr, "\t-sim:       use simulator\n");
	fprintf(stderr, "\t-freq:      specify radio frequency (906 or 904)\n");
	fprintf(stderr, "\t-nolog:     don't write log files\n");
	exit(1);
}

int main (int argc, char* argv[])
{
	printf("Starting Soccer...\n");

//	debugInit(argv[0]);  // FIXME: re-enable debugging

	// Seed the large random number generator
	long int seed = 0;
	int fd = open("/dev/random", O_RDONLY);
	if (fd >= 0)
	{
		if (read(fd, &seed, sizeof(seed)) != sizeof(seed))
		{
			fprintf(stderr, "Can't read /dev/random, using zero seed: %m\n");
		}
		close(fd);
	} else {
		fprintf(stderr, "Can't open /dev/random, using zero seed: %m\n");
	}

	QApplication app(argc, argv);

	bool blueTeam = false;
	QString cfgFile;
	QString playbook;
	vector<const char *> playDirs;
	vector<QString> extraPlays;
	bool goalie = true;
	bool sim = false;
	bool log = true;
    QString radioFreq;

	for (int i=1 ; i<argc; ++i)
	{
		const char* var = argv[i];

		if (strcmp(var, "--help") == 0)
		{
			usage(argv[0]);
		} else if (strcmp(var, "-y") == 0)
		{
			blueTeam = false;
		}
		else if (strcmp(var, "-b") == 0)
		{
			blueTeam = true;
		}
		else if (strcmp(var, "-ng") == 0)
		{
			goalie = false;
		}
		else if (strcmp(var, "-sim") == 0)
		{
			sim = true;
		}
		else if (strcmp(var, "-nolog") == 0)
		{
			log = false;
		}
        else if(strcmp(var, "-freq") == 0)
        {
            if(i+1 >= argc)
            {
                printf("No radio frequency specified after -freq");
                usage(argv[0]);
            }

            i++;
            radioFreq = argv[i];
        }
		else if(strcmp(var, "-c") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no config file specified after -c");
				usage(argv[0]);
			}

			i++;
			cfgFile = argv[i];
		}
		else if(strcmp(var, "-s") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no seed specified after -s");
				usage(argv[0]);
			}

			i++;
			seed = strtol(argv[i], 0, 16);
		}
		else if(strcmp(var, "-pp") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no play specified after -pp");
				usage(argv[0]);
			}

			i++;
			extraPlays.push_back(argv[i]);
		}
		else if(strcmp(var, "-p") == 0)
		{
			if (i+1 >= argc)
			{
				printf("no playbook file specified after -p");
				usage(argv[0]);
			}

			i++;
			playbook = argv[i];
        }
		else
		{
			printf("Not a valid flag: %s\n", argv[i]);
			usage(argv[0]);
		}
	}

	printf("Running on %s\n", sim ? "simulation" : "real hardware");

	printf("seed %016lx\n", seed);
	srand48(seed);

	// Default config file name
	if (cfgFile.isNull())
	{
		cfgFile = sim ? "soccer-sim.cfg" : "soccer-real.cfg";
	}

	Configuration config;

	Processor *processor = new Processor(sim);
	processor->blueTeam(blueTeam);

	BOOST_FOREACH(Configurable *obj, Configurable::configurables())
	{
		obj->createConfiguration(&config);
	}

	// Load config file
	QString error;
	if (!config.load(cfgFile, error))
	{
		QMessageBox::critical(0, "Soccer",
			QString("Can't read initial configuration %1:\n%2").arg(cfgFile, error));
	}

	MainWindow *win = new MainWindow;
	win->configuration(&config);
	win->processor(processor);

	if (!playbook.isNull())
	{
		win->playConfigTab()->load(playbook);
	} else if (extraPlays.empty())
	{
		// Try to load a default playbook
		win->playConfigTab()->load("default.pbk");
	}

	BOOST_FOREACH(const QString &str, extraPlays)
	{
		win->playConfigTab()->enable(str);
	}

	if (!QDir("logs").exists())
	{
		fprintf(stderr, "No logs/ directory - not writing log file\n");
	} else if (!log)
	{
		fprintf(stderr, "Not writing log file\n");
	} else {
		QString logFile = QString("logs/") + QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss.log");
		if (!processor->openLog(logFile))
		{
			printf("Failed to open %s: %m\n", (const char *)logFile.toAscii());
		}
	}

    if(!radioFreq.isEmpty())
    {
        if(radioFreq == "904")
            win->setRadioChannel(RadioChannels::MHz_904);
        else if(radioFreq == "906")
            win->setRadioChannel(RadioChannels::MHz_906);
        else
            printf("Cannot recognize radio frequency : %s\n", radioFreq.toStdString().c_str());
    }

	win->logFileChanged();

	processor->start();

	win->showMaximized();

	//	TODO: remove
	EmbeddedInstance::initialize();

	int ret = app.exec();
	processor->stop();

	delete win;
	delete processor;

	return ret;
}
<|endoftext|>


<commit_before>#include <count.h>
#include <compile.h>
#include <cstdlib>
#include <disassemble.h>
#include <gen.h>
#include <getline.h>
#include <lcutil.h>
#include <module.h>
#include <o.h>
#include <objectio.h>
#include <parse.h>
#include <primio.h>
#include <sym.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    const char* infile = nullptr;
    bool object        = false;
    bool trace         = false;
    for (int i = 1; i < argc; ++i) {
        if (argv[i][0] != '-') {
            infile = argv[i];
        } else {
            for (int j = 1; argv[i][j]; ++j) {
                if (argv[i][j] == 'o') object = true;
                if (argv[i][j] == 't') trace  = true;
            }
        }
    }
    if (infile) {
        H(2) << "nyi: qc file (work-around: redirect to stdin)\n" << flush;
        return EXIT_FAILURE;
    }

    KV<S,O> module(init_module(S(0)));
    L<S> infix_words{"in"_s};
    if (isatty(0)) H(1) << "  " << flush;
    L<C> line = getline();
    for (; trim(line) != "\\\\"; line = getline()) {
        try {
            O ast(parse(line, infix_words));
            O flattened_ast(compile(ast, trace));
            gen(module, flattened_ast, trace);
            L<X> code(module["code"_s]);
            if (object) H(1) << code;
            else        H(1) << disassemble(code);
            H(1) << flush;
        } catch (const Exception& e) {
            H(2) << e.what() << '\n' << flush;
        }
        if (isatty(0)) H(1) << "  " << flush;
    }

    return EXIT_SUCCESS;
}
<commit_msg>Add newline to qc object output<commit_after>#include <count.h>
#include <compile.h>
#include <cstdlib>
#include <disassemble.h>
#include <gen.h>
#include <getline.h>
#include <lcutil.h>
#include <module.h>
#include <o.h>
#include <objectio.h>
#include <parse.h>
#include <primio.h>
#include <sym.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    const char* infile = nullptr;
    bool object        = false;
    bool trace         = false;
    for (int i = 1; i < argc; ++i) {
        if (argv[i][0] != '-') {
            infile = argv[i];
        } else {
            for (int j = 1; argv[i][j]; ++j) {
                if (argv[i][j] == 'o') object = true;
                if (argv[i][j] == 't') trace  = true;
            }
        }
    }
    if (infile) {
        H(2) << "nyi: qc file (work-around: redirect to stdin)\n" << flush;
        return EXIT_FAILURE;
    }

    KV<S,O> module(init_module(S(0)));
    L<S> infix_words{"in"_s};
    if (isatty(0)) H(1) << "  " << flush;
    L<C> line = getline();
    for (; trim(line) != "\\\\"; line = getline()) {
        try {
            O ast(parse(line, infix_words));
            O flattened_ast(compile(ast, trace));
            gen(module, flattened_ast, trace);
            L<X> code(module["code"_s]);
            if (object) H(1) << code << '\n';
            else        H(1) << disassemble(code);
            H(1) << flush;
        } catch (const Exception& e) {
            H(2) << e.what() << '\n' << flush;
        }
        if (isatty(0)) H(1) << "  " << flush;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the libqgit2 library
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>
 * Copyright (C) 2013 Leonardo Giordani
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "qgitoid.h"
#include "qgitexception.h"

namespace LibQGit2
{

OId::OId(const git_oid* oid)
    : d(GIT_OID_RAWSZ, 0)
{
    if (oid != 0) {
        git_oid_cpy(data(), oid);
    }
}

OId::OId(const OId& other)
    : d(other.d)
{
}

OId::~OId()
{
}

bool OId::isValid() const
{
    return ( !d.isEmpty() &&
             (d.length() <= GIT_OID_RAWSZ) &&
             (d != QByteArray(GIT_OID_RAWSZ, 0))
             );
}

OId OId::fromString(const QByteArray& string)
{
    int len = qMin(string.length(), GIT_OID_HEXSZ);
    OId oid;
    qGitThrow(git_oid_fromstrn(oid.data(), string.constData(), len));
    oid.d.resize(len / 2);
    return oid;
}

OId OId::fromRawData(const QByteArray& raw)
{
    OId oid;
    oid.d = raw;
    return oid;
}

QByteArray OId::format() const
{
    QByteArray ba(GIT_OID_HEXSZ, Qt::Uninitialized);
    git_oid_fmt(ba.data(), constData());
    return ba;
}

QByteArray OId::pathFormat() const
{
    QByteArray ba(GIT_OID_HEXSZ+1, Qt::Uninitialized);
    git_oid_pathfmt(ba.data(), constData());
    return ba;
}

git_oid* OId::data()
{
    return reinterpret_cast<git_oid*>(d.data());
}

const git_oid* OId::constData() const
{
    return reinterpret_cast<const git_oid*>(d.constData());
}

bool operator ==(const OId &oid1, const OId &oid2)
{
    return git_oid_cmp(oid1.constData(), oid2.constData()) == 0;
}

bool operator !=(const OId &oid1, const OId &oid2)
{
    return !(operator ==(oid1, oid2));
}

int OId::length() const
{
    return d.length() * 2;
}

} // LibQGit2
<commit_msg>Review of conversion functions<commit_after>/******************************************************************************
 * This file is part of the libqgit2 library
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>
 * Copyright (C) 2013 Leonardo Giordani
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "qgitoid.h"
#include "qgitexception.h"

namespace LibQGit2
{

OId::OId(const git_oid* oid)
    : d(GIT_OID_RAWSZ, 0)
{
    if (oid != 0) {
        git_oid_cpy(data(), oid);
    }
}

OId::OId(const OId& other)
    : d(other.d)
{
}

OId::~OId()
{
}

bool OId::isValid() const
{
    return ( !d.isEmpty() &&
             (d.length() <= GIT_OID_RAWSZ) &&
             (d != QByteArray(GIT_OID_RAWSZ, 0))
             );
}

void OId::fromHex(const QByteArray& hex)
{
    int len = qMin(hex.length(), GIT_OID_HEXSZ);
    qGitThrow(git_oid_fromstrn(data(), hex.constData(), len));
    d.resize(len / 2);
}

void OId::fromString(const QString& string)
{
    fromHex(string.toUtf8());
}

void OId::fromRawData(const QByteArray& raw)
{
    qGitThrow(raw.length() < GIT_OID_HEXSZ);
    d = raw;
}

OId OId::stringToOid(const QByteArray& string)
{
    int len = qMin(string.length(), GIT_OID_HEXSZ);
    OId oid;
    qGitThrow(git_oid_fromstrn(oid.data(), string.constData(), len));
    oid.d.resize(len / 2);
    return oid;
}

OId OId::rawDataToOid(const QByteArray& raw)
{
    OId oid;
    oid.d = raw;
    return oid;
}

QByteArray OId::format() const
{
    QByteArray ba(GIT_OID_HEXSZ, Qt::Uninitialized);
    git_oid_fmt(ba.data(), constData());
    return ba;
}

QByteArray OId::pathFormat() const
{
    QByteArray ba(GIT_OID_HEXSZ+1, Qt::Uninitialized);
    git_oid_pathfmt(ba.data(), constData());
    return ba;
}

git_oid* OId::data()
{
    return reinterpret_cast<git_oid*>(d.data());
}

const git_oid* OId::constData() const
{
    return reinterpret_cast<const git_oid*>(d.constData());
}

bool operator ==(const OId &oid1, const OId &oid2)
{
    return git_oid_cmp(oid1.constData(), oid2.constData()) == 0;
}

bool operator !=(const OId &oid1, const OId &oid2)
{
    return !(operator ==(oid1, oid2));
}

int OId::length() const
{
    return d.length() * 2;
}

} // LibQGit2
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: idlccompile.cxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: ihi $ $Date: 2008-02-04 13:44:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#ifndef _IDLC_IDLC_HXX_
#include <idlc/idlc.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif

#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#endif

#ifdef  SAL_UNX
#include <unistd.h>
#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)
#include <sys/wait.h>
#else
#include <wait.h>
#endif
#endif

#include <string.h>

using namespace ::rtl;
using namespace ::osl;

extern int yyparse();
extern FILE* yyin;
extern int yydebug;

sal_Int32 lineNumber = 1;

static OUString TMP(RTL_CONSTASCII_USTRINGPARAM("TMP"));
static OUString TEMP(RTL_CONSTASCII_USTRINGPARAM("TEMP"));
static sal_Char tmpFilePattern[512];

sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OString convertToAbsoluteSystemPath(const OString& fileName)
{
    OUString uSysFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( isFileUrl(fileName) )
    {
        if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    } else
    {
        OUString uWorkingDir, uUrlFileName, uTmp;
        if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    }

    return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());
}

OString convertToFileUrl(const OString& fileName)
{
    if ( !isFileUrl(fileName) )
    {
        OString tmp = convertToAbsoluteSystemPath(fileName);
        OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());
        OUString uUrlFileName;
        if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());
    }

    return fileName;
}

OString makeTempName(const OString& prefix)
{
    OUString uTmpPath;
    OString tmpPath;

    if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32)
            tmpPath = OString("c:\\temp");
#else
            tmpPath = OString("/tmp");
#endif
        }
    }

    if ( uTmpPath.getLength() )
        tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);

#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)

    OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)
                                           + RTL_CONSTASCII_LENGTH(
                                                PATH_SEPARATOR )
                                           + prefix.getLength()
                                           + RTL_CONSTASCII_LENGTH(
                                                "XXXXXX") ) );

    tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\0';
    strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);
    strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, "XXXXXX", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));

#ifdef SAL_UNX
    int nDescriptor = mkstemp(tmpFilePattern);
    if( -1 == nDescriptor )
    {
        fprintf( stderr,"idlc: couldn't create temporary file\n" );
        exit( 1 );
    }
    // the file shall later be reopened by stdio functions
    close( nDescriptor );
#else
    (void) mktemp(tmpFilePattern);
#endif
#endif

    return OString(tmpFilePattern);
}

sal_Bool copyFile(const OString* source, const OString& target)
{
    sal_Bool bRet = sal_True;

    FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), "rb");

    if ( !pSource )
        return sal_False;

    FILE* pTarget = fopen(target.getStr(), "wb");

    if ( !pTarget )
    {
        fclose(pSource);
        return sal_False;
    }

    size_t totalSize = 512;
    size_t readSize  = 0;
    size_t writeSize = 0;
    char   pBuffer[513];

    while ( !feof(pSource) )
    {
        if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )
        {
            if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )
            {
                if (source != 0) {
                    fclose(pSource);
                }
                fclose(pTarget);
                return sal_False;
            }
        }
    }

    if (source != 0) {
        fclose(pSource);
    }
    if ( fflush(pTarget) )
        bRet = sal_False;
    fclose(pTarget);

    return bRet;
}

sal_Int32 compileFile(const OString * pathname)
{
    // preprocess input file
    OString tmpFile = makeTempName(OString("idli_"));
    OString preprocFile = makeTempName(OString("idlf_"));

    OString fileName;
    if (pathname == 0) {
        fileName = "stdin";
    } else {
        fileName = *pathname;
    }

    if ( !copyFile(pathname, tmpFile) )
    {
          fprintf(stderr, "%s: could not copy %s%s to %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                pathname == 0 ? "" : "file ", fileName.getStr(),
                tmpFile.getStr());
          exit(99);
    }

    idlc()->setFileName(fileName);
    idlc()->setMainFileName(fileName);
    idlc()->setRealFileName(tmpFile);

    OStringBuffer cppArgs(512);
    cppArgs.append("-DIDL -Xi -Xc -+ -I.");
    Options* pOptions = idlc()->getOptions();

    OString filePath;
    sal_Int32 index = fileName.lastIndexOf(SEPARATOR);

    if ( index > 0)
    {
        filePath = fileName.copy(0, index);

        if ( filePath.getLength() )
        {
            cppArgs.append(" -I\"");
            cppArgs.append(filePath);
            cppArgs.append("\"");
        }
    }

    if ( pOptions->isValid("-D") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-D"));
    }
    if ( pOptions->isValid("-I") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-I"));
    }

    cppArgs.append(" \"");
    cppArgs.append(tmpFile);
    cppArgs.append("\" \"");
    cppArgs.append(preprocFile);
    cppArgs.append("\"");

    OString cmdFileName = makeTempName(OString("idlc_"));
    FILE* pCmdFile = fopen(cmdFileName, "w");

    if ( !pCmdFile )
    {
          fprintf(stderr, "%s: couldn't open temporary file for preprocessor commands: %s\n",
            idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());
          exit(99);
    }
#ifdef SAL_OS2_00
      char* tok = strtok( (char*)cppArgs.getStr(), " \t\n\r");
      while( tok) {
         if (tok[strlen(tok)-1] == '\"')
            tok[strlen(tok)-1] = '\0';
         if (*tok == '\"')
            memcpy( tok, tok+1, strlen(tok));
         if (strlen(tok)>0) {
            fputs(tok, pCmdFile);
            fputc('\n', pCmdFile);
         }
         tok = strtok( NULL, " \t\n\r");
      }
#else
    fprintf(pCmdFile, "%s", cppArgs.getStr());
#endif
    fclose(pCmdFile);

    OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM("@"));
    cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);

    OUString cpp;
    OUString startDir;
    if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {
        OSL_ASSERT(false);
    }

    sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM("idlc")) );
     cpp = cpp.copy(0, idx);

#if defined(SAL_W32) || defined(SAL_OS2)
     cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp.exe"));
#else
    cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp"));
#endif

    oslProcess      hProcess = NULL;
    oslProcessError procError = osl_Process_E_None;

    procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,
                                   0, startDir.pData, 0, 0, &hProcess);

    oslProcessInfo hInfo;
    hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));
    if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)
        != osl_Process_E_None)
    {
        OSL_ASSERT(false);
    }

    if ( procError || (hInfo.Code != 0) )
    {
        if ( procError != osl_Process_E_None )
            fprintf(stderr, "%s: starting preprocessor failed\n", pOptions->getProgramName().getStr());
        else
            fprintf(stderr, "%s: preprocessing %s%s failed\n",
                    pOptions->getProgramName().getStr(),
                    pathname == 0 ? "" : "file ", fileName.getStr());

        unlink(tmpFile.getStr());
        unlink(preprocFile.getStr());
        unlink(cmdFileName.getStr());
        osl_freeProcessHandle(hProcess);
        exit(hInfo.Code ? hInfo.Code : 99);
    }
    osl_freeProcessHandle(hProcess);

    if (unlink(tmpFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove cpp input file %s\n",
                 pOptions->getProgramName().getStr(), tmpFile.getStr());
        exit(99);
    }

    if (unlink(cmdFileName.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove unocpp command file %s\n",
                   pOptions->getProgramName().getStr(), cmdFileName.getStr());

        exit(99);
    }

    if ( pOptions->isValid("-E") )
    {
        if (unlink(preprocFile) != 0)
        {
            fprintf(stderr, "%s: Could not remove parser input file %s\n",
                       pOptions->getProgramName().getStr(), preprocFile.getStr());
            exit(99);
        }
        exit(0);
    }

    // parse file
    yyin = fopen(preprocFile.getStr(), "r");
    if (yyin == NULL)
    {
        fprintf(stderr, "%s: Could not open cpp output file %s\n",
                   pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    //yydebug = 0 no trace information
    //yydebug = 1 parser produce trace information
    yydebug = 0;

    sal_Int32 nErrors = yyparse();
    nErrors = idlc()->getErrorCount();

    fclose(yyin);
    if (unlink(preprocFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove parser input file %s\n",
                pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    return nErrors;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.23.8); FILE MERGED 2008/04/01 15:20:34 thb 1.23.8.3: #i85898# Stripping all external header guards 2008/04/01 12:31:29 thb 1.23.8.2: #i85898# Stripping all external header guards 2008/03/31 07:23:51 rt 1.23.8.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: idlccompile.cxx,v $
 * $Revision: 1.24 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#include <idlc/idlc.hxx>
#include <rtl/ustring.hxx>
#include <rtl/strbuf.hxx>
#include <osl/process.h>
#include <osl/diagnose.h>
#include <osl/thread.h>
#include <osl/file.hxx>

#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#endif

#ifdef  SAL_UNX
#include <unistd.h>
#if defined(MACOSX) || defined(FREEBSD) || defined(NETBSD)
#include <sys/wait.h>
#else
#include <wait.h>
#endif
#endif

#include <string.h>

using namespace ::rtl;
using namespace ::osl;

extern int yyparse();
extern FILE* yyin;
extern int yydebug;

sal_Int32 lineNumber = 1;

static OUString TMP(RTL_CONSTASCII_USTRINGPARAM("TMP"));
static OUString TEMP(RTL_CONSTASCII_USTRINGPARAM("TEMP"));
static sal_Char tmpFilePattern[512];

sal_Bool isFileUrl(const OString& fileName)
{
    if (fileName.indexOf("file://") == 0 )
        return sal_True;
    return sal_False;
}

OString convertToAbsoluteSystemPath(const OString& fileName)
{
    OUString uSysFileName;
    OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
    if ( isFileUrl(fileName) )
    {
        if (FileBase::getSystemPathFromFileURL(uFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    } else
    {
        OUString uWorkingDir, uUrlFileName, uTmp;
        if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getFileURLFromSystemPath(uFileName, uTmp)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getAbsoluteFileURL(uWorkingDir, uTmp, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        if (FileBase::getSystemPathFromFileURL(uUrlFileName, uSysFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
    }

    return OUStringToOString(uSysFileName, osl_getThreadTextEncoding());
}

OString convertToFileUrl(const OString& fileName)
{
    if ( !isFileUrl(fileName) )
    {
        OString tmp = convertToAbsoluteSystemPath(fileName);
        OUString uFileName(tmp.getStr(), tmp.getLength(), osl_getThreadTextEncoding());
        OUString uUrlFileName;
        if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
            != FileBase::E_None)
        {
            OSL_ASSERT(false);
        }
        return OUStringToOString(uUrlFileName, osl_getThreadTextEncoding());
    }

    return fileName;
}

OString makeTempName(const OString& prefix)
{
    OUString uTmpPath;
    OString tmpPath;

    if ( osl_getEnvironment(TMP.pData, &uTmpPath.pData) != osl_Process_E_None )
    {
        if ( osl_getEnvironment(TEMP.pData, &uTmpPath.pData) != osl_Process_E_None )
        {
#if defined(SAL_W32)
            tmpPath = OString("c:\\temp");
#else
            tmpPath = OString("/tmp");
#endif
        }
    }

    if ( uTmpPath.getLength() )
        tmpPath = OUStringToOString(uTmpPath, RTL_TEXTENCODING_UTF8);

#if defined(SAL_W32) || defined(SAL_UNX) || defined(SAL_OS2)

    OSL_ASSERT( sizeof(tmpFilePattern) > ( strlen(tmpPath)
                                           + RTL_CONSTASCII_LENGTH(
                                                PATH_SEPARATOR )
                                           + prefix.getLength()
                                           + RTL_CONSTASCII_LENGTH(
                                                "XXXXXX") ) );

    tmpFilePattern[ sizeof(tmpFilePattern)-1 ] = '\0';
    strncpy(tmpFilePattern, tmpPath, sizeof(tmpFilePattern)-1);
    strncat(tmpFilePattern, PATH_SEPARATOR, sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, prefix.getStr(), sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));
    strncat(tmpFilePattern, "XXXXXX", sizeof(tmpFilePattern)-1-strlen(tmpFilePattern));

#ifdef SAL_UNX
    int nDescriptor = mkstemp(tmpFilePattern);
    if( -1 == nDescriptor )
    {
        fprintf( stderr,"idlc: couldn't create temporary file\n" );
        exit( 1 );
    }
    // the file shall later be reopened by stdio functions
    close( nDescriptor );
#else
    (void) mktemp(tmpFilePattern);
#endif
#endif

    return OString(tmpFilePattern);
}

sal_Bool copyFile(const OString* source, const OString& target)
{
    sal_Bool bRet = sal_True;

    FILE* pSource = source == 0 ? stdin : fopen(source->getStr(), "rb");

    if ( !pSource )
        return sal_False;

    FILE* pTarget = fopen(target.getStr(), "wb");

    if ( !pTarget )
    {
        fclose(pSource);
        return sal_False;
    }

    size_t totalSize = 512;
    size_t readSize  = 0;
    size_t writeSize = 0;
    char   pBuffer[513];

    while ( !feof(pSource) )
    {
        if ( (readSize = fread(pBuffer, 1, totalSize, pSource)) > 0 && !ferror(pSource) )
        {
            if ( (writeSize = fwrite(pBuffer, 1, readSize, pTarget)) != readSize || ferror(pTarget) )
            {
                if (source != 0) {
                    fclose(pSource);
                }
                fclose(pTarget);
                return sal_False;
            }
        }
    }

    if (source != 0) {
        fclose(pSource);
    }
    if ( fflush(pTarget) )
        bRet = sal_False;
    fclose(pTarget);

    return bRet;
}

sal_Int32 compileFile(const OString * pathname)
{
    // preprocess input file
    OString tmpFile = makeTempName(OString("idli_"));
    OString preprocFile = makeTempName(OString("idlf_"));

    OString fileName;
    if (pathname == 0) {
        fileName = "stdin";
    } else {
        fileName = *pathname;
    }

    if ( !copyFile(pathname, tmpFile) )
    {
          fprintf(stderr, "%s: could not copy %s%s to %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                pathname == 0 ? "" : "file ", fileName.getStr(),
                tmpFile.getStr());
          exit(99);
    }

    idlc()->setFileName(fileName);
    idlc()->setMainFileName(fileName);
    idlc()->setRealFileName(tmpFile);

    OStringBuffer cppArgs(512);
    cppArgs.append("-DIDL -Xi -Xc -+ -I.");
    Options* pOptions = idlc()->getOptions();

    OString filePath;
    sal_Int32 index = fileName.lastIndexOf(SEPARATOR);

    if ( index > 0)
    {
        filePath = fileName.copy(0, index);

        if ( filePath.getLength() )
        {
            cppArgs.append(" -I\"");
            cppArgs.append(filePath);
            cppArgs.append("\"");
        }
    }

    if ( pOptions->isValid("-D") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-D"));
    }
    if ( pOptions->isValid("-I") )
    {
        cppArgs.append(" ");
        cppArgs.append(pOptions->getOption("-I"));
    }

    cppArgs.append(" \"");
    cppArgs.append(tmpFile);
    cppArgs.append("\" \"");
    cppArgs.append(preprocFile);
    cppArgs.append("\"");

    OString cmdFileName = makeTempName(OString("idlc_"));
    FILE* pCmdFile = fopen(cmdFileName, "w");

    if ( !pCmdFile )
    {
          fprintf(stderr, "%s: couldn't open temporary file for preprocessor commands: %s\n",
            idlc()->getOptions()->getProgramName().getStr(), cmdFileName.getStr());
          exit(99);
    }
#ifdef SAL_OS2_00
      char* tok = strtok( (char*)cppArgs.getStr(), " \t\n\r");
      while( tok) {
         if (tok[strlen(tok)-1] == '\"')
            tok[strlen(tok)-1] = '\0';
         if (*tok == '\"')
            memcpy( tok, tok+1, strlen(tok));
         if (strlen(tok)>0) {
            fputs(tok, pCmdFile);
            fputc('\n', pCmdFile);
         }
         tok = strtok( NULL, " \t\n\r");
      }
#else
    fprintf(pCmdFile, "%s", cppArgs.getStr());
#endif
    fclose(pCmdFile);

    OUString cmdArg(RTL_CONSTASCII_USTRINGPARAM("@"));
    cmdArg += OStringToOUString(cmdFileName, RTL_TEXTENCODING_UTF8);

    OUString cpp;
    OUString startDir;
    if (osl_getExecutableFile(&cpp.pData) != osl_Process_E_None) {
        OSL_ASSERT(false);
    }

    sal_Int32 idx= cpp.lastIndexOf(OUString( RTL_CONSTASCII_USTRINGPARAM("idlc")) );
     cpp = cpp.copy(0, idx);

#if defined(SAL_W32) || defined(SAL_OS2)
     cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp.exe"));
#else
    cpp += OUString( RTL_CONSTASCII_USTRINGPARAM("idlcpp"));
#endif

    oslProcess      hProcess = NULL;
    oslProcessError procError = osl_Process_E_None;

    procError = osl_executeProcess(cpp.pData, &cmdArg.pData, 1, osl_Process_WAIT,
                                   0, startDir.pData, 0, 0, &hProcess);

    oslProcessInfo hInfo;
    hInfo.Size = (sal_uInt32)(sizeof(oslProcessInfo));
    if (osl_getProcessInfo(hProcess, osl_Process_EXITCODE, &hInfo)
        != osl_Process_E_None)
    {
        OSL_ASSERT(false);
    }

    if ( procError || (hInfo.Code != 0) )
    {
        if ( procError != osl_Process_E_None )
            fprintf(stderr, "%s: starting preprocessor failed\n", pOptions->getProgramName().getStr());
        else
            fprintf(stderr, "%s: preprocessing %s%s failed\n",
                    pOptions->getProgramName().getStr(),
                    pathname == 0 ? "" : "file ", fileName.getStr());

        unlink(tmpFile.getStr());
        unlink(preprocFile.getStr());
        unlink(cmdFileName.getStr());
        osl_freeProcessHandle(hProcess);
        exit(hInfo.Code ? hInfo.Code : 99);
    }
    osl_freeProcessHandle(hProcess);

    if (unlink(tmpFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove cpp input file %s\n",
                 pOptions->getProgramName().getStr(), tmpFile.getStr());
        exit(99);
    }

    if (unlink(cmdFileName.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove unocpp command file %s\n",
                   pOptions->getProgramName().getStr(), cmdFileName.getStr());

        exit(99);
    }

    if ( pOptions->isValid("-E") )
    {
        if (unlink(preprocFile) != 0)
        {
            fprintf(stderr, "%s: Could not remove parser input file %s\n",
                       pOptions->getProgramName().getStr(), preprocFile.getStr());
            exit(99);
        }
        exit(0);
    }

    // parse file
    yyin = fopen(preprocFile.getStr(), "r");
    if (yyin == NULL)
    {
        fprintf(stderr, "%s: Could not open cpp output file %s\n",
                   pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    //yydebug = 0 no trace information
    //yydebug = 1 parser produce trace information
    yydebug = 0;

    sal_Int32 nErrors = yyparse();
    nErrors = idlc()->getErrorCount();

    fclose(yyin);
    if (unlink(preprocFile.getStr()) != 0)
    {
        fprintf(stderr, "%s: Could not remove parser input file %s\n",
                pOptions->getProgramName().getStr(), preprocFile.getStr());
        exit(99);
    }

    return nErrors;
}
<|endoftext|>


<commit_before>
#include "filesystem.h"

#include <iostream>

#include <stdio.h>
#include <string.h>

FileSystem::FileSystem(const std::string &partfname):partfilename(partfname){
}

FileSystem::~FileSystem(){
}

void FileSystem::debug(){

  std::cout << "Debugging the filesystem class..." << std::endl;
  this->init();

}

int FileSystem::init(){

  FILE* fd = fopen(partfilename.c_str(), "wb+");

  // step 1: writeout 1024 0xbb's
  unsigned char bootblock[1024];
  memset(bootblock, 0xbb, sizeof(bootblock));
  fwrite(bootblock, 1, sizeof(bootblock), fd);

  // step 2: writeout the fat "header"
  unsigned char fatheader[20] = {0xff, 0xfd,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xff};

  fwrite(fatheader, 1, sizeof(fatheader), fd);

  // step 3: writeout blank rest
  unsigned char blankrest[4193260];
  memset(blankrest, 0x00, sizeof(blankrest));
  fwrite(blankrest, 1, sizeof(blankrest), fd);

  fclose(fd);

  return RET_OK;

}

int FileSystem::load(){

  // mvtodo: load fat into ram

  return RET_OK;
}

int FileSystem::listdir(const std::string &path, std::vector<std::string> &result){
  (void)path;
  (void)result;
  return -1;
}

int FileSystem::makedir(const std::string &path){
  (void)path;
  return -1;
}

int FileSystem::createfile(const std::string &path){
  (void)path;
  return -1;
}

int FileSystem::unlink(const std::string &path){
  (void)path;
  return -1;
}

int FileSystem::write(const std::string &path, const std::string &content){
  (void)path;
  (void)content;
  return -1;
}

int FileSystem::append(const std::string &path, const std::string &content){
  (void)path;
  (void)content;
  return -1;
}

int FileSystem::read(const std::string &path, std::string &content){
  (void)path;
  (void)content;
  return -1;
}

<commit_msg>second operation: read fat into RAM<commit_after>
#include "filesystem.h"

#include <iostream>

#include <stdio.h>
#include <string.h>

FileSystem::FileSystem(const std::string &partfname):partfilename(partfname){
}

FileSystem::~FileSystem(){
}

void FileSystem::debug(){

  std::cout << "Debugging the filesystem class..." << std::endl;
  this->init();
  this->load();

}

int FileSystem::init(){

  FILE* fd = fopen(partfilename.c_str(), "wb+");

  // step 1: writeout 1024 0xbb's
  unsigned char bootblock[1024];
  memset(bootblock, 0xbb, sizeof(bootblock));
  fwrite(bootblock, 1, sizeof(bootblock), fd);

  // step 2: writeout the fat "header"
  unsigned char fatheader[20] = {0xff, 0xfd,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xfe,
                                 0xff, 0xff};

  fwrite(fatheader, 1, sizeof(fatheader), fd);

  // step 3: writeout blank rest
  unsigned char blankrest[4193260];
  memset(blankrest, 0x00, sizeof(blankrest));
  fwrite(blankrest, 1, sizeof(blankrest), fd);

  fclose(fd);

  return RET_OK;

}

int FileSystem::load(){

  // mvtodo: load fat into ram

  FILE* fd = fopen(partfilename.c_str(), "rb+");
  fseek(fd, 1024, SEEK_SET);
  fread(fat, 1, sizeof(fat), fd);
  fclose(fd);

  return RET_OK;

}

int FileSystem::listdir(const std::string &path, std::vector<std::string> &result){
  (void)path;
  (void)result;
  return -1;
}

int FileSystem::makedir(const std::string &path){
  (void)path;
  return -1;
}

int FileSystem::createfile(const std::string &path){
  (void)path;
  return -1;
}

int FileSystem::unlink(const std::string &path){
  (void)path;
  return -1;
}

int FileSystem::write(const std::string &path, const std::string &content){
  (void)path;
  (void)content;
  return -1;
}

int FileSystem::append(const std::string &path, const std::string &content){
  (void)path;
  (void)content;
  return -1;
}

int FileSystem::read(const std::string &path, std::string &content){
  (void)path;
  (void)content;
  return -1;
}

<|endoftext|>


<commit_before>/* Copyright 2019 Google LLC. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/experimental/ruy/block_map.h"

#include "profiling/instrumentation.h"
#include "tensorflow/lite/experimental/ruy/check_macros.h"
#include "tensorflow/lite/experimental/ruy/opt_set.h"
#include "tensorflow/lite/experimental/ruy/size_util.h"

namespace ruy {

void GetBlockByIndex(const BlockMap& block_map, int index,
                     SidePair<int>* block) {
  gemmlowp::ScopedProfilingLabel label("GetBlockByIndex");
  const std::uint32_t index_u32 = index;
  const std::uint32_t rectr =
      index_u32 & ((1u << block_map.rectangularness_log2[Side::kLhs]) - 1);
  const std::uint32_t rectc =
      index_u32 & ((1u << block_map.rectangularness_log2[Side::kRhs]) - 1);

  const std::uint32_t n1 =
      index_u32 >> (block_map.rectangularness_log2[Side::kLhs] +
                    block_map.rectangularness_log2[Side::kRhs]);
  RUY_DCHECK_EQ(index_u32,
                (n1 << (block_map.rectangularness_log2[Side::kLhs] +
                        block_map.rectangularness_log2[Side::kRhs])) +
                    rectr + rectc);

  std::uint32_t br, bc;
  if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {
    br = n1 & ((1u << block_map.num_blocks_base_log2) - 1);
    bc = n1 >> block_map.num_blocks_base_log2;
  } else {
    // Decode fractal z-order
    const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |
                             ((n1 & 0x22222222u) << 1);
    const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |
                             ((n2 & 0x0c0c0c0cu) << 2);
    const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |
                             ((n4 & 0x00f000f0u) << 4);
    const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |
                              ((n8 & 0x0000ff00u) << 8);

    br = n16 & 0xffff;
    bc = n16 >> 16;
    if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {
      // Change fractal z-order to u-order
      br ^= bc;
    }
  }

  br = (br << block_map.rectangularness_log2[Side::kLhs]) + rectr;
  bc = (bc << block_map.rectangularness_log2[Side::kRhs]) + rectc;

  // Store
  (*block)[Side::kLhs] = br;
  (*block)[Side::kRhs] = bc;
}

namespace {

int floor_log2_quotient(int num, int denom) {
  if (num <= denom) {
    return 0;
  }
  int log2_quotient = floor_log2(num) - ceil_log2(denom);
  if ((denom << (log2_quotient + 1)) <= num) {
    log2_quotient++;
  }
  return log2_quotient;
}

}  // namespace

void MakeBlockMap(int rows, int cols, int depth, int kernel_rows,
                  int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,
                  int cache_friendly_traversal_threshold, BlockMap* block_map) {
  gemmlowp::ScopedProfilingLabel label("MakeBlockMap");
  RUY_DCHECK_GE(rows, kernel_rows);
  RUY_DCHECK_GE(cols, kernel_cols);
  RUY_DCHECK_EQ(rows % kernel_rows, 0);
  RUY_DCHECK_EQ(cols % kernel_cols, 0);

  block_map->traversal_order = BlockMapTraversalOrder::kLinear;
  if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&
      (rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=
          cache_friendly_traversal_threshold) {
    block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)
                                     ? BlockMapTraversalOrder::kFractalU
                                     : BlockMapTraversalOrder::kFractalZ;
  }

  // See the comment on BlockMap in block_map.h.
  // The destination matrix shape (rows x cols) is to be subdivided into a
  // square (N x N) grid of blocks, whose shapes must be multiples of the
  // kernel block shape (kernel_rows x kernel_cols).
  // Inside each of these N*N blocks, we may have one further level of
  // subdivision either along rows or along cols but not both, to handle
  // better the highly rectangular cases. That is what we call
  // 'rectangularness'.  This extra level of subdivision is into
  // (1 << rows_rectangularness_log2) blocks along rows dimension, or into
  // (1 << cols_rectangularness_log2) blocks along cols dimension.
  int rows_rectangularness_log2 = 0;
  int cols_rectangularness_log2 = 0;
  // In order to compute these rectangularness values, we need to divide
  // the destination matrix's aspect ratio,
  //    rows / cols
  // by the kernel block's aspect ratio,
  //    kernel_block_rows / kernel_block_cols.
  // The quotient of these two quotients simplifies to
  //    (rows * kernel_cols) / (cols * kernel_rows)
  // Whence the introduction of the following products:
  const int rows_times_kernel_cols = rows * kernel_cols;
  const int cols_times_kernel_rows = cols * kernel_rows;
  if (rows_times_kernel_cols > cols_times_kernel_rows) {
    rows_rectangularness_log2 =
        floor_log2_quotient(rows_times_kernel_cols, cols_times_kernel_rows);
    // Sanity check that we did not over-estimate rows_rectangularness_log2.
    RUY_DCHECK_GE(rows_times_kernel_cols >> rows_rectangularness_log2,
                  cols_times_kernel_rows);
  } else if (cols_times_kernel_rows > rows_times_kernel_cols) {
    cols_rectangularness_log2 =
        floor_log2_quotient(cols_times_kernel_rows, rows_times_kernel_cols);
    // Sanity check that we did not over-estimate cols_rectangularness_log2.
    RUY_DCHECK_GE(cols_times_kernel_rows >> cols_rectangularness_log2,
                  rows_times_kernel_cols);
  }

  RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);

  const int size = std::min(rows, cols);
  const int size_floor_log2 = floor_log2(size);
  const int depth_ceil_log2 = ceil_log2(depth);
  const int kernel_width_log2 = ceil_log2(std::max(kernel_cols, kernel_rows));

  // l1_size_log2 was originally, coarsely speaking the number of rows of LHS,
  // or the number of columns of RHS in a matrix multiplication that we expect,
  // to fit in L1 cache.
  //
  // This initial rationale is not necessarily still relevant. The logic below
  // was determined empirically, not in a principled way.
  int l1_size_log2;
  if (size_floor_log2 <= 3) {
    l1_size_log2 = size_floor_log2;
  } else if (size_floor_log2 <= 6) {
    l1_size_log2 = 4;
  } else {
    l1_size_log2 = 5;
  }

  // The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).
  // Once again this only has a distant memory of being originally motivated
  // by such clear principles linking this logic to cache sizes.
  l1_size_log2 = std::min(
      l1_size_log2, 15 - depth_ceil_log2 -
                        ceil_log2(std::max(lhs_scalar_size, rhs_scalar_size)));
  l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);
  l1_size_log2 = std::min(l1_size_log2, size_floor_log2);

  int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;
  RUY_DCHECK_GE(num_blocks_base_log2, 0);

  const int num_blocks_of_rows_log2 =
      num_blocks_base_log2 + rows_rectangularness_log2;
  const int num_blocks_of_cols_log2 =
      num_blocks_base_log2 + cols_rectangularness_log2;

  const int smallr =
      round_down_pot(rows >> num_blocks_of_rows_log2, kernel_rows);
  const int smallc =
      round_down_pot(cols >> num_blocks_of_cols_log2, kernel_cols);
  const int missr =
      round_up_pot(rows - (smallr << num_blocks_of_rows_log2), kernel_rows) /
      kernel_rows;
  const int missc =
      round_up_pot(cols - (smallc << num_blocks_of_cols_log2), kernel_cols) /
      kernel_cols;

  block_map->dims[Side::kLhs] = rows;
  block_map->dims[Side::kRhs] = cols;
  block_map->kernel_dims[Side::kLhs] = kernel_rows;
  block_map->kernel_dims[Side::kRhs] = kernel_cols;
  block_map->num_blocks_base_log2 = num_blocks_base_log2;
  block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;
  block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;
  block_map->small_block_dims[Side::kLhs] = smallr;
  block_map->small_block_dims[Side::kRhs] = smallc;
  block_map->large_blocks[Side::kLhs] = missr;
  block_map->large_blocks[Side::kRhs] = missc;
}

void GetBlockMatrixCoords(Side side, const BlockMap& block_map, int block,
                          int* start, int* end) {
  gemmlowp::ScopedProfilingLabel label("GetBlockMatrixCoords");
  *start = block * block_map.small_block_dims[side] +
           std::min(block, block_map.large_blocks[side]) *
               block_map.kernel_dims[side];
  *end =
      *start + block_map.small_block_dims[side] +
      (block < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);

  RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);
  RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);
  RUY_DCHECK_LE(*end, block_map.dims[side]);
  RUY_DCHECK_LT(*start, *end);
  RUY_DCHECK_GE(*start, 0);
}

void GetBlockMatrixCoords(const BlockMap& block_map, const SidePair<int>& block,
                          SidePair<int>* start, SidePair<int>* end) {
  for (Side side : {Side::kLhs, Side::kRhs}) {
    GetBlockMatrixCoords(side, block_map, block[side], &(*start)[side],
                         &(*end)[side]);
  }
}

}  // namespace ruy
<commit_msg>Avoid divisions when the divisor is a power of two.<commit_after>/* Copyright 2019 Google LLC. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/experimental/ruy/block_map.h"

#include "profiling/instrumentation.h"
#include "tensorflow/lite/experimental/ruy/check_macros.h"
#include "tensorflow/lite/experimental/ruy/opt_set.h"
#include "tensorflow/lite/experimental/ruy/size_util.h"

namespace ruy {

void GetBlockByIndex(const BlockMap& block_map, int index,
                     SidePair<int>* block) {
  gemmlowp::ScopedProfilingLabel label("GetBlockByIndex");
  const std::uint32_t index_u32 = index;
  const std::uint32_t rectr =
      index_u32 & ((1u << block_map.rectangularness_log2[Side::kLhs]) - 1);
  const std::uint32_t rectc =
      index_u32 & ((1u << block_map.rectangularness_log2[Side::kRhs]) - 1);

  const std::uint32_t n1 =
      index_u32 >> (block_map.rectangularness_log2[Side::kLhs] +
                    block_map.rectangularness_log2[Side::kRhs]);
  RUY_DCHECK_EQ(index_u32,
                (n1 << (block_map.rectangularness_log2[Side::kLhs] +
                        block_map.rectangularness_log2[Side::kRhs])) +
                    rectr + rectc);

  std::uint32_t br, bc;
  if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {
    br = n1 & ((1u << block_map.num_blocks_base_log2) - 1);
    bc = n1 >> block_map.num_blocks_base_log2;
  } else {
    // Decode fractal z-order
    const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |
                             ((n1 & 0x22222222u) << 1);
    const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |
                             ((n2 & 0x0c0c0c0cu) << 2);
    const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |
                             ((n4 & 0x00f000f0u) << 4);
    const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |
                              ((n8 & 0x0000ff00u) << 8);

    br = n16 & 0xffff;
    bc = n16 >> 16;
    if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {
      // Change fractal z-order to u-order
      br ^= bc;
    }
  }

  br = (br << block_map.rectangularness_log2[Side::kLhs]) + rectr;
  bc = (bc << block_map.rectangularness_log2[Side::kRhs]) + rectc;

  // Store
  (*block)[Side::kLhs] = br;
  (*block)[Side::kRhs] = bc;
}

namespace {

int floor_log2_quotient(int num, int denom) {
  if (num <= denom) {
    return 0;
  }
  int log2_quotient = floor_log2(num) - ceil_log2(denom);
  if ((denom << (log2_quotient + 1)) <= num) {
    log2_quotient++;
  }
  return log2_quotient;
}

}  // namespace

void MakeBlockMap(int rows, int cols, int depth, int kernel_rows,
                  int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,
                  int cache_friendly_traversal_threshold, BlockMap* block_map) {
  gemmlowp::ScopedProfilingLabel label("MakeBlockMap");
  RUY_DCHECK_GE(rows, kernel_rows);
  RUY_DCHECK_GE(cols, kernel_cols);
  RUY_DCHECK_EQ(rows % kernel_rows, 0);
  RUY_DCHECK_EQ(cols % kernel_cols, 0);

  block_map->traversal_order = BlockMapTraversalOrder::kLinear;
  if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&
      (rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=
          cache_friendly_traversal_threshold) {
    block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)
                                     ? BlockMapTraversalOrder::kFractalU
                                     : BlockMapTraversalOrder::kFractalZ;
  }

  // See the comment on BlockMap in block_map.h.
  // The destination matrix shape (rows x cols) is to be subdivided into a
  // square (N x N) grid of blocks, whose shapes must be multiples of the
  // kernel block shape (kernel_rows x kernel_cols).
  // Inside each of these N*N blocks, we may have one further level of
  // subdivision either along rows or along cols but not both, to handle
  // better the highly rectangular cases. That is what we call
  // 'rectangularness'.  This extra level of subdivision is into
  // (1 << rows_rectangularness_log2) blocks along rows dimension, or into
  // (1 << cols_rectangularness_log2) blocks along cols dimension.
  int rows_rectangularness_log2 = 0;
  int cols_rectangularness_log2 = 0;
  // In order to compute these rectangularness values, we need to divide
  // the destination matrix's aspect ratio,
  //    rows / cols
  // by the kernel block's aspect ratio,
  //    kernel_block_rows / kernel_block_cols.
  // The quotient of these two quotients simplifies to
  //    (rows * kernel_cols) / (cols * kernel_rows)
  // Whence the introduction of the following products:
  const int rows_times_kernel_cols = rows * kernel_cols;
  const int cols_times_kernel_rows = cols * kernel_rows;
  if (rows_times_kernel_cols > cols_times_kernel_rows) {
    rows_rectangularness_log2 =
        floor_log2_quotient(rows_times_kernel_cols, cols_times_kernel_rows);
    // Sanity check that we did not over-estimate rows_rectangularness_log2.
    RUY_DCHECK_GE(rows_times_kernel_cols >> rows_rectangularness_log2,
                  cols_times_kernel_rows);
  } else if (cols_times_kernel_rows > rows_times_kernel_cols) {
    cols_rectangularness_log2 =
        floor_log2_quotient(cols_times_kernel_rows, rows_times_kernel_cols);
    // Sanity check that we did not over-estimate cols_rectangularness_log2.
    RUY_DCHECK_GE(cols_times_kernel_rows >> cols_rectangularness_log2,
                  rows_times_kernel_cols);
  }

  RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);

  const int size = std::min(rows, cols);
  const int size_floor_log2 = floor_log2(size);
  const int depth_ceil_log2 = ceil_log2(depth);
  const int kernel_width_log2 = ceil_log2(std::max(kernel_cols, kernel_rows));

  // l1_size_log2 was originally, coarsely speaking the number of rows of LHS,
  // or the number of columns of RHS in a matrix multiplication that we expect,
  // to fit in L1 cache.
  //
  // This initial rationale is not necessarily still relevant. The logic below
  // was determined empirically, not in a principled way.
  int l1_size_log2;
  if (size_floor_log2 <= 3) {
    l1_size_log2 = size_floor_log2;
  } else if (size_floor_log2 <= 6) {
    l1_size_log2 = 4;
  } else {
    l1_size_log2 = 5;
  }

  // The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).
  // Once again this only has a distant memory of being originally motivated
  // by such clear principles linking this logic to cache sizes.
  l1_size_log2 = std::min(
      l1_size_log2, 15 - depth_ceil_log2 -
                        ceil_log2(std::max(lhs_scalar_size, rhs_scalar_size)));
  l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);
  l1_size_log2 = std::min(l1_size_log2, size_floor_log2);

  int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;
  RUY_DCHECK_GE(num_blocks_base_log2, 0);

  const int num_blocks_of_rows_log2 =
      num_blocks_base_log2 + rows_rectangularness_log2;
  const int num_blocks_of_cols_log2 =
      num_blocks_base_log2 + cols_rectangularness_log2;

  const int smallr =
      round_down_pot(rows >> num_blocks_of_rows_log2, kernel_rows);
  const int smallc =
      round_down_pot(cols >> num_blocks_of_cols_log2, kernel_cols);
  const int missr =
      round_up_pot(rows - (smallr << num_blocks_of_rows_log2), kernel_rows) >>
      floor_log2(kernel_rows);
  const int missc =
      round_up_pot(cols - (smallc << num_blocks_of_cols_log2), kernel_cols) >>
      floor_log2(kernel_cols);

  block_map->dims[Side::kLhs] = rows;
  block_map->dims[Side::kRhs] = cols;
  block_map->kernel_dims[Side::kLhs] = kernel_rows;
  block_map->kernel_dims[Side::kRhs] = kernel_cols;
  block_map->num_blocks_base_log2 = num_blocks_base_log2;
  block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;
  block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;
  block_map->small_block_dims[Side::kLhs] = smallr;
  block_map->small_block_dims[Side::kRhs] = smallc;
  block_map->large_blocks[Side::kLhs] = missr;
  block_map->large_blocks[Side::kRhs] = missc;
}

void GetBlockMatrixCoords(Side side, const BlockMap& block_map, int block,
                          int* start, int* end) {
  gemmlowp::ScopedProfilingLabel label("GetBlockMatrixCoords");
  *start = block * block_map.small_block_dims[side] +
           std::min(block, block_map.large_blocks[side]) *
               block_map.kernel_dims[side];
  *end =
      *start + block_map.small_block_dims[side] +
      (block < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);

  RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);
  RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);
  RUY_DCHECK_LE(*end, block_map.dims[side]);
  RUY_DCHECK_LT(*start, *end);
  RUY_DCHECK_GE(*start, 0);
}

void GetBlockMatrixCoords(const BlockMap& block_map, const SidePair<int>& block,
                          SidePair<int>* start, SidePair<int>* end) {
  for (Side side : {Side::kLhs, Side::kRhs}) {
    GetBlockMatrixCoords(side, block_map, block[side], &(*start)[side],
                         &(*end)[side]);
  }
}

}  // namespace ruy
<|endoftext|>


<commit_before>/* ux++ - ux implementation for C++ */

/* LICENSE - The MIT License (MIT)

Copyright (c) 2013 Tomona Nanase

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef ENVELOPEOPERATE_H
#define	ENVELOPEOPERATE_H

#include <unordered_map>
#include <string>
#include "EnumBase.hpp"

using namespace std;

namespace uxpp {

  /**
   * エンベロープの状態を表す列挙体です。
   */
  class EnvelopeOperate : public EnumBase {
  public:

    // <editor-fold desc="-- Enums --">

    enum values {
      /**
       * オプションなし。
       * これは音源に対するオプションと組み合わせるために用意されています。
       */
      none = 0x00,

      /**
       * アタック時間。
       */
      attack = 0x01,

      /**
       * ピーク時間。
       */
      peak = 0x02,

      /**
       * ディケイ時間。
       */
      decay = 0x03,

      /**
       * サスティンレベル。
       */
      sustain = 0x04,

      /**
       * リリース時間。
       */
      release = 0x05,
    };

    // </editor-fold>

    // <editor-fold desc="-- Methods --">

    _key_exists_impl(EnvelopeOperate);
    _value_exists_impl(EnvelopeOperate);
    _toString_impl(EnvelopeOperate);
    _tryParse_impl(EnvelopeOperate);
    // </editor-fold>

  private:
    static const unordered_map<string, values> map;
  };

  const unordered_map<string, EnvelopeOperate::values>
          EnvelopeOperate::map = {
    {"none", none},
    {"attack", attack},
    {"peak", peak},
    {"decay", decay},
    {"sustain", sustain},
    {"release", release},
    {"a", attack},
    {"p", peak},
    {"d", decay},
    {"s", sustain},
    {"r", release},
  };
}

#endif	/* ENVELOPEOPERATE_H */

<commit_msg>EnvelopeOperateクラスのusingディレクティブを削除<commit_after>/* ux++ - ux implementation for C++ */

/* LICENSE - The MIT License (MIT)

Copyright (c) 2013 Tomona Nanase

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef ENVELOPEOPERATE_H
#define	ENVELOPEOPERATE_H

#include <unordered_map>
#include <string>
#include "EnumBase.hpp"

namespace uxpp {

  /**
   * エンベロープの状態を表す列挙体です。
   */
  class EnvelopeOperate : public EnumBase {
  public:

    // <editor-fold desc="-- Enums --">

    enum values {
      /**
       * オプションなし。
       * これは音源に対するオプションと組み合わせるために用意されています。
       */
      none = 0x00,

      /**
       * アタック時間。
       */
      attack = 0x01,

      /**
       * ピーク時間。
       */
      peak = 0x02,

      /**
       * ディケイ時間。
       */
      decay = 0x03,

      /**
       * サスティンレベル。
       */
      sustain = 0x04,

      /**
       * リリース時間。
       */
      release = 0x05,
    };

    // </editor-fold>

    // <editor-fold desc="-- Methods --">

    _key_exists_impl(EnvelopeOperate);
    _value_exists_impl(EnvelopeOperate);
    _toString_impl(EnvelopeOperate);
    _tryParse_impl(EnvelopeOperate);
    // </editor-fold>

  private:
    static const std::unordered_map<std::string, values> map;
  };

  const std::unordered_map<std::string, EnvelopeOperate::values>
          EnvelopeOperate::map = {
    {"none", none},
    {"attack", attack},
    {"peak", peak},
    {"decay", decay},
    {"sustain", sustain},
    {"release", release},
    {"a", attack},
    {"p", peak},
    {"d", decay},
    {"s", sustain},
    {"r", release},
  };
}

#endif	/* ENVELOPEOPERATE_H */

<|endoftext|>


<commit_before>#include "IwGx.h"
#include "IwTween.h"
#include "audio.h"
#include "scene.h"
#include "grid.h"
#include "game.h"
#include "blankObject.h"
#include "resources.h"
#include "main.h"

using namespace IwTween;

Grid::Grid(CNode* scene, int num_columns, int num_rows, int offset_x, int offset_y, int grid_width)
{
	int map[11][17] = {
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
	};

	Width = num_columns;
	Height = num_rows;
	GameObjects = new GameObject* [num_columns * (num_rows + 1)];

	int bm_width = (int)g_pResources->GetRock()->GetWidth();
	GameObjectSize = (IwGxGetScreenWidth() * bm_width) / GRAPHIC_DESIGN_WIDTH;

	float gem_scale = (float)GameObjectSize / bm_width;

	GridOriginX = offset_x;
	GridOriginY = IwGxGetScreenHeight() - (num_rows * GameObjectSize) - offset_y;

	for (int y = 0; y < num_rows; y++)
	{
		for (int x = 0; x < num_columns; x++)
		{
			switch (map[x][y])
			{
			case 0:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 0));
				GameObjects[x + Width*y] = new BlankObject();
				GameObjects[x + Width*y]->setId(0);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetBlank());
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 1:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 1));
				GameObjects[x + Width*y] = new Rock();
				GameObjects[x + Width*y]->setId(1);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetRock());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 2:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 2));
				GameObjects[x + Width*y] = new Player();
				GameObjects[x + Width*y]->setId(2);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetPlayer());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;
			}
		}
	}
}

Grid::~Grid()
{
	if (GameObjects != 0)
		delete[] GameObjects;
}

void Grid::movePlayerLeft()
{
	int index = 0;

	for (int y = 0; y < Height; y++)
	{
		for (int x = 0; x < Width; x++)
		{
			if (GameObjects[x + Width * y]->getId() == 2)
			{
				index = x + Width * y;
			}
		}
	}

	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	IwTrace(APP, ("coords [%d][%d]", x, y));

	int distance = 0;

	while (GameObjects[(x - (distance + 1)) + Width*y]->getId() == 0) {
		distance++;
	}

	IwTrace(APP, ("distance = %d", distance));

	//cleanup
}

void Grid::movePlayerRight()
{
}

void Grid::movePlayerUp()
{
}

void Grid::movePlayerDown()
{
}

int Grid::getDistance(Grid::Direction dir)
{
	int distance = 0;

	switch (dir)
	{
	case LEFT:
		break;
	case RIGHT:
		break;
	case UP:
		break;
	case DOWN:
		break;
	}

	return 0;
}
<commit_msg>player sliding left<commit_after>#include "IwGx.h"
#include "IwTween.h"
#include "audio.h"
#include "scene.h"
#include "grid.h"
#include "game.h"
#include "blankObject.h"
#include "resources.h"
#include "main.h"

using namespace IwTween;

Grid::Grid(CNode* scene, int num_columns, int num_rows, int offset_x, int offset_y, int grid_width)
{
	int map[11][17] = {
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
		{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
	};

	Width = num_columns;
	Height = num_rows;
	GameObjects = new GameObject* [num_columns * (num_rows + 1)];

	int bm_width = (int)g_pResources->GetRock()->GetWidth();
	GameObjectSize = (IwGxGetScreenWidth() * bm_width) / GRAPHIC_DESIGN_WIDTH;

	float gem_scale = (float)GameObjectSize / bm_width;

	GridOriginX = offset_x;
	GridOriginY = IwGxGetScreenHeight() - (num_rows * GameObjectSize) - offset_y;

	for (int y = 0; y < num_rows; y++)
	{
		for (int x = 0; x < num_columns; x++)
		{
			switch (map[x][y])
			{
			case 0:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 0));
				GameObjects[x + Width*y] = new BlankObject();
				GameObjects[x + Width*y]->setId(0);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetBlank());
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 1:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 1));
				GameObjects[x + Width*y] = new Rock();
				GameObjects[x + Width*y]->setId(1);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetRock());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;

			case 2:
				IwTrace(APP, ("GameObject[%d], Id(%d)", x + Width*y, 2));
				GameObjects[x + Width*y] = new Player();
				GameObjects[x + Width*y]->setId(2);
				GameObjects[x + Width*y]->setGridCoords(x, y);
				GameObjects[x + Width*y]->init((float)x * GameObjectSize + GridOriginX, GridOriginY + (float)y * GameObjectSize, g_pResources->GetPlayer());
				GameObjects[x + Width*y]->m_ScaleX = gem_scale;
				GameObjects[x + Width*y]->m_ScaleY = gem_scale;
				scene->AddChild(GameObjects[x + Width*y]);
				break;
			}
		}
	}
}

Grid::~Grid()
{
	if (GameObjects != 0)
		delete[] GameObjects;
}

void Grid::movePlayerLeft()
{
	int index = 0;

	for (int y = 0; y < Height; y++)
	{
		for (int x = 0; x < Width; x++)
		{
			if (GameObjects[x + Width * y]->getId() == 2)
			{
				index = x + Width * y;
			}
		}
	}

	std::pair<int, int> coords = GameObjects[index]->getCoords();
	int x = coords.first;
	int y = coords.second;

	IwTrace(APP, ("coords [%d][%d]", x, y));

	int distance = 0;

	while (GameObjects[(x - (distance + 1)) + Width*y]->getId() == 0) {
		distance++;
	}

	IwTrace(APP, ("distance = %d", distance));

	float new_X = GameObjects[index]->m_X - (distance * GameObjectSize);

	Game* game = (Game*)g_pSceneManager->Find("game");

	game->GetTweener().Tween(0.5f,
		FLOAT, &GameObjects[index]->m_X, new_X,
		EASING, Ease::sineInOut,
		END);
}

void Grid::movePlayerRight()
{
}

void Grid::movePlayerUp()
{
}

void Grid::movePlayerDown()
{
}

int Grid::getDistance(Grid::Direction dir)
{
	int distance = 0;

	switch (dir)
	{
	case LEFT:
		break;
	case RIGHT:
		break;
	case UP:
		break;
	case DOWN:
		break;
	}

	return 0;
}
<|endoftext|>


<commit_before>
#include "leaf.h"
#include "composite.h"
#include "component.h"

int main (void)
{

}
<commit_msg>Instantiation of all 3 classes as a first test<commit_after>
#include "leaf.h"
#include "composite.h"
#include "component.h"

int main (void)
{
	Kompositum::Component component(0);
	Kompositum::Composite composite(1);
	Kompositum::Leaf leaf(2);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 C. Brett Witherspoon
 */

#ifndef OSCILLATOR_HPP_
#define OSCILLATOR_HPP_

#include <complex>

namespace comm {

template<class T>
class oscillator
{
public:
  using sample_type = T;

  oscillator(double frequency, double sample_rate, double amplitude=1)
    : m_freq(frequency),
      m_rate(sample_rate),
      m_ampl(amplitude)
  {
    static_assert(std::is_floating_point<sample_type>::value,
                  "Sample type must be a floating point type");

    m_y1 = 0;
    m_y2 = -m_ampl * sin(2 * M_PI * m_freq / m_rate);
    m_2cos_omega  = 2 * cos(2 * M_PI * m_freq / m_rate);
  }

  template<size_t N>
  void operator()(std::array<sample_type, N> &output)
  {
    for (auto &y0 : output)
    {
      y0 = m_2cos_omega * m_y1 - m_y2;
      m_y2 = m_y1;
      m_y1 = y0;
    }
  }

  double frequency() { return m_freq; }

  double sample_rate() { return m_rate; }

  double amplitude() { return m_ampl; }

private:
  double m_freq;
  double m_rate;
  double m_ampl;

  double m_y1;
  double m_y2;
  double m_2cos_omega;
};

template<>
template<class T>
class oscillator<std::complex<T>>
{
public:
  using sample_type = std::complex<T>;

  oscillator(double frequency, double sample_rate, double amplitude = 1)
    : m_freq(frequency),
      m_rate(sample_rate),
      m_ampl(amplitude)
  {
    static_assert(std::is_floating_point<T>::value,
                  "Sample type must be a floating point type");

    m_cos_omega = cos(2 * M_PI * m_freq / m_rate);
    m_sin_omega = sin(2 * M_PI * m_freq / m_rate);
    m_cos1 = m_ampl * m_cos_omega;
    m_sin1 = -m_ampl * m_sin_omega;
  }

  template<size_t N>
  void operator()(std::array<sample_type, N> &output)
  {
    T cos0;
    T sin0;

    for (auto &out : output)
    {
      cos0 = m_cos_omega * m_cos1 - m_sin_omega * m_sin1;
      sin0 = m_sin_omega * m_cos1 + m_cos_omega * m_sin1;
      m_cos1 = cos0;
      m_sin1 = sin0;
      out = std::complex<T>(cos0, sin0);
    }
  }

  double frequency() { return m_freq; }

  double sample_rate() { return m_rate; }

  double amplitude() { return m_ampl; }

private:
  double m_freq;
  double m_rate;
  double m_ampl;

  double m_cos1;
  double m_sin1;
  double m_cos_omega;
  double m_sin_omega;
};

} /* namespace comm */

#endif /* OSCILLATOR_HPP_ */
<commit_msg>oscillator: refactor<commit_after>/*
 * Copyright 2015 C. Brett Witherspoon
 */

#ifndef OSCILLATOR_HPP_
#define OSCILLATOR_HPP_

#include <complex>

namespace comm
{
/**
 *
 */
template<typename T>
class oscillator
{
public:
  using sample_type = T;

  oscillator(T frequency, T sample_rate, T amplitude = 1);

  template<typename U> void operator()(U& output);

  T frequency() { return m_freq; }

  T sample_rate() { return m_rate; }

  T amplitude() { return m_ampl; }

private:
  T m_freq;
  T m_rate;
  T m_ampl;
  T m_out1;
  T m_out2;
  T m_2cos_omega;
};

///////////////////////////////////////////////////////////////////////////////

template<typename T>
oscillator<T>::oscillator(T frequency, T sample_rate, T amplitude)
  : m_freq(frequency),
    m_rate(sample_rate),
    m_ampl(amplitude)
{
  static_assert(std::is_floating_point<sample_type>::value,
    "Sample type must be a floating point type");

  m_out1 = 0;
  m_out2 = -m_ampl * sin(2 * M_PI * m_freq / m_rate);
  m_2cos_omega  = 2 * cos(2 * M_PI * m_freq / m_rate);
}

template<typename T>
template<typename U>
void oscillator<T>::operator()(U& output)
{
  for (auto &out0 : output)
  {
    out0 = m_2cos_omega * m_out1 - m_out2;
    m_out2 = m_out1;
    m_out1 = out0;
  }
}

///////////////////////////////////////////////////////////////////////////////

/**
 *
 */
template<typename T>
class oscillator<std::complex<T>>
{
public:
  using sample_type = std::complex<T>;

  oscillator(T frequency, T sample_rate, T amplitude = 1);

  template<typename U> void operator()(U& output);

  T frequency() { return m_freq; }

  T sample_rate() { return m_rate; }

  T amplitude() { return m_ampl; }

private:
  T m_freq;
  T m_rate;
  T m_ampl;
  T m_cos1;
  T m_sin1;
  T m_cos_omega;
  T m_sin_omega;
};

///////////////////////////////////////////////////////////////////////////////

template<typename T>
oscillator<std::complex<T>>::oscillator(T frequency, T sample_rate, T amplitude)
  : m_freq(frequency),
    m_rate(sample_rate),
    m_ampl(amplitude)
{
  static_assert(std::is_floating_point<T>::value,
    "Sample type must be a floating point type");

  m_cos_omega = cos(2 * M_PI * m_freq / m_rate);
  m_sin_omega = sin(2 * M_PI * m_freq / m_rate);
  m_cos1 = m_ampl * m_cos_omega;
  m_sin1 = -m_ampl * m_sin_omega;
}

template<typename T>
template<typename U>
void oscillator<std::complex<T>>::operator()(U& output)
{
  T cos0;
  T sin0;

  for (auto &out : output)
  {
    cos0 = m_cos_omega * m_cos1 - m_sin_omega * m_sin1;
    sin0 = m_sin_omega * m_cos1 + m_cos_omega * m_sin1;
    m_cos1 = cos0;
    m_sin1 = sin0;
    out = std::complex<T>(cos0, sin0);
  }
}

} /* namespace comm */

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