<commit_before>/* dtkComposerNodeControlFor.cpp ---
 *
 * Author: tkloczko
 * Copyright (C) 2011 - Thibaud Kloczko, Inria.
 * Created: Wed Feb 15 09:14:22 2012 (+0100)
 * Version: $Id$
 * Last-Updated: mer. sept. 26 13:53:43 2012 (+0200)
 *           By: Nicolas Niclausse
 *     Update #: 140
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkComposerMetatype.h"

#include "dtkComposerNodeControlFor.h"

#include "dtkComposerNodeComposite.h"
#include "dtkComposerNodeProxy.h"

#include "dtkComposerTransmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include "dtkComposerTransmitterProxy.h"
#include "dtkComposerTransmitterVariant.h"

#include <dtkCore/dtkGlobal.h>

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeControlForPrivate definition
// /////////////////////////////////////////////////////////////////

class dtkComposerNodeControlForPrivate
{
public:
    dtkComposerNodeProxy header;
    dtkComposerNodeProxy footer;

    dtkComposerNodeComposite cond_block;
    dtkComposerNodeComposite body_block;
    dtkComposerNodeComposite incr_block;

public:
    dtkComposerTransmitterReceiver<bool> cond;
    dtkComposerTransmitterProxy          cond_prx;

    dtkComposerTransmitterVariant block_rcv;

    dtkComposerTransmitterProxy   incr_rcv;
    dtkComposerTransmitterVariant incr_emt;
};

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeControlFor implementation
// /////////////////////////////////////////////////////////////////

dtkComposerNodeControlFor::dtkComposerNodeControlFor(void) : dtkComposerNodeControl(), d(new dtkComposerNodeControlForPrivate)
{
    d->header.removeEmitter(0);
    d->header.setInputLabelHint("i_begin", 0);
    d->header.setAsHeader(true);

    d->footer.removeReceiver(0);
    d->footer.setOutputLabelHint("i_end", 0);
    d->footer.setAsFooter(true);

    d->cond_block.setTitleHint("Conditional");
    d->cond_block.appendEmitter(&(d->cond));
    d->cond_block.setOutputLabelHint("cond", 0);

    d->body_block.setTitleHint("Body");

    d->incr_block.setTitleHint("Increment");

    d->cond_block.appendReceiver(&(d->cond_prx));
    d->cond_block.setInputLabelHint("i", 0);

    d->body_block.appendReceiver(&(d->block_rcv));
    d->body_block.setInputLabelHint("i", 0);
    this->appendInputTwin(dynamic_cast<dtkComposerTransmitterVariant *>(d->body_block.receivers().first()));

    d->incr_block.appendReceiver(&(d->incr_rcv));
    d->incr_block.setInputLabelHint("i", 0);

    d->incr_block.appendEmitter(&(d->incr_emt));
    d->incr_block.setOutputLabelHint("i_next", 0);
    this->appendOutputTwin(dynamic_cast<dtkComposerTransmitterVariant *>(d->incr_block.emitters().first()));

    d->body_block.receivers().first()->appendPrevious(d->header.receivers().first());
    d->header.receivers().first()->appendNext(d->body_block.receivers().first());

    d->cond_block.receivers().first()->appendPrevious(d->body_block.receivers().first());
    d->body_block.receivers().first()->appendNext(d->cond_block.receivers().first());

    d->incr_block.receivers().first()->appendPrevious(d->body_block.receivers().first());
    d->body_block.receivers().first()->appendNext(d->incr_block.receivers().first());

    d->incr_block.emitters().first()->appendNext(d->footer.emitters().first());
    d->footer.emitters().first()->appendPrevious(d->incr_block.emitters().first());

    this->outputTwins().first()->setTwin(this->inputTwins().first());
}

dtkComposerNodeControlFor::~dtkComposerNodeControlFor(void)
{
    delete d;

    d = NULL;
}

int dtkComposerNodeControlFor::blockCount(void)
{
    return 3;
}

dtkComposerNodeLeaf *dtkComposerNodeControlFor::header(void)
{
    return &(d->header);
}

dtkComposerNodeLeaf *dtkComposerNodeControlFor::footer(void)
{
    return &(d->footer);
}

dtkComposerNodeComposite *dtkComposerNodeControlFor::block(int id)
{
    if(id == 0)
        return &(d->cond_block);

    if(id == 1)
        return &(d->body_block);

    if(id == 2)
        return &(d->incr_block);

    return NULL;
}

void dtkComposerNodeControlFor::setInputs(void)
{
    foreach(dtkComposerTransmitterVariant *v, this->inputTwins()) {
        v->setTwinned(false);
        v->setDataFrom(v);
        v->setTwinned(true);
    }
}

void dtkComposerNodeControlFor::setOutputs(void)
{
    // start from 1 on purpose; the first port is the loop port.
    for (int i = 1; i < this->outputTwins().count(); i++) {
        this->outputTwins().at(i)->twin()->setDataFrom(this->outputTwins().at(i));
    }
}

void dtkComposerNodeControlFor::setVariables(void)
{
    this->outputTwins().first()->twin()->setDataFrom(this->outputTwins().first());
}

int dtkComposerNodeControlFor::selectBranch(void)
{
    return static_cast<int>(!(*d->cond.data()));
}

void dtkComposerNodeControlFor::begin(void)
{
}

void dtkComposerNodeControlFor::end(void)
{
}

QString dtkComposerNodeControlFor::type(void)
{
    return "for";
}

QString dtkComposerNodeControlFor::titleHint(void)
{
    return "For";
}
<commit_msg>micro optimization<commit_after>/* dtkComposerNodeControlFor.cpp ---
 *
 * Author: tkloczko
 * Copyright (C) 2011 - Thibaud Kloczko, Inria.
 * Created: Wed Feb 15 09:14:22 2012 (+0100)
 * Version: $Id$
 * Last-Updated: jeu. sept. 27 14:40:02 2012 (+0200)
 *           By: Nicolas Niclausse
 *     Update #: 147
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkComposerMetatype.h"

#include "dtkComposerNodeControlFor.h"

#include "dtkComposerNodeComposite.h"
#include "dtkComposerNodeProxy.h"

#include "dtkComposerTransmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include "dtkComposerTransmitterProxy.h"
#include "dtkComposerTransmitterVariant.h"

#include <dtkCore/dtkGlobal.h>

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeControlForPrivate definition
// /////////////////////////////////////////////////////////////////

class dtkComposerNodeControlForPrivate
{
public:
    dtkComposerNodeProxy header;
    dtkComposerNodeProxy footer;

    dtkComposerNodeComposite cond_block;
    dtkComposerNodeComposite body_block;
    dtkComposerNodeComposite incr_block;

public:
    dtkComposerTransmitterReceiver<bool> cond;
    dtkComposerTransmitterProxy          cond_prx;

    dtkComposerTransmitterVariant block_rcv;

    dtkComposerTransmitterProxy   incr_rcv;
    dtkComposerTransmitterVariant incr_emt;
};

// /////////////////////////////////////////////////////////////////
// dtkComposerNodeControlFor implementation
// /////////////////////////////////////////////////////////////////

dtkComposerNodeControlFor::dtkComposerNodeControlFor(void) : dtkComposerNodeControl(), d(new dtkComposerNodeControlForPrivate)
{
    d->header.removeEmitter(0);
    d->header.setInputLabelHint("i_begin", 0);
    d->header.setAsHeader(true);

    d->footer.removeReceiver(0);
    d->footer.setOutputLabelHint("i_end", 0);
    d->footer.setAsFooter(true);

    d->cond_block.setTitleHint("Conditional");
    d->cond_block.appendEmitter(&(d->cond));
    d->cond_block.setOutputLabelHint("cond", 0);

    d->body_block.setTitleHint("Body");

    d->incr_block.setTitleHint("Increment");

    d->cond_block.appendReceiver(&(d->cond_prx));
    d->cond_block.setInputLabelHint("i", 0);

    d->body_block.appendReceiver(&(d->block_rcv));
    d->body_block.setInputLabelHint("i", 0);
    this->appendInputTwin(dynamic_cast<dtkComposerTransmitterVariant *>(d->body_block.receivers().first()));

    d->incr_block.appendReceiver(&(d->incr_rcv));
    d->incr_block.setInputLabelHint("i", 0);

    d->incr_block.appendEmitter(&(d->incr_emt));
    d->incr_block.setOutputLabelHint("i_next", 0);
    this->appendOutputTwin(dynamic_cast<dtkComposerTransmitterVariant *>(d->incr_block.emitters().first()));

    d->body_block.receivers().first()->appendPrevious(d->header.receivers().first());
    d->header.receivers().first()->appendNext(d->body_block.receivers().first());

    d->cond_block.receivers().first()->appendPrevious(d->body_block.receivers().first());
    d->body_block.receivers().first()->appendNext(d->cond_block.receivers().first());

    d->incr_block.receivers().first()->appendPrevious(d->body_block.receivers().first());
    d->body_block.receivers().first()->appendNext(d->incr_block.receivers().first());

    d->incr_block.emitters().first()->appendNext(d->footer.emitters().first());
    d->footer.emitters().first()->appendPrevious(d->incr_block.emitters().first());

    this->outputTwins().first()->setTwin(this->inputTwins().first());
}

dtkComposerNodeControlFor::~dtkComposerNodeControlFor(void)
{
    delete d;

    d = NULL;
}

int dtkComposerNodeControlFor::blockCount(void)
{
    return 3;
}

dtkComposerNodeLeaf *dtkComposerNodeControlFor::header(void)
{
    return &(d->header);
}

dtkComposerNodeLeaf *dtkComposerNodeControlFor::footer(void)
{
    return &(d->footer);
}

dtkComposerNodeComposite *dtkComposerNodeControlFor::block(int id)
{
    if(id == 0)
        return &(d->cond_block);

    if(id == 1)
        return &(d->body_block);

    if(id == 2)
        return &(d->incr_block);

    return NULL;
}

void dtkComposerNodeControlFor::setInputs(void)
{
    foreach(dtkComposerTransmitterVariant *v, this->inputTwins()) {
        v->setTwinned(false);
        v->setDataFrom(v);
        v->setTwinned(true);
    }
}

void dtkComposerNodeControlFor::setOutputs(void)
{
    // start from 1 on purpose; the first port is the loop port.
    for (int i = 1; i < this->outputTwins().count(); i++) {
        dtkComposerTransmitterVariant *twin = this->outputTwins().at(i);
        twin->twin()->setDataFrom(twin);
    }
}

void dtkComposerNodeControlFor::setVariables(void)
{
    this->outputTwins().first()->twin()->setDataFrom(this->outputTwins().first());
}

int dtkComposerNodeControlFor::selectBranch(void)
{
    return static_cast<int>(!(*d->cond.data()));
}

void dtkComposerNodeControlFor::begin(void)
{
}

void dtkComposerNodeControlFor::end(void)
{
}

QString dtkComposerNodeControlFor::type(void)
{
    return "for";
}

QString dtkComposerNodeControlFor::titleHint(void)
{
    return "For";
}
<|endoftext|>


<commit_before>// This file is part of libAthena.
//
// libAthena 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.
//
// libAthena 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 libAthena.  If not, see <http://www.gnu.org/licenses/>

#include "Athena/BinaryReader.hpp"
#include "Athena/IOException.hpp"
#include "Athena/FileNotFoundException.hpp"
#include "Athena/InvalidDataException.hpp"
#include "Athena/InvalidOperationException.hpp"
#include "utf8.h"

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <cstring>

#ifdef HW_RVL
#include <malloc.h>
#endif // HW_RVL

namespace Athena
{
namespace io
{
BinaryReader::BinaryReader(const atUint8* data, atUint64 length)
    : m_length(length),
      m_position(0),
      m_bitPosition(0),
      m_endian(Endian::LittleEndian),
      m_progressCallback(nullptr)
{
    if (!data)
        THROW_INVALID_DATA_EXCEPTION("data cannot be NULL");
    if (length == 0)
        THROW_INVALID_OPERATION_EXCEPTION("length cannot be 0");

    m_data = new atUint8[m_length];
    memcpy(m_data, data, m_length);
}

BinaryReader::BinaryReader(const std::string& filename, std::function<void(int)> progFun)
    : m_data(NULL),
      m_length(0),
      m_filepath(filename),
      m_position(0),
      m_bitPosition(0),
      m_endian(Endian::LittleEndian),
      m_progressCallback(progFun)
{
    loadData();
}

BinaryReader::~BinaryReader()
{
    delete[] m_data;
    m_data = NULL;
}

void BinaryReader::setEndian(Endian endian)
{
    m_endian = endian;
}

Endian BinaryReader::endian() const
{
    return m_endian;
}

bool BinaryReader::isBigEndian() const
{
    return (m_endian == Endian::BigEndian);
}

bool BinaryReader::isLittleEndian() const
{
    return (m_endian == Endian::LittleEndian);
}

bool BinaryReader::isOpen() const
{
    return m_data != nullptr;
}

void BinaryReader::seek(atInt64 position, SeekOrigin origin)
{
    switch (origin)
    {
    case SeekOrigin::Begin:
        if ((position < 0 || (atInt64)position > (atInt64)m_length))
            THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", position);
        m_position = position;
    break;
    case SeekOrigin::Current:
        if ((((atInt64)m_position + position) < 0 || (m_position + position) > m_length))
            THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", position);
        m_position += position;
    break;
    case SeekOrigin::End:
        if ((((atInt64)m_length - position < 0) || (m_length - position) > m_length))
            THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", position);
        m_position = m_length - position;
    break;
    }
}

bool BinaryReader::atEnd() const
{
    return m_position >= m_length;
}

atUint64 BinaryReader::position() const
{
    return m_position;
}

atUint64 BinaryReader::length() const
{
    return m_length;
}

void BinaryReader::setData(const atUint8* data, atUint64 length)
{
    if (m_data)
        delete[] m_data;

    m_data = (atUint8*)data;
    m_length = length;
    m_position = 0;
    m_bitPosition = 0;
}

atUint8* BinaryReader::data() const
{
    atUint8* ret = new atUint8[m_length];
    memset(ret, 0, m_length);
    memcpy(ret, m_data, m_length);
    return ret;
}

void BinaryReader::setFilepath(const std::string& filepath)
{
    m_filepath = filepath;
}

std::string BinaryReader::filepath() const
{
    return m_filepath;
}

void BinaryReader::seekBit(int bit)
{
    if (!m_data)
        loadData();

    if (bit < 0 || bit > 7)
        THROW_INVALID_OPERATION_EXCEPTION("bit out of range %i %s",  bit, (bit < 0 ? "< 0" : "> 7"));

    m_bitPosition = bit;
}

bool BinaryReader::readBit()
{
    if (!m_data)
        loadData();
    if (m_position > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    bool ret = (*(atUint8*)(m_data + m_position) & (1 << m_bitPosition));

    m_bitPosition++;
    if (m_bitPosition > 7)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    return ret;
}

atInt8 BinaryReader::readByte()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + 1 > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    return *(atInt8*)(m_data + m_position++);
}

atUint8 BinaryReader::readUByte()
{
    if (!m_data)
        loadData();

    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + 1 > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    return *(atUint8*)(m_data + m_position++);
}

atInt8* BinaryReader::readBytes(atInt64 length)
{
    return (atInt8*)readUBytes(length);
}

atUint8* BinaryReader::readUBytes(atInt64 length)
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    if (m_position + length > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    atUint8* ret;
    ret = new atUint8[length];

    memcpy(ret, (const atUint8*)(m_data + m_position), length);
    m_position += length;
    return ret;
}

atInt16 BinaryReader::readInt16()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    if (m_position + sizeof(atInt16) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);
    atInt16 ret = *(atInt16*)(m_data + m_position);
    m_position += sizeof(atInt16);

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swap16(ret);
    return ret;
}

atUint16 BinaryReader::readUint16()
{
    return readInt16();
}

atInt32 BinaryReader::readInt32()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    if (m_position + sizeof(atInt32) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);
    atInt32 ret = *(atInt32*)(m_data + m_position);
    m_position += 4;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swap32(ret);
    return ret;
}

atUint32 BinaryReader::readUint32()
{
    return readInt32();
}

atInt64 BinaryReader::readInt64()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(atInt64) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    atInt64 ret = *(atInt64*)(m_data + m_position);
    m_position += 8;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swap64(ret);
    return ret;
}

atUint64 BinaryReader::readUint64()
{
    return readUint64();
}

float BinaryReader::readFloat()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(float) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    float ret = *(float*)(m_data + m_position);
    m_position += 4;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swapFloat(ret);
    return ret;
}

double BinaryReader::readDouble()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(double) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    double ret = *(double*)(m_data + m_position);
    m_position += 8;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swapDouble(ret);

    return ret;
}

bool BinaryReader::readBool()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(bool) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    bool ret = *(bool*)(m_data + m_position);
    m_position += 1;
    return ret;
}

std::string BinaryReader::readUnicode()
{
    if (!m_data)
        loadData();
    std::string ret;
    std::vector<short> tmp;
    atUint16 chr = readUint16();
    for(;;)
    {
        if (!chr)
            break;
        tmp.push_back(chr);
        chr = readUint16();
    }

    utf8::utf16to8(tmp.begin(), tmp.end(), back_inserter(ret));
    return ret;
}

std::string BinaryReader::readString()
{
    std::string ret = "";
    atUint8 chr = readByte();

    while (chr != 0)
    {
        ret += chr;
        chr = readByte();
    }

    return ret;
}

void BinaryReader::setProgressCallback(std::function<void (int)> cb)
{
    m_progressCallback = cb;
}

void BinaryReader::loadData()
{
    FILE* in;
    atUint32 length;
    in = fopen(m_filepath.c_str(), "rb");

    if (!in)
        THROW_FILE_NOT_FOUND_EXCEPTION(m_filepath);

    fseek(in, 0, SEEK_END);
    length = ftell(in);
    fseek(in, 0, SEEK_SET);
#ifdef HW_RVL
    m_data = (Uint8*)memalign(32, length);
#else
    m_data = new atUint8[length];
#endif

    atUint32 done = 0;
    atUint32 blocksize = BLOCKSZ;
    do
    {
        if (blocksize > length - done)
            blocksize = length - done;

        atInt32 ret = fread(m_data + done, 1, blocksize, in);

        if (ret < 0)
            THROW_IO_EXCEPTION("Error reading data from disk");
        else if (ret == 0)
            break;

        done += ret;

        if (m_progressCallback)
            m_progressCallback((int)((float)(done* 100.f)/length));

    } while (done < length);

    fclose(in);
    m_length = length;
    m_position = 0;
    m_bitPosition = 0;
}

}
}
<commit_msg>* Fix infinite recursion in BinaryReader::readUint64<commit_after>// This file is part of libAthena.
//
// libAthena 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.
//
// libAthena 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 libAthena.  If not, see <http://www.gnu.org/licenses/>

#include "Athena/BinaryReader.hpp"
#include "Athena/IOException.hpp"
#include "Athena/FileNotFoundException.hpp"
#include "Athena/InvalidDataException.hpp"
#include "Athena/InvalidOperationException.hpp"
#include "utf8.h"

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <cstring>

#ifdef HW_RVL
#include <malloc.h>
#endif // HW_RVL

namespace Athena
{
namespace io
{
BinaryReader::BinaryReader(const atUint8* data, atUint64 length)
    : m_length(length),
      m_position(0),
      m_bitPosition(0),
      m_endian(Endian::LittleEndian),
      m_progressCallback(nullptr)
{
    if (!data)
        THROW_INVALID_DATA_EXCEPTION("data cannot be NULL");
    if (length == 0)
        THROW_INVALID_OPERATION_EXCEPTION("length cannot be 0");

    m_data = new atUint8[m_length];
    memcpy(m_data, data, m_length);
}

BinaryReader::BinaryReader(const std::string& filename, std::function<void(int)> progFun)
    : m_data(NULL),
      m_length(0),
      m_filepath(filename),
      m_position(0),
      m_bitPosition(0),
      m_endian(Endian::LittleEndian),
      m_progressCallback(progFun)
{
    loadData();
}

BinaryReader::~BinaryReader()
{
    delete[] m_data;
    m_data = NULL;
}

void BinaryReader::setEndian(Endian endian)
{
    m_endian = endian;
}

Endian BinaryReader::endian() const
{
    return m_endian;
}

bool BinaryReader::isBigEndian() const
{
    return (m_endian == Endian::BigEndian);
}

bool BinaryReader::isLittleEndian() const
{
    return (m_endian == Endian::LittleEndian);
}

bool BinaryReader::isOpen() const
{
    return m_data != nullptr;
}

void BinaryReader::seek(atInt64 position, SeekOrigin origin)
{
    switch (origin)
    {
    case SeekOrigin::Begin:
        if ((position < 0 || (atInt64)position > (atInt64)m_length))
            THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", position);
        m_position = position;
    break;
    case SeekOrigin::Current:
        if ((((atInt64)m_position + position) < 0 || (m_position + position) > m_length))
            THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", position);
        m_position += position;
    break;
    case SeekOrigin::End:
        if ((((atInt64)m_length - position < 0) || (m_length - position) > m_length))
            THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", position);
        m_position = m_length - position;
    break;
    }
}

bool BinaryReader::atEnd() const
{
    return m_position >= m_length;
}

atUint64 BinaryReader::position() const
{
    return m_position;
}

atUint64 BinaryReader::length() const
{
    return m_length;
}

void BinaryReader::setData(const atUint8* data, atUint64 length)
{
    if (m_data)
        delete[] m_data;

    m_data = (atUint8*)data;
    m_length = length;
    m_position = 0;
    m_bitPosition = 0;
}

atUint8* BinaryReader::data() const
{
    atUint8* ret = new atUint8[m_length];
    memset(ret, 0, m_length);
    memcpy(ret, m_data, m_length);
    return ret;
}

void BinaryReader::setFilepath(const std::string& filepath)
{
    m_filepath = filepath;
}

std::string BinaryReader::filepath() const
{
    return m_filepath;
}

void BinaryReader::seekBit(int bit)
{
    if (!m_data)
        loadData();

    if (bit < 0 || bit > 7)
        THROW_INVALID_OPERATION_EXCEPTION("bit out of range %i %s",  bit, (bit < 0 ? "< 0" : "> 7"));

    m_bitPosition = bit;
}

bool BinaryReader::readBit()
{
    if (!m_data)
        loadData();
    if (m_position > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    bool ret = (*(atUint8*)(m_data + m_position) & (1 << m_bitPosition));

    m_bitPosition++;
    if (m_bitPosition > 7)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    return ret;
}

atInt8 BinaryReader::readByte()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + 1 > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    return *(atInt8*)(m_data + m_position++);
}

atUint8 BinaryReader::readUByte()
{
    if (!m_data)
        loadData();

    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + 1 > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    return *(atUint8*)(m_data + m_position++);
}

atInt8* BinaryReader::readBytes(atInt64 length)
{
    return (atInt8*)readUBytes(length);
}

atUint8* BinaryReader::readUBytes(atInt64 length)
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    if (m_position + length > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    atUint8* ret;
    ret = new atUint8[length];

    memcpy(ret, (const atUint8*)(m_data + m_position), length);
    m_position += length;
    return ret;
}

atInt16 BinaryReader::readInt16()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    if (m_position + sizeof(atInt16) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);
    atInt16 ret = *(atInt16*)(m_data + m_position);
    m_position += sizeof(atInt16);

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swap16(ret);
    return ret;
}

atUint16 BinaryReader::readUint16()
{
    return readInt16();
}

atInt32 BinaryReader::readInt32()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }

    if (m_position + sizeof(atInt32) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);
    atInt32 ret = *(atInt32*)(m_data + m_position);
    m_position += 4;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swap32(ret);
    return ret;
}

atUint32 BinaryReader::readUint32()
{
    return readInt32();
}

atInt64 BinaryReader::readInt64()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(atInt64) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    atInt64 ret = *(atInt64*)(m_data + m_position);
    m_position += 8;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swap64(ret);
    return ret;
}

atUint64 BinaryReader::readUint64()
{
    return readInt64();
}

float BinaryReader::readFloat()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(float) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    float ret = *(float*)(m_data + m_position);
    m_position += 4;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swapFloat(ret);
    return ret;
}

double BinaryReader::readDouble()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(double) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    double ret = *(double*)(m_data + m_position);
    m_position += 8;

    if ((!utility::isSystemBigEndian() && isBigEndian()) || (utility::isSystemBigEndian() && isLittleEndian()))
        ret = utility::swapDouble(ret);

    return ret;
}

bool BinaryReader::readBool()
{
    if (!m_data)
        loadData();

    if (m_bitPosition > 0)
    {
        m_bitPosition = 0;
        m_position += sizeof(atUint8);
    }
    if (m_position + sizeof(bool) > m_length)
        THROW_IO_EXCEPTION("Position %0.16X outside stream bounds ", m_position);

    bool ret = *(bool*)(m_data + m_position);
    m_position += 1;
    return ret;
}

std::string BinaryReader::readUnicode()
{
    if (!m_data)
        loadData();
    std::string ret;
    std::vector<short> tmp;
    atUint16 chr = readUint16();
    for(;;)
    {
        if (!chr)
            break;
        tmp.push_back(chr);
        chr = readUint16();
    }

    utf8::utf16to8(tmp.begin(), tmp.end(), back_inserter(ret));
    return ret;
}

std::string BinaryReader::readString()
{
    std::string ret = "";
    atUint8 chr = readByte();

    while (chr != 0)
    {
        ret += chr;
        chr = readByte();
    }

    return ret;
}

void BinaryReader::setProgressCallback(std::function<void (int)> cb)
{
    m_progressCallback = cb;
}

void BinaryReader::loadData()
{
    FILE* in;
    atUint32 length;
    in = fopen(m_filepath.c_str(), "rb");

    if (!in)
        THROW_FILE_NOT_FOUND_EXCEPTION(m_filepath);

    fseek(in, 0, SEEK_END);
    length = ftell(in);
    fseek(in, 0, SEEK_SET);
#ifdef HW_RVL
    m_data = (Uint8*)memalign(32, length);
#else
    m_data = new atUint8[length];
#endif

    atUint32 done = 0;
    atUint32 blocksize = BLOCKSZ;
    do
    {
        if (blocksize > length - done)
            blocksize = length - done;

        atInt32 ret = fread(m_data + done, 1, blocksize, in);

        if (ret < 0)
            THROW_IO_EXCEPTION("Error reading data from disk");
        else if (ret == 0)
            break;

        done += ret;

        if (m_progressCallback)
            m_progressCallback((int)((float)(done* 100.f)/length));

    } while (done < length);

    fclose(in);
    m_length = length;
    m_position = 0;
    m_bitPosition = 0;
}

}
}
<|endoftext|>


<commit_before>/*
** Author(s):
**  - Pierre Roullon <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2011, 2012 Aldebararan Robotics
*/
#include <qic/object.h>
#include <qic/future.h>
#include <qic/value.h>
#include "future_p.h"
#include "object_p.h"
#include "value_p.h"

#include <qitype/genericobject.hpp>
#include <qitype/genericvalue.hpp>
#include <qitype/genericobjectbuilder.hpp>

qiLogCategory("qimessaging.object");

static qi::GenericValuePtr c_call(const std::string &complete_sig,
                                          qi_object_method_t func,
                                              void* data,
                                  const qi::GenericFunctionParameters& params)
{
  //TODO: move to register
  std::vector<std::string> vs = qi::signatureSplit(std::string(complete_sig));
  qi_value_t* value = qi_value_create(vs[2].c_str());
  qi_value_t* ret = qi_value_create(vs[0].c_str());
  // First argument is the DynamicObject instance, drop it.
  qi::GenericFunctionParameters remove_first;
  if (params.size() > 1)
    remove_first.insert(remove_first.end(), params.begin()+1, params.end());
  qi::GenericValue &gvp = qi_value_cpp(value);
  //TODO: there is a copy here
  gvp = qi::GenericValue::makeTuple(remove_first);
  std::cout << "Complete sig:" << complete_sig << std::endl;

  if (func)
    func(complete_sig.c_str(), value, ret, data);

  qi::GenericValuePtr &gvpr = qi_value_cpp(ret);
  qi::GenericValuePtr re = gvpr;
  //just reset the gvp, we dont want destroy to destroy it...
  gvpr.type = 0;
  gvpr.value = 0;
  qi_value_destroy(value);
  qi_value_destroy(ret);
  return re;
}

static qi::GenericValuePtr c_signal_callback(const std::vector<qi::GenericValuePtr>& args,
                                             const std::string &params_sigs,
                                             qi_object_signal_callback_t f,
                                             void *user_data) {
  qiLogInfo() << "Signal Callback(" << params_sigs << ")";

  qi_value_t* params = qi_value_create(params_sigs.c_str());
  qi::GenericValue &gvp = qi_value_cpp(params);
  gvp = qi::GenericValue::makeTuple(args);
  f(params, user_data);
  qi_value_destroy(params);
  return qi::GenericValuePtr();
}

#ifdef __cplusplus
extern "C"
{
#endif

void qiFutureCAdapter(qi::Future<qi::GenericValuePtr> result, qi::Promise<qi::GenericValue> promise) {
  if (result.hasError()) {
    promise.setError(result.error());
    return;
  }
  qi::GenericValue gv;
  //we take the ownership of the GVP content. we are now responsible for freeing it.
  gv.reset(result.value(), false, true);
  promise.setValue(gv);
}

qi_object_t *qi_object_create()
{
  qi::ObjectPtr *obj = new qi::ObjectPtr();
  return (qi_object_t *) obj;
}

void        qi_object_destroy(qi_object_t *object)
{
  qi::ObjectPtr *obj = &qi_object_cpp(object);
  delete obj;
}

qi_future_t *qi_object_call(qi_object_t *object, const char *signature_c, qi_value_t *params)
{
  qi::ObjectPtr             &obj = qi_object_cpp(object);
  qi::GenericValue           gv  = qi_value_cpp(params);

  qi::Future<qi::GenericValuePtr> res = obj->metaCall(signature_c, gv.asTupleValuePtr());
  qi::Promise<qi::GenericValue> prom;
  res.connect(boost::bind<void>(&qiFutureCAdapter, _1, prom));
  return qi_cpp_promise_get_future(prom);
}

// ObjectBuilder

qi_object_builder_t *qi_object_builder_create()
{
  qi::GenericObjectBuilder *ob = new qi::GenericObjectBuilder();
  return (qi_object_builder_t *) ob;
}

void        qi_object_builder_destroy(qi_object_builder_t *object_builder)
{
  qi::GenericObjectBuilder *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  delete ob;
}

qi_value_t*          qi_object_get_metaobject(qi_object_t *object)
{
  qi::ObjectPtr &obj = *(reinterpret_cast<qi::ObjectPtr *>(object));
  const qi::MetaObject &mo = obj->metaObject();
  qi_value_t *ret = qi_value_create("");

  qi_value_cpp(ret) = qi::GenericValue::from(mo);
  return ret;
}

int                 qi_object_event_emit(qi_object_t* object, const char *signature, qi_value_t* params) {
  qi::ObjectPtr       &obj = qi_object_cpp(object);
  qi::GenericValuePtr &val = qi_value_cpp(params);
  if (qi_value_get_kind(params) != QI_VALUE_KIND_TUPLE)
    return -1;
  obj->metaPost(signature, val.asTupleValuePtr());
  return 0;
}

qi_future_t*        qi_object_event_connect(qi_object_t* object, const char *signature, qi_object_signal_callback_t f, void* user_data) {
  qi::ObjectPtr &obj = qi_object_cpp(object);
  std::vector<std::string> vs = qi::signatureSplit(std::string(signature));
  qi::DynamicFunction fn = boost::bind<qi::GenericValuePtr>(&c_signal_callback, _1, vs[2], f, user_data);
  return qi_future_wrap(obj->xConnect(signature, qi::makeDynamicGenericFunction(fn)));
}

qi_future_t*        qi_object_event_disconnect(qi_object_t* object, unsigned long long id) {
  qi::ObjectPtr &obj = qi_object_cpp(object);
  return qi_future_wrap(obj->disconnect(id));
}

int          qi_object_builder_register_method(qi_object_builder_t *object_builder, const char *complete_signature, qi_object_method_t func, void *data)
{
  qi::GenericObjectBuilder  *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  std::string signature(complete_signature);
  std::vector<std::string>  sigInfo;

  sigInfo = qi::signatureSplit(signature);
  ob->xAdvertiseMethod(sigInfo[0], sigInfo[1], sigInfo[2],
    makeDynamicGenericFunction(
    boost::bind(&c_call, std::string(complete_signature), func, data, _1)));
  return 0;
}

int          qi_object_builder_register_event(qi_object_builder_t *object_builder, const char *complete_signature)
{
  qi::GenericObjectBuilder  *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  std::vector<std::string>  sigInfo;
  sigInfo = qi::signatureSplit(complete_signature);
  return ob->xAdvertiseSignal(sigInfo[1], sigInfo[2]);
}

int          qi_object_builder_register_property(qi_object_builder_t *object_builder, const char *complete_signature)
{
  qi::GenericObjectBuilder  *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  std::vector<std::string>  sigInfo;
  sigInfo = qi::signatureSplit(complete_signature);
  return ob->xAdvertiseProperty(sigInfo[1], sigInfo[2]);
}

qi_object_t*         qi_object_builder_get_object(qi_object_builder_t *object_builder) {
  qi::GenericObjectBuilder *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  qi_object_t *obj = qi_object_create();
  qi::ObjectPtr &o = *(reinterpret_cast<qi::ObjectPtr *>(obj));

  o = ob->object();
  return obj;
}

#ifdef __cplusplus
}
#endif

<commit_msg>c: Adapt for xConnect->connect change.<commit_after>/*
** Author(s):
**  - Pierre Roullon <proullon@aldebaran-robotics.com>
**
** Copyright (C) 2010, 2011, 2012 Aldebararan Robotics
*/
#include <qic/object.h>
#include <qic/future.h>
#include <qic/value.h>
#include "future_p.h"
#include "object_p.h"
#include "value_p.h"

#include <qitype/genericobject.hpp>
#include <qitype/genericvalue.hpp>
#include <qitype/genericobjectbuilder.hpp>

qiLogCategory("qimessaging.object");

static qi::GenericValuePtr c_call(const std::string &complete_sig,
                                          qi_object_method_t func,
                                              void* data,
                                  const qi::GenericFunctionParameters& params)
{
  //TODO: move to register
  std::vector<std::string> vs = qi::signatureSplit(std::string(complete_sig));
  qi_value_t* value = qi_value_create(vs[2].c_str());
  qi_value_t* ret = qi_value_create(vs[0].c_str());
  // First argument is the DynamicObject instance, drop it.
  qi::GenericFunctionParameters remove_first;
  if (params.size() > 1)
    remove_first.insert(remove_first.end(), params.begin()+1, params.end());
  qi::GenericValue &gvp = qi_value_cpp(value);
  //TODO: there is a copy here
  gvp = qi::GenericValue::makeTuple(remove_first);
  std::cout << "Complete sig:" << complete_sig << std::endl;

  if (func)
    func(complete_sig.c_str(), value, ret, data);

  qi::GenericValuePtr &gvpr = qi_value_cpp(ret);
  qi::GenericValuePtr re = gvpr;
  //just reset the gvp, we dont want destroy to destroy it...
  gvpr.type = 0;
  gvpr.value = 0;
  qi_value_destroy(value);
  qi_value_destroy(ret);
  return re;
}

static qi::GenericValuePtr c_signal_callback(const std::vector<qi::GenericValuePtr>& args,
                                             const std::string &params_sigs,
                                             qi_object_signal_callback_t f,
                                             void *user_data) {
  qiLogInfo() << "Signal Callback(" << params_sigs << ")";

  qi_value_t* params = qi_value_create(params_sigs.c_str());
  qi::GenericValue &gvp = qi_value_cpp(params);
  gvp = qi::GenericValue::makeTuple(args);
  f(params, user_data);
  qi_value_destroy(params);
  return qi::GenericValuePtr();
}

#ifdef __cplusplus
extern "C"
{
#endif

void qiFutureCAdapter(qi::Future<qi::GenericValuePtr> result, qi::Promise<qi::GenericValue> promise) {
  if (result.hasError()) {
    promise.setError(result.error());
    return;
  }
  qi::GenericValue gv;
  //we take the ownership of the GVP content. we are now responsible for freeing it.
  gv.reset(result.value(), false, true);
  promise.setValue(gv);
}

qi_object_t *qi_object_create()
{
  qi::ObjectPtr *obj = new qi::ObjectPtr();
  return (qi_object_t *) obj;
}

void        qi_object_destroy(qi_object_t *object)
{
  qi::ObjectPtr *obj = &qi_object_cpp(object);
  delete obj;
}

qi_future_t *qi_object_call(qi_object_t *object, const char *signature_c, qi_value_t *params)
{
  qi::ObjectPtr             &obj = qi_object_cpp(object);
  qi::GenericValue           gv  = qi_value_cpp(params);

  qi::Future<qi::GenericValuePtr> res = obj->metaCall(signature_c, gv.asTupleValuePtr());
  qi::Promise<qi::GenericValue> prom;
  res.connect(boost::bind<void>(&qiFutureCAdapter, _1, prom));
  return qi_cpp_promise_get_future(prom);
}

// ObjectBuilder

qi_object_builder_t *qi_object_builder_create()
{
  qi::GenericObjectBuilder *ob = new qi::GenericObjectBuilder();
  return (qi_object_builder_t *) ob;
}

void        qi_object_builder_destroy(qi_object_builder_t *object_builder)
{
  qi::GenericObjectBuilder *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  delete ob;
}

qi_value_t*          qi_object_get_metaobject(qi_object_t *object)
{
  qi::ObjectPtr &obj = *(reinterpret_cast<qi::ObjectPtr *>(object));
  const qi::MetaObject &mo = obj->metaObject();
  qi_value_t *ret = qi_value_create("");

  qi_value_cpp(ret) = qi::GenericValue::from(mo);
  return ret;
}

int                 qi_object_event_emit(qi_object_t* object, const char *signature, qi_value_t* params) {
  qi::ObjectPtr       &obj = qi_object_cpp(object);
  qi::GenericValuePtr &val = qi_value_cpp(params);
  if (qi_value_get_kind(params) != QI_VALUE_KIND_TUPLE)
    return -1;
  obj->metaPost(signature, val.asTupleValuePtr());
  return 0;
}

qi_future_t*        qi_object_event_connect(qi_object_t* object, const char *signature, qi_object_signal_callback_t f, void* user_data) {
  qi::ObjectPtr &obj = qi_object_cpp(object);
  std::vector<std::string> vs = qi::signatureSplit(std::string(signature));
  qi::DynamicFunction fn = boost::bind<qi::GenericValuePtr>(&c_signal_callback, _1, vs[2], f, user_data);
  return qi_future_wrap(obj->connect(signature, qi::makeDynamicGenericFunction(fn)));
}

qi_future_t*        qi_object_event_disconnect(qi_object_t* object, unsigned long long id) {
  qi::ObjectPtr &obj = qi_object_cpp(object);
  return qi_future_wrap(obj->disconnect(id));
}

int          qi_object_builder_register_method(qi_object_builder_t *object_builder, const char *complete_signature, qi_object_method_t func, void *data)
{
  qi::GenericObjectBuilder  *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  std::string signature(complete_signature);
  std::vector<std::string>  sigInfo;

  sigInfo = qi::signatureSplit(signature);
  ob->xAdvertiseMethod(sigInfo[0], sigInfo[1], sigInfo[2],
    makeDynamicGenericFunction(
    boost::bind(&c_call, std::string(complete_signature), func, data, _1)));
  return 0;
}

int          qi_object_builder_register_event(qi_object_builder_t *object_builder, const char *complete_signature)
{
  qi::GenericObjectBuilder  *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  std::vector<std::string>  sigInfo;
  sigInfo = qi::signatureSplit(complete_signature);
  return ob->xAdvertiseSignal(sigInfo[1], sigInfo[2]);
}

int          qi_object_builder_register_property(qi_object_builder_t *object_builder, const char *complete_signature)
{
  qi::GenericObjectBuilder  *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  std::vector<std::string>  sigInfo;
  sigInfo = qi::signatureSplit(complete_signature);
  return ob->xAdvertiseProperty(sigInfo[1], sigInfo[2]);
}

qi_object_t*         qi_object_builder_get_object(qi_object_builder_t *object_builder) {
  qi::GenericObjectBuilder *ob = reinterpret_cast<qi::GenericObjectBuilder *>(object_builder);
  qi_object_t *obj = qi_object_create();
  qi::ObjectPtr &o = *(reinterpret_cast<qi::ObjectPtr *>(obj));

  o = ob->object();
  return obj;
}

#ifdef __cplusplus
}
#endif

<|endoftext|>


<commit_before>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>

int main (void) {
    return 0;
}

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        // We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci)
        //int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line)
        //int totalLoci = size/(272*2);
        //std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0));
        //std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0));
        //long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates
        //unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;
        unsigned long long int lociPerThread = numLoci;

        //std::thread t;
        //std::thread t[numThreads];
        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            unsigned long long firstLocus = (unsigned long long) threadRunning * lociPerThread;
            unsigned long long finishingLocus = ((unsigned long long) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;

            std::cout << "Got to the function call" << std::endl;
            //calcPWPforRange(firstLocus, finishingLocus, 272, readCounts, pwp, weightings);
            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
            //std::thread t = std::thread(calcPWPforRange, firstLocus, finishingLocus, std::thread(readCounts), std::thread(pwpThreads[threadRunning]), std::thread(weightingsThreads[threadRunning]));
        }

        //t.join();
        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
        }

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0));
        std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0));
        for (int element = 0; element < 272; element++) {
            for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) {
                for (int threadVector = 0; threadVector <= numThreads; threadVector++) {
                    weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement];
                    pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement];
                }
            }
        }

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
    /*

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;

     //usage: calcPWPforRange(0, 1000000, readCounts) // where readCounts is a vector with all the read count data
     //this function will return both the pwp calculations for the matrix as well as the weightings, which will later
     //be summed across all threads

     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
     if (locus % 100000 == 0) {
     std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
     }

     int coverages[numIndividuals];
     double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

     for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
     unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
     unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

     //std::cout << "\tTrying to access readCounts[" << minorIndex << "]" << ". locus: " << locus << ". numIndividuals: " << numIndividuals << ". tortoise: " << tortoise << std::endl;

     coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
     //std::cout << "\t\tCalced coverage in line 232" << std::endl;
     //std::cout << coverages[tortoise] << std::endl;

     //std::cout << "Total coverage for tortoise " << tortoise << " at locus " << locus+1 << ": " << coverages[tortoise] << std::endl;

     if ( coverages[tortoise] > 0 ) {
     //std::cout << "Made it to line 222 for locus " << locus << std::endl;
     majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
     //std::cout << "Major allele frequency for individual " << tortoise << " at locus " << locus << ": " << majorAlleleFreqs[tortoise] << std::endl;
     //std::cout << "\t\t\tCalced majorAlleleFreqs[" << tortoise << "] in line 239" << std::endl;
     if (coverages[tortoise] > 1) {
     unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
     //std::cout << "\t\t\t\tCalced weightings in line 245 for tortoise[" << tortoise << "]" << std::endl;

     threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
     //std::cout << "\t\t\t\t\tCalced pwp in line 247 for tortoise[" << tortoise << "]" << std::endl;
     //std::cout << "Locus self weighting for individual " << tortoise << " at locus: " << locus << ": " << locusWeighting << ". Locus self PWP: " << double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]))) / (double((coverages[tortoise])-1.0)) << std::endl;
     //std::cout << "\tmajorAlleleFreq: " << majorAlleleFreqs[tortoise] << ". Coverages: " << double(coverages[tortoise]) << ". readCounts: " << double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]) << std::endl;
     //std::cout << "PWP for self:" << pwp[tortoise][tortoise] << std::endl;
     //std::cout << "Made it to line 233 for locus " << locus << ". Weightings = " << weightings[tortoise][tortoise] << ". PWP = " << pwp[tortoise][tortoise] << std::endl;
     }

     for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
     if (coverages[comparisonTortoise] > 0) {

     //std::cout << "Coverages for the two comparison individuals: " << std::to_string((double)coverages[tortoise]) << " and " << std::to_string((double)coverages[comparisonTortoise]) << std::endl;
     //std::cout << "Major allele freqs for the two comparison individuals: " << std::to_string(majorAlleleFreqs[tortoise]) << " and " << std::to_string(majorAlleleFreqs[comparisonTortoise]) << std::endl;
     double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
     threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
     //std::cout << "locusDiffPWP: " << (double)locusWeighting * ((double)majorAlleleFreqs[tortoise] * (1-(double)majorAlleleFreqs[comparisonTortoise]) + (double)majorAlleleFreqs[comparisonTortoise] * (1-(double)majorAlleleFreqs[tortoise])) << std::endl;
     threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
     //std::cout << "\t\t\t\t\t\tCalced pwp for tortoise[" << tortoise << "] and comparisonTortoise[" << comparisonTortoise << "]" << std::endl;
     //std::cout << pwp[tortoise][comparisonTortoise] << std::endl;
     //std::cout << "Cumulative weightings = " << weightings[tortoise][comparisonTortoise] << ". Cumulative PWP = " << pwp[tortoise][comparisonTortoise] << std::endl;
     }
     }
     }
     }
     delete[] majorAlleleFreqs; // Needed to avoid memory leaks
     //delete[] coverages; // Since that locus is done, and this variable holds per-locus coverages, we can nuke the coverages to start anew
     }
     */
    return 0;

}
<commit_msg>Minor changes<commit_after>//
//  calcPWP.cpp
//
//
//  Created by Evan McCartney-Melstad on 1/10/15.
//
//

#include "calcPWP.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>

int main (void) {
    return 0;
}

int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {

    //****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****

    std::streampos size;
    std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);
    //ifstream file ("test500k.binary8bitunsigned", ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = file.tellg(); // Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!
        file.seekg (0, std::ios::beg); // Go back to the beginning of the file
        //file.read((char*)readCounts, size); // cast to a char* to give to file.read

        //unsigned char* readCounts;
        //readCounts = new unsigned char[size];
        std::vector<unsigned char> readCounts(size);
        file.read((char*) &readCounts[0], size);
        file.close();

        std::cout << "the entire file content is in memory" << std::endl;
        std::cout << "the total size of the file is " << size << std::endl;
        std::cout << "the number of elements in the readCounts vector is: " << readCounts.size() << std::endl; // Will give the total size bytes divided by the size of one element--so it gives the number of elements

        // We now have an array of numIndividuals * 2 (major and minor allele) * 1million (loci)
        //int totalLoci = (int)size / (numIndividuals*2); // The 1 million locus file has 999,999 sites in it (because of header line)
        //int totalLoci = size/(272*2);
        //std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0));
        //std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0));
        //long double pwp[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the pwp estimates
        //unsigned long long int weightings[numIndividuals][numIndividuals] = {0.0}; // This is the matrix that will hold the weightings--need to use a long long because the values are basically equal to the coverage squared by the end

        /* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
         vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0))    and   std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))

         First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
         vector of two-dimensional vectors...
         */
        std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); //pwpThreads[0] is the first 2D array for the first thread, etc...
        std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );

        // Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size/(numIndividuals*2))/numThreads
        //unsigned long long int lociPerThread = numLoci / numThreads;
        unsigned long long int lociPerThread = numLoci;

        //std::thread t;
        //std::thread t[numThreads];
        std::vector<std::thread> threadsVec;
        for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
            unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
            unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;

            std::cout << "Got to the function call" << std::endl;
            //calcPWPforRange(firstLocus, finishingLocus, 272, readCounts, pwp, weightings);
            threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
            //std::thread t = std::thread(calcPWPforRange, firstLocus, finishingLocus, std::thread(readCounts), std::thread(pwpThreads[threadRunning]), std::thread(weightingsThreads[threadRunning]));
        }

        //t.join();
        // Wait on threads to finish
        for (int i = 0; i < numThreads; ++i) {
            threadsVec[i].join();
        }

        // Now aggregate the results of the threads and print final results
        std::vector<std::vector<long double>> weightingsSum(272, std::vector<long double>(272,0));
        std::vector<std::vector<long double>> pwpSum(272, std::vector<long double>(272,0));
        for (int element = 0; element < 272; element++) {
            for (int comparisonElement = 0; comparisonElement <= element; comparisonElement++) {
                for (int threadVector = 0; threadVector <= numThreads; threadVector++) {
                    weightingsSum[element][comparisonElement] += weightingsThreads[threadVector][element][comparisonElement];
                    pwpSum[element][comparisonElement] += pwpThreads[threadVector][element][comparisonElement];
                }
            }
        }

        // Now print out the final output to the pairwise pi file:
        std::ofstream pwpOUT (outFile);
        int rowCounter = 0;
        if (!pwpOUT) {
            std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
        } else {
            for (int tortoise=0; tortoise <= (numIndividuals-1); tortoise++) {
                for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
                    rowCounter++;

                    //std::cout << "Made it past the beginning of the last end for loop" << std::endl;
                    //std::cout << "Tortoise numbers: " << tortoise << " and " << comparisonTortoise << std::endl;
                    if (weightingsSum[tortoise][comparisonTortoise] > 0) {
                        //std::cout << weightings[tortoise][comparisonTortoise] << std::endl;
                        //std::cout << pwp[tortoise][comparisonTortoise] / weightings[tortoise][comparisonTortoise] << std::endl;
                        pwpOUT << pwpSum[tortoise][comparisonTortoise] / weightingsSum[tortoise][comparisonTortoise] << std::endl;
                    } else {
                        pwpOUT << "NA" << std::endl;
                    }
                }
            }
        }
    } else std::cout << "Unable to open file";

    return 0;
}

//int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {
int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
    /*

     std::cout << "Calculating PWP for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;

     //usage: calcPWPforRange(0, 1000000, readCounts) // where readCounts is a vector with all the read count data
     //this function will return both the pwp calculations for the matrix as well as the weightings, which will later
     //be summed across all threads

     for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
     //std::cout << "Processing locus # " << locus << std::endl;
     if (locus % 100000 == 0) {
     std::cout << locus << " loci processed through calcPWPfromBinaryFile" << std::endl;
     }

     int coverages[numIndividuals];
     double *majorAlleleFreqs = new double[numIndividuals]; // This will hold the major allele frequencies for that locus for each tortoise

     for( int tortoise = 0; tortoise <= (numIndividuals-1); tortoise++ ) {
     unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
     unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;

     //std::cout << "\tTrying to access readCounts[" << minorIndex << "]" << ". locus: " << locus << ". numIndividuals: " << numIndividuals << ". tortoise: " << tortoise << std::endl;

     coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
     //std::cout << "\t\tCalced coverage in line 232" << std::endl;
     //std::cout << coverages[tortoise] << std::endl;

     //std::cout << "Total coverage for tortoise " << tortoise << " at locus " << locus+1 << ": " << coverages[tortoise] << std::endl;

     if ( coverages[tortoise] > 0 ) {
     //std::cout << "Made it to line 222 for locus " << locus << std::endl;
     majorAlleleFreqs[tortoise] = (double)mainReadCountVector[majorIndex] / (double)coverages[tortoise]; // Not necessarily an int, but could be 0 or 1
     //std::cout << "Major allele frequency for individual " << tortoise << " at locus " << locus << ": " << majorAlleleFreqs[tortoise] << std::endl;
     //std::cout << "\t\t\tCalced majorAlleleFreqs[" << tortoise << "] in line 239" << std::endl;
     if (coverages[tortoise] > 1) {
     unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);
     threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; // This is an int--discrete number of reads
     //std::cout << "\t\t\t\tCalced weightings in line 245 for tortoise[" << tortoise << "]" << std::endl;

     threadPWP[tortoise][tortoise] += double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(mainReadCountVector[majorIndex]))) / (double((coverages[tortoise])-1.0));
     //std::cout << "\t\t\t\t\tCalced pwp in line 247 for tortoise[" << tortoise << "]" << std::endl;
     //std::cout << "Locus self weighting for individual " << tortoise << " at locus: " << locus << ": " << locusWeighting << ". Locus self PWP: " << double(locusWeighting) * (2.0 * majorAlleleFreqs[tortoise] * (double(coverages[tortoise]) - double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]))) / (double((coverages[tortoise])-1.0)) << std::endl;
     //std::cout << "\tmajorAlleleFreq: " << majorAlleleFreqs[tortoise] << ". Coverages: " << double(coverages[tortoise]) << ". readCounts: " << double(readCounts[locus * numIndividuals * 2 + 2 * tortoise]) << std::endl;
     //std::cout << "PWP for self:" << pwp[tortoise][tortoise] << std::endl;
     //std::cout << "Made it to line 233 for locus " << locus << ". Weightings = " << weightings[tortoise][tortoise] << ". PWP = " << pwp[tortoise][tortoise] << std::endl;
     }

     for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
     if (coverages[comparisonTortoise] > 0) {

     //std::cout << "Coverages for the two comparison individuals: " << std::to_string((double)coverages[tortoise]) << " and " << std::to_string((double)coverages[comparisonTortoise]) << std::endl;
     //std::cout << "Major allele freqs for the two comparison individuals: " << std::to_string(majorAlleleFreqs[tortoise]) << " and " << std::to_string(majorAlleleFreqs[comparisonTortoise]) << std::endl;
     double locusWeighting = (double)coverages[tortoise] * (double)coverages[comparisonTortoise];
     threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
     //std::cout << "locusDiffPWP: " << (double)locusWeighting * ((double)majorAlleleFreqs[tortoise] * (1-(double)majorAlleleFreqs[comparisonTortoise]) + (double)majorAlleleFreqs[comparisonTortoise] * (1-(double)majorAlleleFreqs[tortoise])) << std::endl;
     threadPWP[tortoise][comparisonTortoise] += (double)locusWeighting * (majorAlleleFreqs[tortoise] * (1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * (1.0-majorAlleleFreqs[tortoise]));
     //std::cout << "\t\t\t\t\t\tCalced pwp for tortoise[" << tortoise << "] and comparisonTortoise[" << comparisonTortoise << "]" << std::endl;
     //std::cout << pwp[tortoise][comparisonTortoise] << std::endl;
     //std::cout << "Cumulative weightings = " << weightings[tortoise][comparisonTortoise] << ". Cumulative PWP = " << pwp[tortoise][comparisonTortoise] << std::endl;
     }
     }
     }
     }
     delete[] majorAlleleFreqs; // Needed to avoid memory leaks
     //delete[] coverages; // Since that locus is done, and this variable holds per-locus coverages, we can nuke the coverages to start anew
     }
     */
    return 0;

}
<|endoftext|>


<commit_before>// Macro MUONrecoNtuple.C (TO BE COMPILED)
// for testing the C++ reconstruction code
// and producing an Ntuple with reconstructed tracks
// in output file "MUONtrackReco.root".
// An example for using the Ntuple is in the macro MUONmassPlot.C

// Arguments:
//   FirstEvent (default 0)
//   LastEvent (default 0)
//   RecGeantHits (1 to reconstruct GEANT hits) (default 0)
//   FileName (for signal) (default "galice.root")
//   BkgGeantFileName (for background),
//      needed only if RecGeantHits = 1 and background to be added

// IMPORTANT NOTICE FOR USERS:
// under "root" or "root.exe", execute the following commands:
// 1. "gSystem->SetIncludePath("-I$ALICE_ROOT/MUON -I$ALICE_ROOT/STEER -I$ROOTSYS/include")" to get the right path at compilation time
// 2. ".x loadlibs.C" to load the shared libraries
// 3. ".x MUONrecoNtuple.C+()" with the right arguments, without forgetting the "+" which implies the compilation of the macro before its execution

#include <iostream.h>

#include <TClassTable.h>
#include <TClonesArray.h>
#include <TFile.h>
#include <TParticle.h>
#include <TROOT.h>
#include <TTree.h>

#include "AliHeader.h"
#include "AliRun.h"

#include "AliMUON.h"
#include "AliMUONEventReconstructor.h"
#include "AliMUONTrack.h"
#include "AliMUONTrackHit.h"
#include "AliMUONTrackParam.h"

// Classes for Ntuple ////////////////////////////////////////////////////

class AliMUONTrackRecNtuple : public TObject {
 public:
  // for direct access to members
  Int_t fCharge; // charge of reconstructed track (+/- 1)
  Float_t fPxRec; // Px of reconstructed track at vertex (GeV/c)
  Float_t fPyRec; // Py of reconstructed track at vertex (GeV/c)
  Float_t fPzRec; // Pz of reconstructed track at vertex (GeV/c)
  Float_t fZRec; // Z of reconstructed track at vertex (cm)
  Float_t fZRec1; // Z of reconstructed track at first hit (cm)
  Int_t fNHits; // number of hits
  Float_t fChi2; // chi2 of fit
  Float_t fPxGen; // Px of best compatible generated track at vertex (GeV/c)
  Float_t fPyGen; // Py of best compatible generated track at vertex (GeV/c)
  Float_t fPzGen; // Pz of best compatible generated track at vertex (GeV/c)
  AliMUONTrackRecNtuple(){;} // Constructor
  virtual ~AliMUONTrackRecNtuple(){;} // Destructor
 protected:
 private:
  ClassDef(AliMUONTrackRecNtuple, 1) // AliMUONTrackRecNtuple
    };

class AliMUONHeaderRecNtuple : public TObject {
 public:
  // for direct access to members
  Int_t fEvent; // event number
  AliMUONHeaderRecNtuple(){;} // Constructor
  virtual ~AliMUONHeaderRecNtuple(){;} // Destructor
 protected:
 private:
  ClassDef(AliMUONHeaderRecNtuple, 1) // AliMUONHeaderRecNtuple
    };

ClassImp(AliMUONTrackRecNtuple) // Class implementation in ROOT context
ClassImp(AliMUONHeaderRecNtuple) // Class implementation in ROOT context

  //__________________________________________________________________________
void AliMUONEventRecNtupleFill(AliMUONEventReconstructor *Reco, Int_t FillWrite = 0)
{
  // Fill Ntuple for reconstructed event pointed to by "Reco"
  // if "FillWrite" different from -1.
  // Ntuple is created automatically before filling first event.
  // If "FillWrite" = -1, write and close the file

  static Bool_t firstTime = kTRUE;
  static TTree *ntuple;
  static AliMUONHeaderRecNtuple *header = new AliMUONHeaderRecNtuple();
  static TClonesArray *recTracks = new TClonesArray("AliMUONTrackRecNtuple",5);

  Int_t trackIndex;
  AliMUONTrack *track;
  AliMUONTrackParam *trackParam;
  AliMUONTrackRecNtuple *recTrackNt;
  Double_t bendingSlope, nonBendingSlope, pYZ;

  if (FillWrite == -1) {
    printf(">>> Writing Ntuple of reconstructed tracks\n");
    // better to create the file before the Ntuple ????
    TFile *file = new TFile("MUONtrackReco.root","recreate");
    ntuple->Write();
    file->Write();
    file->Close();
  }

  if (firstTime) {
    firstTime = kFALSE;
    // first call: create tree for Ntuple...
    printf(">>> Creating Ntuple of reconstructed tracks\n");
    ntuple = new TTree("MUONtrackReco", "MUONtrackReco");
    ntuple->Branch("Header","AliMUONHeaderRecNtuple", &header);
    ntuple->Branch("Tracks", &recTracks);
  }

  // header

  header->fEvent = gAlice->GetHeader()->GetEvent();

  TClonesArray *recoTracksPtr = Reco->GetRecTracksPtr();
  recoTracksPtr->Compress(); // for simple loop without "Next" since no hole
  recTracks->Clear(); // to reset the TClonesArray of tracks to be put in the ntuple
  // Loop over reconstructed tracks
  for (trackIndex = 0; trackIndex < Reco->GetNRecTracks(); trackIndex++) {
    track = (AliMUONTrack*) ((*recoTracksPtr)[trackIndex]);
    recTrackNt = (AliMUONTrackRecNtuple*)
      new ((*recTracks)[trackIndex]) AliMUONTrackRecNtuple();
    // track parameters at Vertex
    trackParam = track->GetTrackParamAtVertex();
    recTrackNt->fCharge =
      Int_t(TMath::Sign(1., trackParam->GetInverseBendingMomentum()));
    bendingSlope = trackParam->GetBendingSlope();
    nonBendingSlope = trackParam->GetNonBendingSlope();
    pYZ = 1/TMath::Abs(trackParam->GetInverseBendingMomentum());
    recTrackNt->fPzRec = pYZ / TMath::Sqrt(1.0 + bendingSlope * bendingSlope);
    recTrackNt->fPxRec = recTrackNt->fPzRec * nonBendingSlope;
    recTrackNt->fPyRec = recTrackNt->fPzRec * bendingSlope;
    recTrackNt->fZRec = trackParam->GetZ();
    // track parameters at first hit
    trackParam = ((AliMUONTrackHit*)
		  (track->GetTrackHitsPtr()->First()))->GetTrackParam();
    recTrackNt->fZRec1 = trackParam->GetZ();
    // chi2
    recTrackNt->fChi2 = track->GetFitFMin();
    // number of hits
    recTrackNt->fNHits = track->GetNTrackHits();
    // track parameters at vertex of best compatible generated track:
    // in fact muon with the right charge
 //     for (int iPart = 0; iPart < gAlice->Particles()->GetEntriesFast(); iPart++) {
//        TParticle *particle = (TParticle*) gAlice->Particles()->UncheckedAt(iPart);
//        if ((particle->GetPdgCode() * recTrackNt->fCharge) == -13) {
//  	recTrackNt->fPxGen = particle->Px();
//  	recTrackNt->fPyGen = particle->Py();
//  	recTrackNt->fPzGen = particle->Pz();
//        }  // commented by Gines
    //    }
  } // for (trackIndex = 0;...

  printf(">>> Filling Ntuple of reconstructed tracks\n");
  ntuple->Fill();

  return;
}

void MUONrecoNtuple (Int_t FirstEvent = 0, Int_t LastEvent = 0, Int_t RecGeantHits = 0, Text_t *FileName = "galice.root", Text_t *BkgGeantFileName = "")
{
  //
  cout << "MUON_recoNtuple" << endl;
  cout << "FirstEvent " << FirstEvent << endl;
  cout << "LastEvent " << LastEvent << endl;
  cout << "RecGeantHits " << RecGeantHits << endl;
  cout << "FileName ``" << FileName << "''" << endl;
  cout << "BkgGeantFileName ``" << BkgGeantFileName << "''" << endl;
//   // Dynamically link some shared libs
//   if (gClassTable->GetID("AliRun") < 0) {
//     gROOT->LoadMacro("loadlibs.C");
//     loadlibs();
//   }

  // Creating Run Loader and openning file containing Hits, Digits and RecPoints
  AliRunLoader * RunLoader = AliRunLoader::Open(FileName,"Event","UPDATE");
  if (RunLoader ==0x0) {
    printf(">>> Error : Error Opening %s file \n",FileName);
    return;
  }
  // Loading AliRun master
  RunLoader->LoadgAlice();
  gAlice = RunLoader->GetAliRun();

  // Loading MUON subsystem
  AliMUON * MUON = (AliMUON *) gAlice->GetDetector("MUON");
  AliLoader * MUONLoader = RunLoader->GetLoader("MUONLoader");
  MUONLoader->LoadHits("READ");
  MUONLoader->LoadRecPoints("READ");

  Int_t ievent, nevents;
  nevents = RunLoader->GetNumberOfEvents();

  // Initializations
  // AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
  AliMUONEventReconstructor *Reco = new AliMUONEventReconstructor();

  Reco->SetRecGeantHits(RecGeantHits);

  // The right place for changing AliMUONEventReconstructor parameters
  // with respect to the default ones
//   Reco->SetMaxSigma2Distance(100.0);
  Reco->SetPrintLevel(20);
//   Reco->SetPrintLevel(1);
//   Reco->SetBendingResolution(0.0);
//   Reco->SetNonBendingResolution(0.0);
  cout << "AliMUONEventReconstructor: actual parameters" << endl;
  Reco->Dump();
//   gObjectTable->Print();

  // Loop over events
  for (Int_t event = FirstEvent; event <= LastEvent; event++) {
    MUON->ResetRawClusters();
    cout << "Event: " << event << endl;
    RunLoader->GetEvent(event);
    // Addressing
    MUON->SetTreeAddress();

 //     Int_t nparticles = gAlice->GetEvent(event);
//      cout << "nparticles: " << nparticles << endl;
    // prepare background file and/or event if necessary
    if (RecGeantHits == 1) {
      if (event == FirstEvent) Reco->SetBkgGeantFile(BkgGeantFileName);
      if (Reco->GetBkgGeantFile())Reco->NextBkgGeantEvent();
    }
    Reco->EventReconstruct();
    // Dump current event
    Reco->EventDump();
    // Fill Ntuple
    AliMUONEventRecNtupleFill(Reco, 0);
//     gObjectTable->Print();

  } // Event loop
    // Write Ntuple
    AliMUONEventRecNtupleFill(Reco, -1);
}
<commit_msg>Reseting rawclusters at the end of the event loop<commit_after>// Macro MUONrecoNtuple.C (TO BE COMPILED)
// for testing the C++ reconstruction code
// and producing an Ntuple with reconstructed tracks
// in output file "MUONtrackReco.root".
// An example for using the Ntuple is in the macro MUONmassPlot.C

// Arguments:
//   FirstEvent (default 0)
//   LastEvent (default 0)
//   RecGeantHits (1 to reconstruct GEANT hits) (default 0)
//   FileName (for signal) (default "galice.root")
//   BkgGeantFileName (for background),
//      needed only if RecGeantHits = 1 and background to be added

// IMPORTANT NOTICE FOR USERS:
// under "root" or "root.exe", execute the following commands:
// 1. "gSystem->SetIncludePath("-I$ALICE_ROOT/MUON -I$ALICE_ROOT/STEER -I$ROOTSYS/include")" to get the right path at compilation time
// 2. ".x loadlibs.C" to load the shared libraries
// 3. ".x MUONrecoNtuple.C+()" with the right arguments, without forgetting the "+" which implies the compilation of the macro before its execution

#include <iostream.h>

#include <TClassTable.h>
#include <TClonesArray.h>
#include <TFile.h>
#include <TParticle.h>
#include <TROOT.h>
#include <TTree.h>

#include "AliHeader.h"
#include "AliRun.h"

#include "AliMUON.h"
#include "AliMUONEventReconstructor.h"
#include "AliMUONTrack.h"
#include "AliMUONTrackHit.h"
#include "AliMUONTrackParam.h"

// Classes for Ntuple ////////////////////////////////////////////////////

class AliMUONTrackRecNtuple : public TObject {
 public:
  // for direct access to members
  Int_t fCharge; // charge of reconstructed track (+/- 1)
  Float_t fPxRec; // Px of reconstructed track at vertex (GeV/c)
  Float_t fPyRec; // Py of reconstructed track at vertex (GeV/c)
  Float_t fPzRec; // Pz of reconstructed track at vertex (GeV/c)
  Float_t fZRec; // Z of reconstructed track at vertex (cm)
  Float_t fZRec1; // Z of reconstructed track at first hit (cm)
  Int_t fNHits; // number of hits
  Float_t fChi2; // chi2 of fit
  Float_t fPxGen; // Px of best compatible generated track at vertex (GeV/c)
  Float_t fPyGen; // Py of best compatible generated track at vertex (GeV/c)
  Float_t fPzGen; // Pz of best compatible generated track at vertex (GeV/c)
  AliMUONTrackRecNtuple(){;} // Constructor
  virtual ~AliMUONTrackRecNtuple(){;} // Destructor
 protected:
 private:
  ClassDef(AliMUONTrackRecNtuple, 1) // AliMUONTrackRecNtuple
    };

class AliMUONHeaderRecNtuple : public TObject {
 public:
  // for direct access to members
  Int_t fEvent; // event number
  AliMUONHeaderRecNtuple(){;} // Constructor
  virtual ~AliMUONHeaderRecNtuple(){;} // Destructor
 protected:
 private:
  ClassDef(AliMUONHeaderRecNtuple, 1) // AliMUONHeaderRecNtuple
    };

ClassImp(AliMUONTrackRecNtuple) // Class implementation in ROOT context
ClassImp(AliMUONHeaderRecNtuple) // Class implementation in ROOT context

  //__________________________________________________________________________
void AliMUONEventRecNtupleFill(AliMUONEventReconstructor *Reco, Int_t FillWrite = 0)
{
  // Fill Ntuple for reconstructed event pointed to by "Reco"
  // if "FillWrite" different from -1.
  // Ntuple is created automatically before filling first event.
  // If "FillWrite" = -1, write and close the file

  static Bool_t firstTime = kTRUE;
  static TTree *ntuple;
  static AliMUONHeaderRecNtuple *header = new AliMUONHeaderRecNtuple();
  static TClonesArray *recTracks = new TClonesArray("AliMUONTrackRecNtuple",5);

  Int_t trackIndex;
  AliMUONTrack *track;
  AliMUONTrackParam *trackParam;
  AliMUONTrackRecNtuple *recTrackNt;
  Double_t bendingSlope, nonBendingSlope, pYZ;

  if (FillWrite == -1) {
    printf(">>> Writing Ntuple of reconstructed tracks\n");
    // better to create the file before the Ntuple ????
    TFile *file = new TFile("MUONtrackReco.root","recreate");
    ntuple->Write();
    file->Write();
    file->Close();
  }

  if (firstTime) {
    firstTime = kFALSE;
    // first call: create tree for Ntuple...
    printf(">>> Creating Ntuple of reconstructed tracks\n");
    ntuple = new TTree("MUONtrackReco", "MUONtrackReco");
    ntuple->Branch("Header","AliMUONHeaderRecNtuple", &header);
    ntuple->Branch("Tracks", &recTracks);
  }

  // header

  header->fEvent = gAlice->GetHeader()->GetEvent();

  TClonesArray *recoTracksPtr = Reco->GetRecTracksPtr();
  recoTracksPtr->Compress(); // for simple loop without "Next" since no hole
  recTracks->Clear(); // to reset the TClonesArray of tracks to be put in the ntuple
  // Loop over reconstructed tracks
  for (trackIndex = 0; trackIndex < Reco->GetNRecTracks(); trackIndex++) {
    track = (AliMUONTrack*) ((*recoTracksPtr)[trackIndex]);
    recTrackNt = (AliMUONTrackRecNtuple*)
      new ((*recTracks)[trackIndex]) AliMUONTrackRecNtuple();
    // track parameters at Vertex
    trackParam = track->GetTrackParamAtVertex();
    recTrackNt->fCharge =
      Int_t(TMath::Sign(1., trackParam->GetInverseBendingMomentum()));
    bendingSlope = trackParam->GetBendingSlope();
    nonBendingSlope = trackParam->GetNonBendingSlope();
    pYZ = 1/TMath::Abs(trackParam->GetInverseBendingMomentum());
    recTrackNt->fPzRec = pYZ / TMath::Sqrt(1.0 + bendingSlope * bendingSlope);
    recTrackNt->fPxRec = recTrackNt->fPzRec * nonBendingSlope;
    recTrackNt->fPyRec = recTrackNt->fPzRec * bendingSlope;
    recTrackNt->fZRec = trackParam->GetZ();
    // track parameters at first hit
    trackParam = ((AliMUONTrackHit*)
		  (track->GetTrackHitsPtr()->First()))->GetTrackParam();
    recTrackNt->fZRec1 = trackParam->GetZ();
    // chi2
    recTrackNt->fChi2 = track->GetFitFMin();
    // number of hits
    recTrackNt->fNHits = track->GetNTrackHits();
    // track parameters at vertex of best compatible generated track:
    // in fact muon with the right charge
 //     for (int iPart = 0; iPart < gAlice->Particles()->GetEntriesFast(); iPart++) {
//        TParticle *particle = (TParticle*) gAlice->Particles()->UncheckedAt(iPart);
//        if ((particle->GetPdgCode() * recTrackNt->fCharge) == -13) {
//  	recTrackNt->fPxGen = particle->Px();
//  	recTrackNt->fPyGen = particle->Py();
//  	recTrackNt->fPzGen = particle->Pz();
//        }  // commented by Gines
    //    }
  } // for (trackIndex = 0;...

  printf(">>> Filling Ntuple of reconstructed tracks\n");
  ntuple->Fill();

  return;
}

void MUONrecoNtuple (Int_t FirstEvent = 0, Int_t LastEvent = 0, Int_t RecGeantHits = 0, Text_t *FileName = "galice.root", Text_t *BkgGeantFileName = "")
{
  //
  cout << "MUON_recoNtuple" << endl;
  cout << "FirstEvent " << FirstEvent << endl;
  cout << "LastEvent " << LastEvent << endl;
  cout << "RecGeantHits " << RecGeantHits << endl;
  cout << "FileName ``" << FileName << "''" << endl;
  cout << "BkgGeantFileName ``" << BkgGeantFileName << "''" << endl;
//   // Dynamically link some shared libs
//   if (gClassTable->GetID("AliRun") < 0) {
//     gROOT->LoadMacro("loadlibs.C");
//     loadlibs();
//   }

  // Creating Run Loader and openning file containing Hits, Digits and RecPoints
  AliRunLoader * RunLoader = AliRunLoader::Open(FileName,"Event","UPDATE");
  if (RunLoader ==0x0) {
    printf(">>> Error : Error Opening %s file \n",FileName);
    return;
  }
  // Loading AliRun master
  RunLoader->LoadgAlice();
  gAlice = RunLoader->GetAliRun();

  // Loading MUON subsystem
  AliMUON * MUON = (AliMUON *) gAlice->GetDetector("MUON");
  AliLoader * MUONLoader = RunLoader->GetLoader("MUONLoader");
  MUONLoader->LoadHits("READ");
  MUONLoader->LoadRecPoints("READ");

  Int_t ievent, nevents;
  nevents = RunLoader->GetNumberOfEvents();

  // Initializations
  // AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
  MUON->SetTreeAddress();
  AliMUONEventReconstructor *Reco = new AliMUONEventReconstructor();

  Reco->SetRecGeantHits(RecGeantHits);

  // The right place for changing AliMUONEventReconstructor parameters
  // with respect to the default ones
//   Reco->SetMaxSigma2Distance(100.0);
  Reco->SetPrintLevel(20);
//   Reco->SetPrintLevel(1);
//   Reco->SetBendingResolution(0.0);
//   Reco->SetNonBendingResolution(0.0);
  cout << "AliMUONEventReconstructor: actual parameters" << endl;
  Reco->Dump();
//   gObjectTable->Print();
  // Loop over events
  for (Int_t event = FirstEvent; event < LastEvent; event++) {
    cout << "Event: " << event << endl;
    RunLoader->GetEvent(event);
    //     Int_t nparticles = gAlice->GetEvent(event);
    //      cout << "nparticles: " << nparticles << endl;
    // prepare background file and/or event if necessary
    if (RecGeantHits == 1) {
      if (event == FirstEvent) Reco->SetBkgGeantFile(BkgGeantFileName);
      if (Reco->GetBkgGeantFile())Reco->NextBkgGeantEvent();
    }
    Reco->EventReconstruct();
    // Dump current event
    Reco->EventDump();
    // Fill Ntuple
    AliMUONEventRecNtupleFill(Reco, 0);
//     gObjectTable->Print();
    MUON->ResetRawClusters();
  } // Event loop
    // Write Ntuple
    AliMUONEventRecNtupleFill(Reco, -1);
}
<|endoftext|>


<commit_before>#define WINVER 0x0501
#define BUFSIZE 4096
#pragma comment(lib, "Shlwapi.lib")

#include <string>
#include <iostream>
#include <fstream>
#include "Shlwapi.h"
#include "encoder_format.h"
using namespace std;

extern EncoderFormat encoderFormat;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);

class FuzzingDebugger
{
public:
  bool load(wstring fileName)
  {
    ifstream
      file;

    streampos
      size;

    file = ifstream(fileName, ios::in | ios::binary | ios::ate);
    if (!file.is_open())
      return(false);

    size = file.tellg();
    _size = size;
    _data = new char[_size];
    file.seekg(0, ios::beg);
    file.read(_data, size);
    file.close();

    encoderFormat.set(wstring(PathFindExtension(fileName.c_str())));

    return(true);
  }

  void start()
  {
    const uint8_t
      *data;

    data = reinterpret_cast<const uint8_t *>(_data);
    LLVMFuzzerTestOneInput(data, _size);
  }

private:
  char * _data;
  size_t _size;
};

int wmain(int argc, wchar_t *argv[])
{
  FuzzingDebugger
    debugger;

  wstring
    fileName;

  if (argc == 1)
  {
    wchar_t
      fullPath[BUFSIZE],
      **lppPart;

    lppPart = NULL;
    GetFullPathName(argv[0], BUFSIZE, fullPath, lppPart);
    PathRemoveExtension(fullPath);
    fileName = wstring(fullPath) + L".input";
  }
  else
    fileName = wstring(argv[1]);

  if (!debugger.load(fileName))
  {
    wcerr << L"Unable to load " << fileName;
    cin.get();
  }
  else
    debugger.start();
}<commit_msg>Fixed build for VS2013.<commit_after>#define WINVER 0x0501
#define BUFSIZE 4096
#pragma comment(lib, "Shlwapi.lib")

#include <string>
#include <iostream>
#include <fstream>
#include <Shlwapi.h>
#include <stdint.h>
#include "encoder_format.h"
using namespace std;

extern EncoderFormat encoderFormat;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);

class FuzzingDebugger
{
public:
  bool load(wstring fileName)
  {
    ifstream
      file;

    streampos
      size;

    file = ifstream(fileName, ios::in | ios::binary | ios::ate);
    if (!file.is_open())
      return(false);

    size = file.tellg();
    _size = size;
    _data = new char[_size];
    file.seekg(0, ios::beg);
    file.read(_data, size);
    file.close();

    encoderFormat.set(wstring(PathFindExtension(fileName.c_str())));

    return(true);
  }

  void start()
  {
    const uint8_t
      *data;

    data = reinterpret_cast<const uint8_t *>(_data);
    LLVMFuzzerTestOneInput(data, _size);
  }

private:
  char * _data;
  size_t _size;
};

int wmain(int argc, wchar_t *argv[])
{
  FuzzingDebugger
    debugger;

  wstring
    fileName;

  if (argc == 1)
  {
    wchar_t
      fullPath[BUFSIZE],
      **lppPart;

    lppPart = NULL;
    GetFullPathName(argv[0], BUFSIZE, fullPath, lppPart);
    PathRemoveExtension(fullPath);
    fileName = wstring(fullPath) + L".input";
  }
  else
    fileName = wstring(argv[1]);

  if (!debugger.load(fileName))
  {
    wcerr << L"Unable to load " << fileName;
    cin.get();
  }
  else
    debugger.start();
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   This file is part of Kate search plugin                               *
 *   Copyright 2014 Kåre Särs <kare.sars@iki.fi>                           *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This 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 Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "UrlInserter.h"
#include <klocalizedstring.h>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QFileInfo>
#include <QIcon>
#include <QDebug>

UrlInserter::UrlInserter(const QUrl &startUrl, QWidget* parent): QWidget(parent), m_startUrl(startUrl), m_replace(false)
{
    m_lineEdit = new QLineEdit();
    m_toolButton = new QToolButton();
    m_toolButton->setIcon(QIcon::fromTheme(QStringLiteral("archive-insert-directory")));
    m_toolButton->setToolTip(i18n("Inset path"));

    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setContentsMargins(0,0,0,0);
    layout->setSpacing(0);
    layout->addWidget(m_lineEdit);
    layout->addWidget(m_toolButton);
    setFocusProxy(m_lineEdit);
    connect(m_toolButton, SIGNAL(clicked(bool)), this, SLOT(insertFolder()));
}

void UrlInserter::insertFolder()
{
    QUrl startUrl;
    if (QFileInfo(m_lineEdit->text()).exists()) {
        startUrl.setPath(m_lineEdit->text());
    }
    else {
        startUrl = m_startUrl;
    }
    QString folder = QFileDialog::getExistingDirectory(this, i18n("Select directory to insert"),
                                                       startUrl.path());
    if (!folder.isEmpty()) {
        if (!m_replace) {
            m_lineEdit->insert(folder);
        }
        else {
            m_lineEdit->setText(folder);
        }
    }
}

void UrlInserter::setReplace(bool replace)
{
    m_replace = replace;
}
<commit_msg>Fix typo<commit_after>/***************************************************************************
 *   This file is part of Kate search plugin                               *
 *   Copyright 2014 Kåre Särs <kare.sars@iki.fi>                           *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This 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 Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "UrlInserter.h"
#include <klocalizedstring.h>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QFileInfo>
#include <QIcon>
#include <QDebug>

UrlInserter::UrlInserter(const QUrl &startUrl, QWidget* parent): QWidget(parent), m_startUrl(startUrl), m_replace(false)
{
    m_lineEdit = new QLineEdit();
    m_toolButton = new QToolButton();
    m_toolButton->setIcon(QIcon::fromTheme(QStringLiteral("archive-insert-directory")));
    m_toolButton->setToolTip(i18n("Insert path"));

    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setContentsMargins(0,0,0,0);
    layout->setSpacing(0);
    layout->addWidget(m_lineEdit);
    layout->addWidget(m_toolButton);
    setFocusProxy(m_lineEdit);
    connect(m_toolButton, SIGNAL(clicked(bool)), this, SLOT(insertFolder()));
}

void UrlInserter::insertFolder()
{
    QUrl startUrl;
    if (QFileInfo(m_lineEdit->text()).exists()) {
        startUrl.setPath(m_lineEdit->text());
    }
    else {
        startUrl = m_startUrl;
    }
    QString folder = QFileDialog::getExistingDirectory(this, i18n("Select directory to insert"),
                                                       startUrl.path());
    if (!folder.isEmpty()) {
        if (!m_replace) {
            m_lineEdit->insert(folder);
        }
        else {
            m_lineEdit->setText(folder);
        }
    }
}

void UrlInserter::setReplace(bool replace)
{
    m_replace = replace;
}
<|endoftext|>