<commit_before>#include <benchmark/benchmark.h>
#include <ryml.hpp>
#include <ryml_std.hpp>
#include <c4/fs/fs.hpp>
#include <vector>
#include <iostream>
#include <yaml-cpp/yaml.h>

namespace bm = benchmark;

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

struct BmCase
{
    c4::csubstr filename;
    std::vector<char> src;
    std::vector<char> in_place;
    ryml::Tree ryml_tree;
    bool is_json;

    void run(int argc, char **argv)
    {
        bm::Initialize(&argc, argv);
        C4_CHECK(argc == 2);
        load(argv[1]);
        bm::RunSpecifiedBenchmarks();
    }

    void load(const char* file)
    {
        filename = c4::to_csubstr(file);
        is_json = filename.ends_with(".json");
        c4::fs::file_get_contents(file, &src);
        in_place = src;
    }
};

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

BmCase c; // this is used by the benchmarks

int main(int argc, char** argv)
{
    c.run(argc, argv);
}

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

void yamlcpp(bm::State& st)
{
    std::string src(c.src.begin(), c.src.end());
    for(auto _ : st)
    {
        YAML::Node node = YAML::Load(src);
    }
    st.SetBytesProcessed(st.iterations() * src.size());
}

void ryml_rw(bm::State& st)
{
    size_t sz;
    for(auto _ : st)
    {
        ryml::Tree tree = ryml::parse(c.filename, to_substr(c.in_place));
        sz = tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.in_place.size());
}

void ryml_ro(bm::State& st)
{
    size_t sz;
    for(auto _ : st)
    {
        ryml::Tree tree = ryml::parse(c.filename, to_csubstr(c.src));
        sz = tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.in_place.size());
}

void ryml_rw_reuse(bm::State& st)
{
    size_t sz;
    ryml::Parser p;
    for(auto _ : st)
    {
        c.ryml_tree.clear();
        c.ryml_tree.clear_arena();
        p.parse(c.filename, to_substr(c.in_place), &c.ryml_tree);
        sz = c.ryml_tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.in_place.size());
}

void ryml_ro_reuse(bm::State& st)
{
    size_t sz;
    ryml::Parser p;
    for(auto _ : st)
    {
        c.ryml_tree.clear();
        c.ryml_tree.clear_arena();
        p.parse(c.filename, to_csubstr(c.src), &c.ryml_tree);
        sz = c.ryml_tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.in_place.size());
}

BENCHMARK(yamlcpp);
BENCHMARK(ryml_ro);
BENCHMARK(ryml_rw);
BENCHMARK(ryml_ro_reuse);
BENCHMARK(ryml_rw_reuse);
<commit_msg>some fixes to the parse benchmark<commit_after>#include <benchmark/benchmark.h>
#include <ryml.hpp>
#include <ryml_std.hpp>
#include <c4/fs/fs.hpp>
#include <vector>
#include <iostream>
#include <yaml-cpp/yaml.h>

namespace bm = benchmark;

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

struct BmCase
{
    c4::csubstr filename;
    std::vector<char> src;
    std::vector<char> in_place;
    ryml::Parser ryml_parser;
    ryml::Tree   ryml_tree;
    bool is_json;

    void run(int argc, char **argv)
    {
        bm::Initialize(&argc, argv);
        C4_CHECK(argc == 2);
        load(argv[1]);
        bm::RunSpecifiedBenchmarks();
    }

    void load(const char* file)
    {
        filename = c4::to_csubstr(file);
        is_json = filename.ends_with(".json");
        c4::fs::file_get_contents(file, &src);
        in_place = src;
    }
};

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

BmCase c; // this is used by the benchmarks

int main(int argc, char** argv)
{
    c.run(argc, argv);
}

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

void yamlcpp(bm::State& st)
{
    std::string src(c.src.begin(), c.src.end());
    for(auto _ : st)
    {
        YAML::Node node = YAML::Load(src);
    }
    st.SetBytesProcessed(st.iterations() * src.size());
}

void ryml_rw(bm::State& st)
{
    size_t sz;
    for(auto _ : st)
    {
        ryml::Tree tree = ryml::parse(c.filename, to_substr(c.in_place));
        sz = tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.src.size());
}

void ryml_ro(bm::State& st)
{
    size_t sz;
    for(auto _ : st)
    {
        ryml::Tree tree = ryml::parse(c.filename, to_csubstr(c.src));
        sz = tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.src.size());
}

void ryml_rw_reuse(bm::State& st)
{
    size_t sz;
    for(auto _ : st)
    {
        c.ryml_tree.clear();
        c.ryml_tree.clear_arena();
        c.ryml_parser.parse(c.filename, to_substr(c.in_place), &c.ryml_tree);
        sz = c.ryml_tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.src.size());
}

void ryml_ro_reuse(bm::State& st)
{
    size_t sz;
    for(auto _ : st)
    {
        c.ryml_tree.clear();
        c.ryml_tree.clear_arena();
        c.ryml_parser.parse(c.filename, to_csubstr(c.src), &c.ryml_tree);
        sz = c.ryml_tree.size();
    }
    st.SetItemsProcessed(st.iterations() * sz);
    st.SetBytesProcessed(st.iterations() * c.src.size());
}

BENCHMARK(yamlcpp);
BENCHMARK(ryml_ro);
BENCHMARK(ryml_rw);
BENCHMARK(ryml_ro_reuse);
BENCHMARK(ryml_rw_reuse);
<|endoftext|>


<commit_before>// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2005 2006 2007 2010 2012 2013 2014 2015 2017 2018 HörTech gGmbH
//
// openMHA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// openMHA 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 Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA.  If not, see <http://www.gnu.org/licenses/>.

/*
 * A simple example \mha plugin written in C++
 *
 * This plugin scales one channel of the input signal, working in the
 * spectral domain. The scale factor and the scaled channel number is made
 * accessible to the configuration structure.
 *
 * This plugin implementation uses the C++ macros for standard \mha
 * plugins and a template class for algorithms with a thread safe
 * configuration space. The second item is important if the
 * configuration will be changed at runtime.
 */

#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
/*
 * On some MS Windows compilers, the function "snprintf" is defined as
 * "_snprintf":
 */
#define snprintf _snprintf
#else
/*
 * On MS Windows functions have to be exported with
 * __declspec(dllexport) so we define a dummy for other OS (like
 * Linux)
 */
#define __declspec(p)
#endif

// MicroSoft Visual C++ has problems with it's own min and max macros...
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif

#include "mha_plugin.hh"
#include "mha_events.h"

/*
 * The definition of the signal processing run time configuration. The
 * constructor is used to initialize and validate the run time
 * configuration, based on the general (parser) configuration. If the
 * constructor failes, the parser command which caused the failure
 * will be rejected. The signal processing thread will not be affected.
 *
 * The constructor and destructor are called from the
 * control/configuration thread. All other functions and variables
 * should only be accessed from the signal processing thread. Read
 * only access from the configuration thread is possible if the read
 * operation is atomic.
 */
class example5_t {
public:
    example5_t(unsigned int,unsigned int,mha_real_t);
    mha_spec_t* process(mha_spec_t*);
private:
    unsigned int channel;
    mha_real_t scale;
};

/*
 * The definition of a simple signal processing class, containing a
 * constructor, a processing method and two variables.
 *
 * The base class MHAParser::parser_t provides the configuration
 * interface, the base class MHAPlugin::plugin_t provides standard
 * methods for \mha plugins (i.e. error handling) and functionality for
 * thread safe runtime configuration.
 *
 * Implementation see below.
 */
class plugin_interface_t : public MHAPlugin::plugin_t<example5_t> {
public:
    plugin_interface_t(const algo_comm_t&,const std::string&,const std::string&);
    mha_spec_t* process(mha_spec_t*);
    void prepare(mhaconfig_t&);
private:
    void update_cfg();
    /* integer variable of MHA-parser: */
    MHAParser::int_t scale_ch;
    /* float variable of MHA-parser: */
    MHAParser::float_t factor;
    /* patch bay for connecting configuration parser
       events with local member functions: */
    MHAEvents::patchbay_t<plugin_interface_t> patchbay;
};

/*
 * Constructor of the runtime configuration class.
 *
 * This constructor is called in the configuration thread. This
 * allowes slow initialization processes (memory allocation,
 * configuration processing) even at run time.
 */
example5_t::example5_t(unsigned int ichannel,
                       unsigned int numchannels,
                       mha_real_t iscale)
    : channel(ichannel),scale(iscale)
{
    if( channel >= numchannels )
        throw MHA_Error(__FILE__,__LINE__,
                        "Invalid channel number %d (only %d channels configured).",
                        channel,numchannels);
}

/*
 * Signal processing method. One channel of the input signal is scaled
 * by a factor. The factor and channel number can be changed at any
 * time using the configuration parser of the framework.
 */
mha_spec_t* example5_t::process(mha_spec_t* spec)
{
    /* Scale channel number "scale_ch" by "factor": */
    for(unsigned int fr = 0; fr < spec->num_frames; fr++){
        spec->buf[fr + channel * spec->num_frames].re *= scale;
        spec->buf[fr + channel * spec->num_frames].im *= scale;
    }
    return spec;
}

/*
 * Constructor of the simple signal processing class.
 */
plugin_interface_t::plugin_interface_t(
    const algo_comm_t& iac,
    const std::string&,const std::string&)
    : MHAPlugin::plugin_t<example5_t>("example plugin configuration structure",iac),
      /* initialzing variable 'scale_ch' with MHAParser::int_t(char* name, .... ) */
      scale_ch("channel number to be scaled","0","[0,["),
      /* initialzing variable 'factor' with MHAParser::float_t(char* name, .... ) */
      factor("scale factor","1.0","[0,2]")
{
    /* Register variables to the configuration parser: */
    insert_item("channel",&scale_ch);
    insert_item("factor",&factor);
    /*
     * On write access to the parser variables a notify callback of
     * this class will be called. That funtion will update the runtime
     * configuration.
     */
    patchbay.connect(&scale_ch.writeaccess,this,&plugin_interface_t::update_cfg);
    patchbay.connect(&factor.writeaccess,this,&plugin_interface_t::update_cfg);
}

/*
 * Signal processing method of the interface class. The new
 * configuration is polled and the processing passed to the new
 * processing.
 */
mha_spec_t* plugin_interface_t::process(mha_spec_t* spec)
{
    poll_config();
    return cfg->process(spec);
}

/*
 * Handle the prepare request of the framework. After this callback
 * was called, a valid run time configuration has to be
 * available. Domain and channel numbers of input and output are
 * passed to the algorithm and can be modified by the algorithm. If
 * not modified by the algorithm, than the output and input parameters
 * are equal. The default domain depends on the output domain of
 * preceeding algorithms.
 */
void plugin_interface_t::prepare(mhaconfig_t& tfcfg)
{
    if( tfcfg.domain != MHA_SPECTRUM )
        throw MHA_Error(__FILE__,__LINE__,
                        "Example5: Only spectral processing is supported.");
    /* remember the transform configuration (i.e. channel numbers): */
    tftype = tfcfg;
    /* make sure that a valid runtime configuration exists: */
    update_cfg();
}

/*
 * This function adds a valid runtime configuration. In this case, the
 * channel number has to be configured for a valid configuration (see
 * prepare() callback).
 */
void plugin_interface_t::update_cfg()
{
    if( tftype.channels )
        push_config(new example5_t(scale_ch.data,tftype.channels,factor.data));
}

/*
 * This macro wraps the required ANSI-C interface around the algorithm
 * class. The first argument is the algorithm class name, the other
 * arguments define the input and output domain of the algorithm.
 */
MHAPLUGIN_CALLBACKS(example5,plugin_interface_t,spec,spec)
MHAPLUGIN_DOCUMENTATION\
(example5,
 "example level-modification audio-channels",
 "")

// Local Variables:
// compile-command: "make"
// c-basic-offset: 4
// indent-tabs-mode: nil
// coding: utf-8-unix
// End:
<commit_msg>example5: Add docstring. Closes T102<commit_after>// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2005 2006 2007 2010 2012 2013 2014 2015 2017 2018 HörTech gGmbH
//
// openMHA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// openMHA 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 Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA.  If not, see <http://www.gnu.org/licenses/>.

/*
 * A simple example \mha plugin written in C++
 *
 * This plugin scales one channel of the input signal, working in the
 * spectral domain. The scale factor and the scaled channel number is made
 * accessible to the configuration structure.
 *
 * This plugin implementation uses the C++ macros for standard \mha
 * plugins and a template class for algorithms with a thread safe
 * configuration space. The second item is important if the
 * configuration will be changed at runtime.
 */

#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
/*
 * On some MS Windows compilers, the function "snprintf" is defined as
 * "_snprintf":
 */
#define snprintf _snprintf
#else
/*
 * On MS Windows functions have to be exported with
 * __declspec(dllexport) so we define a dummy for other OS (like
 * Linux)
 */
#define __declspec(p)
#endif

// MicroSoft Visual C++ has problems with it's own min and max macros...
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif

#include "mha_plugin.hh"
#include "mha_events.h"

/*
 * The definition of the signal processing run time configuration. The
 * constructor is used to initialize and validate the run time
 * configuration, based on the general (parser) configuration. If the
 * constructor failes, the parser command which caused the failure
 * will be rejected. The signal processing thread will not be affected.
 *
 * The constructor and destructor are called from the
 * control/configuration thread. All other functions and variables
 * should only be accessed from the signal processing thread. Read
 * only access from the configuration thread is possible if the read
 * operation is atomic.
 */
class example5_t {
public:
    example5_t(unsigned int,unsigned int,mha_real_t);
    mha_spec_t* process(mha_spec_t*);
private:
    unsigned int channel;
    mha_real_t scale;
};

/*
 * The definition of a simple signal processing class, containing a
 * constructor, a processing method and two variables.
 *
 * The base class MHAParser::parser_t provides the configuration
 * interface, the base class MHAPlugin::plugin_t provides standard
 * methods for \mha plugins (i.e. error handling) and functionality for
 * thread safe runtime configuration.
 *
 * Implementation see below.
 */
class plugin_interface_t : public MHAPlugin::plugin_t<example5_t> {
public:
    plugin_interface_t(const algo_comm_t&,const std::string&,const std::string&);
    mha_spec_t* process(mha_spec_t*);
    void prepare(mhaconfig_t&);
private:
    void update_cfg();
    /* integer variable of MHA-parser: */
    MHAParser::int_t scale_ch;
    /* float variable of MHA-parser: */
    MHAParser::float_t factor;
    /* patch bay for connecting configuration parser
       events with local member functions: */
    MHAEvents::patchbay_t<plugin_interface_t> patchbay;
};

/*
 * Constructor of the runtime configuration class.
 *
 * This constructor is called in the configuration thread. This
 * allowes slow initialization processes (memory allocation,
 * configuration processing) even at run time.
 */
example5_t::example5_t(unsigned int ichannel,
                       unsigned int numchannels,
                       mha_real_t iscale)
    : channel(ichannel),scale(iscale)
{
    if( channel >= numchannels )
        throw MHA_Error(__FILE__,__LINE__,
                        "Invalid channel number %d (only %d channels configured).",
                        channel,numchannels);
}

/*
 * Signal processing method. One channel of the input signal is scaled
 * by a factor. The factor and channel number can be changed at any
 * time using the configuration parser of the framework.
 */
mha_spec_t* example5_t::process(mha_spec_t* spec)
{
    /* Scale channel number "scale_ch" by "factor": */
    for(unsigned int fr = 0; fr < spec->num_frames; fr++){
        spec->buf[fr + channel * spec->num_frames].re *= scale;
        spec->buf[fr + channel * spec->num_frames].im *= scale;
    }
    return spec;
}

/*
 * Constructor of the simple signal processing class.
 */
plugin_interface_t::plugin_interface_t(
    const algo_comm_t& iac,
    const std::string&,const std::string&)
    : MHAPlugin::plugin_t<example5_t>("example plugin scaling a spectral signal",iac),
      /* initialzing variable 'scale_ch' with MHAParser::int_t(char* name, .... ) */
      scale_ch("channel number to be scaled","0","[0,["),
      /* initialzing variable 'factor' with MHAParser::float_t(char* name, .... ) */
      factor("scale factor","1.0","[0,2]")
{
    /* Register variables to the configuration parser: */
    insert_item("channel",&scale_ch);
    insert_item("factor",&factor);
    /*
     * On write access to the parser variables a notify callback of
     * this class will be called. That funtion will update the runtime
     * configuration.
     */
    patchbay.connect(&scale_ch.writeaccess,this,&plugin_interface_t::update_cfg);
    patchbay.connect(&factor.writeaccess,this,&plugin_interface_t::update_cfg);
}

/*
 * Signal processing method of the interface class. The new
 * configuration is polled and the processing passed to the new
 * processing.
 */
mha_spec_t* plugin_interface_t::process(mha_spec_t* spec)
{
    poll_config();
    return cfg->process(spec);
}

/*
 * Handle the prepare request of the framework. After this callback
 * was called, a valid run time configuration has to be
 * available. Domain and channel numbers of input and output are
 * passed to the algorithm and can be modified by the algorithm. If
 * not modified by the algorithm, than the output and input parameters
 * are equal. The default domain depends on the output domain of
 * preceeding algorithms.
 */
void plugin_interface_t::prepare(mhaconfig_t& tfcfg)
{
    if( tfcfg.domain != MHA_SPECTRUM )
        throw MHA_Error(__FILE__,__LINE__,
                        "Example5: Only spectral processing is supported.");
    /* remember the transform configuration (i.e. channel numbers): */
    tftype = tfcfg;
    /* make sure that a valid runtime configuration exists: */
    update_cfg();
}

/*
 * This function adds a valid runtime configuration. In this case, the
 * channel number has to be configured for a valid configuration (see
 * prepare() callback).
 */
void plugin_interface_t::update_cfg()
{
    if( tftype.channels )
        push_config(new example5_t(scale_ch.data,tftype.channels,factor.data));
}

/*
 * This macro wraps the required ANSI-C interface around the algorithm
 * class. The first argument is the algorithm class name, the other
 * arguments define the input and output domain of the algorithm.
 */
MHAPLUGIN_CALLBACKS(example5,plugin_interface_t,spec,spec)
MHAPLUGIN_DOCUMENTATION\
(example5,
 "example level-modification audio-channels",
"This plugin scales one channel of the input signal, working in the spectral domain.\n"
"The scale factor and the scaled channel number is made accessible to the configuration structure."
)

// Local Variables:
// compile-command: "make"
// c-basic-offset: 4
// indent-tabs-mode: nil
// coding: utf-8-unix
// End:
<|endoftext|>


<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "Application.h"
#include <cmath>

using namespace std;
using namespace ouzel;

Application::~Application()
{
    sharedEngine->getEventDispatcher()->removeEventHandler(eventHandler);
}

void Application::begin()
{
#if defined(OUZEL_PLATFORM_WINDOWS) || defined(OUZEL_PLATFORM_LINUX)
    sharedEngine->getFileSystem()->addResourcePath("Resources");
#endif

    sharedEngine->getLocalization()->addLanguage("latvian", "lv.mo");
    sharedEngine->getLocalization()->setLanguage("latvian");

    eventHandler = make_shared<EventHandler>();

    eventHandler->keyboardHandler = bind(&Application::handleKeyboard, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->mouseHandler = bind(&Application::handleMouse, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->touchHandler = bind(&Application::handleTouch, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->gamepadHandler = bind(&Application::handleGamepad, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->uiHandler = bind(&Application::handleUI, this, placeholders::_1, placeholders::_2, placeholders::_3);

    sharedEngine->getEventDispatcher()->addEventHandler(eventHandler);

    sharedEngine->getRenderer()->setClearColor(graphics::Color(64, 0, 0));
    sharedEngine->getWindow()->setTitle("Sample");

    scene::ScenePtr scene = make_shared<scene::Scene>();
    sharedEngine->getSceneManager()->setScene(scene);

    rtLayer = make_shared<scene::Layer>();
    scene->addLayer(rtLayer);
    renderTarget = sharedEngine->getRenderer()->createRenderTarget(Size2(256.0f, 256.0f), false);
    renderTarget->setClearColor(graphics::Color(0, 64, 0));
    rtLayer->setCamera(make_shared<scene::Camera>());
    rtLayer->setRenderTarget(renderTarget);

    layer = make_shared<scene::Layer>();
    scene->addLayer(layer);
    layer->setCamera(make_shared<scene::Camera>());

    uiLayer = make_shared<scene::Layer>();
    scene->addLayer(uiLayer);
    uiLayer->setCamera(make_shared<scene::Camera>());

    scene::DebugDrawablePtr debugDrawable = make_shared<scene::DebugDrawable>();
    debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(0, 128, 128, 255), true);
    debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(255, 255, 255, 255), false);
    debugDrawable->line(Vector2(0.0f, 0.0f), Vector2(50.0f, 50.0f), graphics::Color(0, 255, 255, 255));
    debugDrawable->point(Vector2(75.0f, 75.0f), graphics::Color(255, 0, 0, 255));

    debugDrawable->circle(Vector2(75.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255));
    debugDrawable->circle(Vector2(25.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255), true);

    scene::NodePtr drawNode = make_shared<scene::Node>();
    drawNode->addDrawable(debugDrawable);
    drawNode->setPosition(Vector2(-300, 0.0f));
    layer->addChild(drawNode);

    drawNode->animate(make_shared<scene::Shake>(10.0f, Vector2(10.0f, 20.0f), 20.0f));

    scene::SpritePtr characterSprite = scene::Sprite::createFromFile("run.json");
    characterSprite->play(true);

    character = make_shared<scene::Node>();
    character->addDrawable(characterSprite);
    layer->addChild(character);
    character->setPosition(Vector2(-300.0f, 0.0f));

    vector<scene::AnimatorPtr> sequence = {
        make_shared<scene::Move>(4.0f, Vector2(300.0f, 0.0f)),
        make_shared<scene::Fade>(2.0f, 0.4f)
    };

    character->animate(make_shared<scene::Sequence>(sequence));

    scene::SpritePtr fireSprite = scene::Sprite::createFromFile("fire.json");
    fireSprite->play(true);

    scene::NodePtr fireNode = make_shared<scene::Node>();
    fireNode->addDrawable(fireSprite);
    fireNode->setPosition(Vector2(-100.0f, -100.0f));
    layer->addChild(fireNode);
    fireNode->animate(make_shared<scene::Fade>(5.0f, 0.5f));

    scene::ParticleSystemPtr flameParticleSystem = scene::ParticleSystem::createFromFile("flame.json");

    flame = make_shared<scene::Node>();
    flame->addDrawable(flameParticleSystem);
    layer->addChild(flame);

    scene::SpritePtr witchSprite = scene::Sprite::createFromFile("witch.png");
    //witchSprite->setColor(graphics::Color(128, 0, 255, 255));

    witch = make_shared<scene::Node>();
    witch->addDrawable(witchSprite);
    witch->setPosition(Vector2(100.0f, 100.0f));
    layer->addChild(witch);
    witch->animate(make_shared<scene::Repeat>(make_shared<scene::Rotate>(1.0f, TAU, false), 3));

    gui::LabelPtr label = gui::Label::create("font.fnt", sharedEngine->getLocalization()->getString("Test"));
    uiLayer->addChild(label);

    vector<scene::AnimatorPtr> sequence2 = {
        make_shared<scene::Animator>(1.0f), // delay
        make_shared<scene::Ease>(make_shared<scene::Move>(2.0f, Vector2(0.0f, -240.0f), false), scene::Ease::Type::OUT, scene::Ease::Func::BOUNCE)
    };

    label->animate(make_shared<scene::Sequence>(sequence2));

    button = gui::Button::create("button.png", "button.png", "button_down.png", "", "", graphics::Color(), "");
    button->setPosition(Vector2(-200.0f, 200.0f));
    uiLayer->addChild(button);

    // Render target

    scene::NodePtr rtCharacter = make_shared<scene::Node>();
    rtCharacter->addDrawable(characterSprite);
    rtLayer->addChild(rtCharacter);

    scene::SpriteFramePtr rtFrame = scene::SpriteFrame::create(Rectangle(0.0f, 0.0f, 256.0f, 256.0f), renderTarget->getTexture(), false, renderTarget->getTexture()->getSize(), Vector2(), Vector2(0.5f, 0.5f));

    scene::SpritePtr rtSprite = scene::Sprite::createFromSpriteFrames({ rtFrame });
    scene::NodePtr rtNode = make_shared<scene::Node>();
    rtNode->addDrawable(rtSprite);
    rtNode->setPosition(Vector2(200.0f, 200.0f));
    layer->addChild(rtNode);

    sharedEngine->getInput()->startGamepadDiscovery();
}

bool Application::handleKeyboard(Event::Type type, const KeyboardEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(sender);

    if (type == Event::Type::KEY_DOWN)
    {
        Vector2 position = layer->getCamera()->getPosition();

        switch (event.key)
        {
            case input::KeyboardKey::UP:
                position.y += 10.0f;
                break;
            case input::KeyboardKey::DOWN:
                position.y -= 10.0f;
                break;
            case input::KeyboardKey::LEFT:
                position.x -= 10.0f;
                break;
            case input::KeyboardKey::RIGHT:
                position.x += 10.0f;
                break;
            case input::KeyboardKey::SPACE:
                witch->setVisible(!witch->isVisible());
                break;
            case input::KeyboardKey::RETURN:
                sharedEngine->getWindow()->setSize(Size2(640.0f, 480.0f));
                break;
            case input::KeyboardKey::TAB:
                button->setEnabled(!button->isEnabled());
                break;
            default:
                break;
        }

        layer->getCamera()->setPosition(position);
    }

    return true;
}

bool Application::handleMouse(Event::Type type, const MouseEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(sender);

    switch (type)
    {
        case Event::Type::MOUSE_DOWN:
        {
            sharedEngine->getInput()->setCursorVisible(!sharedEngine->getInput()->isCursorVisible());
            break;
        }
        case Event::Type::MOUSE_MOVE:
        {
            Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
            flame->setPosition(worldLocation);
            break;
        }
        default:
            break;
    }

    return true;
}

bool Application::handleTouch(Event::Type type, const TouchEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(type);
    OUZEL_UNUSED(sender);

    Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
    flame->setPosition(worldLocation);

    return true;
}

bool Application::handleGamepad(Event::Type type, const GamepadEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(sender);

    if (type == Event::Type::GAMEPAD_BUTTON_CHANGE)
    {
        Vector2 position = layer->getCamera()->convertWorldToScreen(flame->getPosition());

        switch (event.button)
        {
            case input::GamepadButton::DPAD_UP:
            case input::GamepadButton::LEFT_THUMB_UP:
            case input::GamepadButton::RIGHT_THUMB_UP:
                position.y = event.value;
                break;
            case input::GamepadButton::DPAD_DOWN:
            case input::GamepadButton::LEFT_THUMB_DOWN:
            case input::GamepadButton::RIGHT_THUMB_DOWN:
                position.y = -event.value;
                break;
            case input::GamepadButton::DPAD_LEFT:
            case input::GamepadButton::LEFT_THUMB_LEFT:
            case input::GamepadButton::RIGHT_THUMB_LEFT:
                position.x = -event.value;
                break;
            case input::GamepadButton::DPAD_RIGHT:
            case input::GamepadButton::LEFT_THUMB_RIGHT:
            case input::GamepadButton::RIGHT_THUMB_RIGHT:
                position.x = event.value;
                break;
            case input::GamepadButton::A:
                witch->setVisible(!event.pressed);
                break;
            default:
                break;
        }

        Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(position);
        flame->setPosition(worldLocation);
    }

    return true;
}

bool Application::handleUI(Event::Type type, const UIEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(event);

    if (type == Event::Type::UI_CLICK_NODE && sender == button)
    {
        character->setVisible(!character->isVisible());
    }

    return true;
}
<commit_msg>Move witch sprite away<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "Application.h"
#include <cmath>

using namespace std;
using namespace ouzel;

Application::~Application()
{
    sharedEngine->getEventDispatcher()->removeEventHandler(eventHandler);
}

void Application::begin()
{
#if defined(OUZEL_PLATFORM_WINDOWS) || defined(OUZEL_PLATFORM_LINUX)
    sharedEngine->getFileSystem()->addResourcePath("Resources");
#endif

    sharedEngine->getLocalization()->addLanguage("latvian", "lv.mo");
    sharedEngine->getLocalization()->setLanguage("latvian");

    eventHandler = make_shared<EventHandler>();

    eventHandler->keyboardHandler = bind(&Application::handleKeyboard, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->mouseHandler = bind(&Application::handleMouse, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->touchHandler = bind(&Application::handleTouch, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->gamepadHandler = bind(&Application::handleGamepad, this, placeholders::_1, placeholders::_2, placeholders::_3);
    eventHandler->uiHandler = bind(&Application::handleUI, this, placeholders::_1, placeholders::_2, placeholders::_3);

    sharedEngine->getEventDispatcher()->addEventHandler(eventHandler);

    sharedEngine->getRenderer()->setClearColor(graphics::Color(64, 0, 0));
    sharedEngine->getWindow()->setTitle("Sample");

    scene::ScenePtr scene = make_shared<scene::Scene>();
    sharedEngine->getSceneManager()->setScene(scene);

    rtLayer = make_shared<scene::Layer>();
    scene->addLayer(rtLayer);
    renderTarget = sharedEngine->getRenderer()->createRenderTarget(Size2(256.0f, 256.0f), false);
    renderTarget->setClearColor(graphics::Color(0, 64, 0));
    rtLayer->setCamera(make_shared<scene::Camera>());
    rtLayer->setRenderTarget(renderTarget);

    layer = make_shared<scene::Layer>();
    scene->addLayer(layer);
    layer->setCamera(make_shared<scene::Camera>());

    uiLayer = make_shared<scene::Layer>();
    scene->addLayer(uiLayer);
    uiLayer->setCamera(make_shared<scene::Camera>());

    scene::DebugDrawablePtr debugDrawable = make_shared<scene::DebugDrawable>();
    debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(0, 128, 128, 255), true);
    debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(255, 255, 255, 255), false);
    debugDrawable->line(Vector2(0.0f, 0.0f), Vector2(50.0f, 50.0f), graphics::Color(0, 255, 255, 255));
    debugDrawable->point(Vector2(75.0f, 75.0f), graphics::Color(255, 0, 0, 255));

    debugDrawable->circle(Vector2(75.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255));
    debugDrawable->circle(Vector2(25.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255), true);

    scene::NodePtr drawNode = make_shared<scene::Node>();
    drawNode->addDrawable(debugDrawable);
    drawNode->setPosition(Vector2(-300, 0.0f));
    layer->addChild(drawNode);

    drawNode->animate(make_shared<scene::Shake>(10.0f, Vector2(10.0f, 20.0f), 20.0f));

    scene::SpritePtr characterSprite = scene::Sprite::createFromFile("run.json");
    characterSprite->play(true);

    character = make_shared<scene::Node>();
    character->addDrawable(characterSprite);
    layer->addChild(character);
    character->setPosition(Vector2(-300.0f, 0.0f));

    vector<scene::AnimatorPtr> sequence = {
        make_shared<scene::Move>(4.0f, Vector2(300.0f, 0.0f)),
        make_shared<scene::Fade>(2.0f, 0.4f)
    };

    character->animate(make_shared<scene::Sequence>(sequence));

    scene::SpritePtr fireSprite = scene::Sprite::createFromFile("fire.json");
    fireSprite->play(true);

    scene::NodePtr fireNode = make_shared<scene::Node>();
    fireNode->addDrawable(fireSprite);
    fireNode->setPosition(Vector2(-100.0f, -100.0f));
    layer->addChild(fireNode);
    fireNode->animate(make_shared<scene::Fade>(5.0f, 0.5f));

    scene::ParticleSystemPtr flameParticleSystem = scene::ParticleSystem::createFromFile("flame.json");

    flame = make_shared<scene::Node>();
    flame->addDrawable(flameParticleSystem);
    layer->addChild(flame);

    scene::SpritePtr witchSprite = scene::Sprite::createFromFile("witch.png");
    //witchSprite->setColor(graphics::Color(128, 0, 255, 255));

    witch = make_shared<scene::Node>();
    witch->addDrawable(witchSprite);
    witch->setPosition(Vector2(-250.0f, -200.0f));
    layer->addChild(witch);
    witch->animate(make_shared<scene::Repeat>(make_shared<scene::Rotate>(1.0f, TAU, false), 3));

    gui::LabelPtr label = gui::Label::create("font.fnt", sharedEngine->getLocalization()->getString("Test"));
    uiLayer->addChild(label);

    vector<scene::AnimatorPtr> sequence2 = {
        make_shared<scene::Animator>(1.0f), // delay
        make_shared<scene::Ease>(make_shared<scene::Move>(2.0f, Vector2(0.0f, -240.0f), false), scene::Ease::Type::OUT, scene::Ease::Func::BOUNCE)
    };

    label->animate(make_shared<scene::Sequence>(sequence2));

    button = gui::Button::create("button.png", "button.png", "button_down.png", "", "", graphics::Color(), "");
    button->setPosition(Vector2(-200.0f, 200.0f));
    uiLayer->addChild(button);

    // Render target

    scene::NodePtr rtCharacter = make_shared<scene::Node>();
    rtCharacter->addDrawable(characterSprite);
    rtLayer->addChild(rtCharacter);

    scene::SpriteFramePtr rtFrame = scene::SpriteFrame::create(Rectangle(0.0f, 0.0f, 256.0f, 256.0f), renderTarget->getTexture(), false, renderTarget->getTexture()->getSize(), Vector2(), Vector2(0.5f, 0.5f));

    scene::SpritePtr rtSprite = scene::Sprite::createFromSpriteFrames({ rtFrame });
    scene::NodePtr rtNode = make_shared<scene::Node>();
    rtNode->addDrawable(rtSprite);
    rtNode->setPosition(Vector2(200.0f, 200.0f));
    layer->addChild(rtNode);

    sharedEngine->getInput()->startGamepadDiscovery();
}

bool Application::handleKeyboard(Event::Type type, const KeyboardEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(sender);

    if (type == Event::Type::KEY_DOWN)
    {
        Vector2 position = layer->getCamera()->getPosition();

        switch (event.key)
        {
            case input::KeyboardKey::UP:
                position.y += 10.0f;
                break;
            case input::KeyboardKey::DOWN:
                position.y -= 10.0f;
                break;
            case input::KeyboardKey::LEFT:
                position.x -= 10.0f;
                break;
            case input::KeyboardKey::RIGHT:
                position.x += 10.0f;
                break;
            case input::KeyboardKey::SPACE:
                witch->setVisible(!witch->isVisible());
                break;
            case input::KeyboardKey::RETURN:
                sharedEngine->getWindow()->setSize(Size2(640.0f, 480.0f));
                break;
            case input::KeyboardKey::TAB:
                button->setEnabled(!button->isEnabled());
                break;
            default:
                break;
        }

        layer->getCamera()->setPosition(position);
    }

    return true;
}

bool Application::handleMouse(Event::Type type, const MouseEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(sender);

    switch (type)
    {
        case Event::Type::MOUSE_DOWN:
        {
            sharedEngine->getInput()->setCursorVisible(!sharedEngine->getInput()->isCursorVisible());
            break;
        }
        case Event::Type::MOUSE_MOVE:
        {
            Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
            flame->setPosition(worldLocation);
            break;
        }
        default:
            break;
    }

    return true;
}

bool Application::handleTouch(Event::Type type, const TouchEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(type);
    OUZEL_UNUSED(sender);

    Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
    flame->setPosition(worldLocation);

    return true;
}

bool Application::handleGamepad(Event::Type type, const GamepadEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(sender);

    if (type == Event::Type::GAMEPAD_BUTTON_CHANGE)
    {
        Vector2 position = layer->getCamera()->convertWorldToScreen(flame->getPosition());

        switch (event.button)
        {
            case input::GamepadButton::DPAD_UP:
            case input::GamepadButton::LEFT_THUMB_UP:
            case input::GamepadButton::RIGHT_THUMB_UP:
                position.y = event.value;
                break;
            case input::GamepadButton::DPAD_DOWN:
            case input::GamepadButton::LEFT_THUMB_DOWN:
            case input::GamepadButton::RIGHT_THUMB_DOWN:
                position.y = -event.value;
                break;
            case input::GamepadButton::DPAD_LEFT:
            case input::GamepadButton::LEFT_THUMB_LEFT:
            case input::GamepadButton::RIGHT_THUMB_LEFT:
                position.x = -event.value;
                break;
            case input::GamepadButton::DPAD_RIGHT:
            case input::GamepadButton::LEFT_THUMB_RIGHT:
            case input::GamepadButton::RIGHT_THUMB_RIGHT:
                position.x = event.value;
                break;
            case input::GamepadButton::A:
                witch->setVisible(!event.pressed);
                break;
            default:
                break;
        }

        Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(position);
        flame->setPosition(worldLocation);
    }

    return true;
}

bool Application::handleUI(Event::Type type, const UIEvent& event, const VoidPtr& sender) const
{
    OUZEL_UNUSED(event);

    if (type == Event::Type::UI_CLICK_NODE && sender == button)
    {
        character->setVisible(!character->isVisible());
    }

    return true;
}
<|endoftext|>


<commit_before>//===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting arm_neon.h, which includes
// a declaration and definition of each function specified by the ARM NEON
// compiler interface.  See ARM document DUI0348B.
//
//===----------------------------------------------------------------------===//

#include "NeonEmitter.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include <string>

using namespace llvm;

void NeonEmitter::run(raw_ostream &OS) {
  EmitSourceFileHeader("ARM NEON Header", OS);

  // FIXME: emit license into file?

  OS << "#ifndef __ARM_NEON_H\n";
  OS << "#define __ARM_NEON_H\n\n";

  OS << "#ifndef __ARM_NEON__\n";
  OS << "#error \"NEON support not enabled\"\n";
  OS << "#endif\n\n";

  OS << "#include <stdint.h>\n\n";

  // EmitTypedefs(OS);

  // Process Records

  std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");

  // Unique the pattern types, and assign them

  // emit #define directives for uniq'd prototypes

  // emit record directives

  for (unsigned i = 0, e = RV.size(); i != e; ++i) {
    Record *R = RV[i];

    OS << LowercaseString(R->getName()) << "\n";

    std::string Types = R->getValueAsString("Types");
    //std::string Pattern = R->getValueAsString("Pattern");
    //OS << Types << "\n" << Pattern << "\n\n";
  }

  OS << "#endif /* __ARM_NEON_H */\n";
}
<commit_msg>Checkpoint arm_neon.h generation with tablegen<commit_after>//===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting arm_neon.h, which includes
// a declaration and definition of each function specified by the ARM NEON
// compiler interface.  See ARM document DUI0348B.
//
//===----------------------------------------------------------------------===//

#include "NeonEmitter.h"
#include "Record.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include <string>

using namespace llvm;

static void ParseTypes(Record *r, std::string &s,
                       SmallVectorImpl<StringRef> &TV) {
  const char *data = s.data();
  int len = 0;

  for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
    if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
      continue;

    switch (data[len]) {
      case 'c':
      case 's':
      case 'i':
      case 'l':
      case 'h':
      case 'f':
        break;
      default:
        throw TGError(r->getLoc(),
                      "Unexpected letter: " + std::string(data + len, 1));
        break;
    }
    TV.push_back(StringRef(data, len + 1));
    data += len + 1;
    len = -1;
  }
}

static const char Widen(const char t) {
  switch (t) {
    case 'c':
      return 's';
    case 's':
      return 'i';
    case 'i':
      return 'l';
    default: throw "unhandled type in widen!";
  }
  return '\0';
}

static std::string TypeString(const char mod, StringRef typestr) {
  unsigned off = 0;

  bool quad = false;
  bool poly = false;
  bool usgn = false;
  bool scal = false;
  bool cnst = false;
  bool pntr = false;

  // remember quad.
  if (typestr[off] == 'Q') {
    quad = true;
    ++off;
  }

  // remember poly.
  if (typestr[off] == 'P') {
    poly = true;
    ++off;
  }

  // remember unsigned.
  if (typestr[off] == 'U') {
    usgn = true;
    ++off;
  }

  // base type to get the type string for.
  char type = typestr[off];

  // Based on the modifying character, change the type and width if necessary.
  switch (mod) {
    case 'v':
      type = 'v';
      scal = true;
      usgn = false;
      break;
    case 't':
      if (poly) {
        poly = false;
        usgn = true;
      }
      break;
    case 'x':
      usgn = true;
      if (type == 'f')
        type = 'i';
      break;
    case 'f':
      type = 'f';
      break;
    case 'w':
      type = Widen(type);
      quad = true;
      break;
    case 'n':
      type = Widen(type);
      break;
    case 'i':
      type = 'i';
      scal = true;
      usgn = false;
      break;
    case 'l':
      type = 'l';
      scal = true;
      usgn = true;
      break;
    case 's':
      scal = true;
      break;
    case 'k':
      quad = true;
      break;
    case 'c':
      cnst = true;
    case 'p':
      pntr = true;
      scal = true;
      break;
    default:
      break;
  }

  SmallString<128> s;

  if (usgn)
    s.push_back('u');

  switch (type) {
    case 'c':
      s += poly ? "poly8" : "int8";
      if (scal)
        break;
      s += quad ? "x16" : "x8";
      break;
    case 's':
      s += poly ? "poly16" : "int16";
      if (scal)
        break;
      s += quad ? "x8" : "x4";
      break;
    case 'i':
      s += "int32";
      if (scal)
        break;
      s += quad ? "x4" : "x2";
      break;
    case 'l':
      s += "int64";
      if (scal)
        break;
      s += quad ? "x2" : "x1";
      break;
    case 'h':
      s += "float16";
      if (scal)
        break;
      s += quad ? "x8" : "x4";
      break;
    case 'f':
      s += "float32";
      if (scal)
        break;
      s += quad ? "x4" : "x2";
      break;
    case 'v':
      s += "void";
      break;
    default:
      throw "unhandled type!";
      break;
  }

  if (mod == '2')
    s += "x2";
  if (mod == '3')
    s += "x3";
  if (mod == '4')
    s += "x4";

  // Append _t, finishing the type string typedef type.
  s += "_t";

  if (cnst)
    s += " const";

  if (pntr)
    s += " *";

  return s.str();
}

// Turn "vst2_lane" into "vst2q_lane_f32", etc.
static std::string MangleName(const std::string &name, StringRef typestr) {
  return "";
}

//
static std::string GenArgs(const std::string &proto, StringRef typestr) {
  return "";
}

void NeonEmitter::run(raw_ostream &OS) {
  EmitSourceFileHeader("ARM NEON Header", OS);

  // FIXME: emit license into file?

  OS << "#ifndef __ARM_NEON_H\n";
  OS << "#define __ARM_NEON_H\n\n";

  OS << "#ifndef __ARM_NEON__\n";
  OS << "#error \"NEON support not enabled\"\n";
  OS << "#endif\n\n";

  OS << "#include <stdint.h>\n\n";

  // EmitTypedefs(OS);

  std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");

  // Initialize Type Map

  // Unique the return+pattern types, and assign them.
  for (unsigned i = 0, e = RV.size(); i != e; ++i) {
    Record *R = RV[i];
    std::string name = LowercaseString(R->getName());
    std::string Proto = R->getValueAsString("Prototype");
    std::string Types = R->getValueAsString("Types");

    SmallVector<StringRef, 16> TypeVec;
    ParseTypes(R, Types, TypeVec);

    for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
      assert(!Proto.empty() && "");

      SmallString<128> Prototype;
      Prototype += TypeString(Proto[0], TypeVec[ti]);
      Prototype += " ";
      Prototype += MangleName(name, TypeVec[ti]);
      Prototype += GenArgs(Proto, TypeVec[ti]);

      OS << Prototype << ";\n";

      // gen definition

        // if (opcode)

          // gen opstring

        // gen builtin (args)
    }
    OS << "\n";
  }

  // TODO:
  // Unique the return+pattern types, and assign them to each record
  // Emit a #define for each unique "type" of intrinsic declaring all variants.
  // Emit a #define for each intrinsic mapping it to a particular type.

  OS << "\n#endif /* __ARM_NEON_H */\n";
}
<|endoftext|>


<commit_before>#include "config.hpp"
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <libevdev/libevdev.h>
#include <linux/input.h>

#include <libweston-3/compositor.h>

using std::string;
/* TODO: add checks to see if values are correct */

string wayfire_config_section::get_string(string name, string default_value)
{
    auto it = options.find(name);
    return (it == options.end() ? default_value : it->second);
}

int wayfire_config_section::get_int(string name, int df)
{
    auto it = options.find(name);
    return (it == options.end() ? df : std::atoi(it->second.c_str()));
}

int wayfire_config_section::get_duration(string name, int df)
{
    int result = get_int(name, df * (1000 / refresh_rate));
    return result / (1000 / refresh_rate);
}

double wayfire_config_section::get_double(string name, double df)
{
    auto it = options.find(name);
    return (it == options.end() ? df : std::atof(it->second.c_str()));
}

wayfire_key wayfire_config_section::get_key(string name, wayfire_key df)
{
    auto it = options.find(name);
    if (it == options.end())
        return df;

    std::stringstream ss(it->second);
    std::vector<std::string> items;
    std::string t;
    while(ss >> t)
        items.push_back(t);

    wayfire_key ans;

    ans.mod = 0;
    for (size_t i = 0; i < items.size() - 1; i++) {
        if (items[i] == "<alt>")
            ans.mod |= MODIFIER_ALT;
        if (items[i] == "<ctrl>")
            ans.mod |= MODIFIER_CTRL;
        if (items[i] == "<shift>")
            ans.mod |= MODIFIER_SHIFT;
        if (items[i] == "<super>")
            ans.mod |= MODIFIER_SUPER;
    }

    ans.keyval = libevdev_event_code_from_name(EV_KEY, items[items.size() - 1].c_str());
    return ans;
}

wayfire_button wayfire_config_section::get_button(string name, wayfire_button df)
{
    auto it = options.find(name);
    if (it == options.end())
        return df;

    std::stringstream ss(it->second);
    std::vector<std::string> items;
    std::string t;
    while(ss >> t)
        items.push_back(t);

    wayfire_button ans;

    ans.mod = 0;
    for (size_t i = 0; i < items.size() - 1; i++) {
        if (items[i] == "<alt>")
            ans.mod |= MODIFIER_ALT;
        if (items[i] == "<ctrl>")
            ans.mod |= MODIFIER_CTRL;
        if (items[i] == "<shift>")
            ans.mod |= MODIFIER_SHIFT;
        if (items[i] == "<super>")
            ans.mod |= MODIFIER_SUPER;
    }

    auto button = items[items.size() - 1];
    if (button == "left")
        ans.button = BTN_LEFT;
    else if (button == "right")
        ans.button = BTN_RIGHT;
    else if (button == "middle")
        ans.button = BTN_MIDDLE;
    else
        ans.button = 0;

    return ans;
}

wayfire_color wayfire_config_section::get_color(string name, wayfire_color df)
{
    auto it = options.find(name);
    if (it == options.end())
        return df;

    wayfire_color ans;
    std::stringstream ss(it->second);
    ss >> ans.r >> ans.g >> ans.b >> ans.a;
    return ans;
}

namespace {
    string trim(string x)
    {
        int i = 0, j = x.length() - 1;
        while(i < (int)x.length() && x[i] == ' ') ++i;
        while(j >= 0 && x[j] == ' ') --j;

        if (i <= j)
            return x.substr(i, j - i + 1);
        else
            return "";
    }
}

wayfire_config::wayfire_config(string name, int rr)
{
    std::ifstream file(name);
    string line;

    refresh_rate = rr;
    wayfire_config_section *current_section;
    int line_id = -1;

    while(std::getline(file, line)) {
        ++line_id;
        if (line.size() == 0 || line[0] == '#')
            continue;

        if (line[0] == '[') {
            current_section = new wayfire_config_section();
            current_section->refresh_rate = rr;
            current_section->name = line.substr(1, line.size() - 2);
            sections.push_back(current_section);
            continue;
        }

        string name, value;
        int i = 0;
        while (i < (int)line.size() && line[i] != '=') i++;
        name = trim(line.substr(0, i));
        value = trim(line.substr(i + 1, line.size() - i - 1));

        current_section->options[name] = value;
    }
}

wayfire_config_section* wayfire_config::get_section(string name)
{
    for (auto section : sections)
        if (section->name == name)
            return section;

    auto nsect = new wayfire_config_section();
    nsect->name = name;
    nsect->refresh_rate = refresh_rate;
    sections.push_back(nsect);
    return nsect;
}
<commit_msg>config: handle "none" as key/button binding<commit_after>#include "config.hpp"
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <libevdev/libevdev.h>
#include <linux/input.h>

#include <libweston-3/compositor.h>

using std::string;
/* TODO: add checks to see if values are correct */

string wayfire_config_section::get_string(string name, string default_value)
{
    auto it = options.find(name);
    return (it == options.end() ? default_value : it->second);
}

int wayfire_config_section::get_int(string name, int df)
{
    auto it = options.find(name);
    return (it == options.end() ? df : std::atoi(it->second.c_str()));
}

int wayfire_config_section::get_duration(string name, int df)
{
    int result = get_int(name, df * (1000 / refresh_rate));
    return result / (1000 / refresh_rate);
}

double wayfire_config_section::get_double(string name, double df)
{
    auto it = options.find(name);
    return (it == options.end() ? df : std::atof(it->second.c_str()));
}

wayfire_key wayfire_config_section::get_key(string name, wayfire_key df)
{
    auto it = options.find(name);
    if (it == options.end())
        return df;

    if (it->second == "none")
        return {0, 0};

    std::stringstream ss(it->second);
    std::vector<std::string> items;
    std::string t;
    while(ss >> t)
        items.push_back(t);

    wayfire_key ans;

    ans.mod = 0;
    for (size_t i = 0; i < items.size() - 1; i++) {
        if (items[i] == "<alt>")
            ans.mod |= MODIFIER_ALT;
        if (items[i] == "<ctrl>")
            ans.mod |= MODIFIER_CTRL;
        if (items[i] == "<shift>")
            ans.mod |= MODIFIER_SHIFT;
        if (items[i] == "<super>")
            ans.mod |= MODIFIER_SUPER;
    }

    ans.keyval = libevdev_event_code_from_name(EV_KEY, items[items.size() - 1].c_str());
    return ans;
}

wayfire_button wayfire_config_section::get_button(string name, wayfire_button df)
{
    auto it = options.find(name);
    if (it == options.end())
        return df;

    if (it->second == "none")
        return {0, 0};

    std::stringstream ss(it->second);
    std::vector<std::string> items;
    std::string t;
    while(ss >> t)
        items.push_back(t);

    wayfire_button ans;

    ans.mod = 0;
    for (size_t i = 0; i < items.size() - 1; i++) {
        if (items[i] == "<alt>")
            ans.mod |= MODIFIER_ALT;
        if (items[i] == "<ctrl>")
            ans.mod |= MODIFIER_CTRL;
        if (items[i] == "<shift>")
            ans.mod |= MODIFIER_SHIFT;
        if (items[i] == "<super>")
            ans.mod |= MODIFIER_SUPER;
    }

    auto button = items[items.size() - 1];
    if (button == "left")
        ans.button = BTN_LEFT;
    else if (button == "right")
        ans.button = BTN_RIGHT;
    else if (button == "middle")
        ans.button = BTN_MIDDLE;
    else
        ans.button = 0;

    return ans;
}

wayfire_color wayfire_config_section::get_color(string name, wayfire_color df)
{
    auto it = options.find(name);
    if (it == options.end())
        return df;

    wayfire_color ans = {0, 0, 0, 0};
    std::stringstream ss(it->second);
    ss >> ans.r >> ans.g >> ans.b >> ans.a;
    return ans;
}

namespace {
    string trim(string x)
    {
        int i = 0, j = x.length() - 1;
        while(i < (int)x.length() && x[i] == ' ') ++i;
        while(j >= 0 && x[j] == ' ') --j;

        if (i <= j)
            return x.substr(i, j - i + 1);
        else
            return "";
    }
}

wayfire_config::wayfire_config(string name, int rr)
{
    std::ifstream file(name);
    string line;

    refresh_rate = rr;
    wayfire_config_section *current_section;
    int line_id = -1;

    while(std::getline(file, line)) {
        ++line_id;
        if (line.size() == 0 || line[0] == '#')
            continue;

        if (line[0] == '[') {
            current_section = new wayfire_config_section();
            current_section->refresh_rate = rr;
            current_section->name = line.substr(1, line.size() - 2);
            sections.push_back(current_section);
            continue;
        }

        string name, value;
        int i = 0;
        while (i < (int)line.size() && line[i] != '=') i++;
        name = trim(line.substr(0, i));
        value = trim(line.substr(i + 1, line.size() - i - 1));

        current_section->options[name] = value;
    }
}

wayfire_config_section* wayfire_config::get_section(string name)
{
    for (auto section : sections)
        if (section->name == name)
            return section;

    auto nsect = new wayfire_config_section();
    nsect->name = name;
    nsect->refresh_rate = refresh_rate;
    sections.push_back(nsect);
    return nsect;
}
<|endoftext|>


<commit_before>#include <Codegen.h>
#include <Python.h>
#include <stdio.h>

static PyObject * echoprint_codegen(PyObject *self, PyObject *args) {
    PyObject *py_samples;
    int start_offset = 0;
    PyObject *item;
    float *samples;
    uint num_samples;
    uint i;
    Codegen *pCodegen;
    PyObject *result;

    if (!PyArg_ParseTuple(args, "O|i", &py_samples, &start_offset)) {
        return NULL;
    }
    if (!PySequence_Check(py_samples)) {
        PyErr_SetString(PyExc_TypeError, "expected sequence");
        return NULL;
    }
    num_samples = PySequence_Size(py_samples);
    samples = new float[num_samples];
    for (i = 0; i < num_samples; i++) {
        item = PySequence_GetItem(py_samples, i);
        if (!PyFloat_Check(item)) {
            delete[] samples;
            PyErr_SetString(PyExc_TypeError, "expected sequence of floats");
            return NULL;
        }
        samples[i] = (float)PyFloat_AsDouble(item);
        Py_DECREF(item);
    }
    pCodegen = new Codegen(samples, num_samples, start_offset);
    result = Py_BuildValue("{s:s,s:s}",
        "code", pCodegen->getCodeString().c_str(),
        "version", pCodegen->getVersion()
    );
    delete pCodegen;
    delete[] samples;
    return result;
}

static PyMethodDef echoprint_methods[] = {
    {"codegen", echoprint_codegen, METH_VARARGS,
     "Generates a echoprint code for a list of floating point PCM data sampled at 11025 Hz and mono. Optionally takes a second integer argument to hint the server on where the sample is taken from in the original file if known."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initechoprint(void)
{
    (void) Py_InitModule("echoprint", echoprint_methods);
}

<commit_msg>Making sure the version number is passed over correctly, as a float<commit_after>#include <Codegen.h>
#include <Python.h>
#include <stdio.h>

static PyObject * echoprint_codegen(PyObject *self, PyObject *args) {
    PyObject *py_samples;
    int start_offset = 0;
    PyObject *item;
    float *samples;
    uint num_samples;
    uint i;
    Codegen *pCodegen;
    PyObject *result;

    if (!PyArg_ParseTuple(args, "O|i", &py_samples, &start_offset)) {
        return NULL;
    }
    if (!PySequence_Check(py_samples)) {
        PyErr_SetString(PyExc_TypeError, "expected sequence");
        return NULL;
    }
    num_samples = PySequence_Size(py_samples);
    samples = new float[num_samples];

    for (i = 0; i < num_samples; i++) {
        item = PySequence_GetItem(py_samples, i);
        if (!PyFloat_Check(item)) {
            delete[] samples;
            PyErr_SetString(PyExc_TypeError, "expected sequence of floats");
            return NULL;
        }
        samples[i] = (float)PyFloat_AsDouble(item);
        Py_DECREF(item);
    }
    pCodegen = new Codegen(samples, num_samples, start_offset);
    result = Py_BuildValue("{s:s,s:f}",
        "code", pCodegen->getCodeString().c_str(),
        "version", pCodegen->getVersion()
    );
    delete pCodegen;
    delete[] samples;
    return result;
}

static PyMethodDef echoprint_methods[] = {
    {"codegen", echoprint_codegen, METH_VARARGS,
     "Generates a echoprint code for a list of floating point PCM data sampled at 11025 Hz and mono. Optionally takes a second integer argument to hint the server on where the sample is taken from in the original file if known."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initechoprint(void)
{
    (void) Py_InitModule("echoprint", echoprint_methods);
}

<|endoftext|>


<commit_before><commit_msg>coverity#1187685 Dereference null return value<commit_after><|endoftext|>


<commit_before>#include "../element.h"
#include "gtest/gtest.h"
#include <sstream>
#include <string>
#include <iostream>
#include <array>
#include <vector>
#include <set>

TEST(Decoding, Int32)
{
  bson::Element e;
  unsigned char bs[4];
  for (int i=0; i<10000; i++)
  {
    memcpy(bs, &i, sizeof(i));
    e.decode(bs, bson::INT32);
    ASSERT_EQ(i, e.data<int>());
  }
}

TEST(Decoding, Int64)
{
  bson::Element e;
  unsigned char bs[8];
  for (long i=0; i<100000; i++)
  {
    memcpy(bs, &i, sizeof(i));
    e.decode(bs, bson::INT64);
    ASSERT_EQ(i, e.data<long>());
  }
}

TEST(Decoding, String)
{
  bson::Element e;
  const unsigned char bs[] = {0x7,0,0,0,'$','q','u','e','r','y', 0};
  e.decode(bs, bson::STRING);
  ASSERT_EQ(std::string("$query"), e.data<std::string>());
}

TEST(Decoding, Document)
{
  bson::Element e;
  // This is actual hex pulled from a mongodb query, not just random crap
  // I promise.
  unsigned char bs[] = {0x3c,0x0,0x0,0x0,0x7,0x5f,0x69,0x64,0x0,0x53,
                        0xd1,0x2b,0xc6,0x86,0x0,0xb0,0xad,0x4f,0xbb,
		        0x90,0x2c,0x2,0x73,0x0,0x2,0x0,0x0,0x0,0x62,
		        0x0,0x10,0x69,0x0,0xd2,0x4,0x0,0x0,0x1,0x64,
		        0x0,0x1f,0x85,0xeb,0x51,0xb8,0x1e,0x9,0x40,
		        0x12,0x6c,0x0,0x16,0xeb,0xe,0xd9,0x1c,0x1,0x0,0x0,0x0};
  e.decode(bs, bson::DOCUMENT);
  std::set<std::string> fields = e.data<bson::Document>().field_names();
  ASSERT_EQ(5, fields.size());
  ASSERT_EQ(1, fields.count("_id"));
  ASSERT_EQ(1, fields.count("s"));
  ASSERT_EQ(1, fields.count("i"));
  ASSERT_EQ(1, fields.count("d"));
  ASSERT_EQ(1, fields.count("l"));

  ASSERT_EQ(std::string("b"), std::string(e.data<bson::Document>()["s"]));
  ASSERT_EQ(1234, e.data<bson::Document>()["i"].data<int>());
  ASSERT_EQ(1223412345622, e.data<bson::Document>()["l"].data<long>());
  ASSERT_EQ(3.14000, e.data<bson::Document>()["d"].data<double>());
  ASSERT_EQ(std::string("53d12bc68600b0ad4fbb902c"), static_cast<std::string>(e.data<bson::Document>()["_id"]));
}

TEST(Decoding, BoolTrue)
{
  unsigned char abool[] = {0x1};
  bson::Element e;
  bool res;
  ASSERT_EQ(1, e.decode(abool, bson::BOOL));
  e.data(res);
  ASSERT_TRUE(res);
}

TEST(Decoding, BoolFalse)
{
  unsigned char abool[] = {0x0};
  bson::Element e;
  bool res;
  ASSERT_EQ(1, e.decode(abool, bson::BOOL));
  e.data(res);
  ASSERT_FALSE(res);
}

TEST(Decoding, ArrayEmpty)
{
  unsigned char avec[] = {5, 0, 0, 0, 0};
  bson::Element e;
  bson::array res;
  ASSERT_EQ(5, e.decode(avec, bson::ARRAY));
  e.data(res);
  ASSERT_EQ(0, res.size());
}
TEST(Decoding, ArrayNonEmpty)
{
  unsigned char avec[] = {0x0c, 0, 0, 0,
                          0x10, '0', 0,
			  3, 0, 0, 0,
			  0};
  bson::Element e;
  bson::array res;
  ASSERT_EQ(12, e.decode(avec, bson::ARRAY));
  e.data(res);
  ASSERT_EQ(1, res.size());
  ASSERT_EQ(3, res[0].data<int>());
}

TEST(Decoding, MinKey)
{
  unsigned char minkey[] = {0};
  bson::Element e;
  ASSERT_EQ(0, e.decode(minkey, bson::MINKEY));
}
TEST(Decoding, MaxKey)
{
  unsigned char maxkey[] = {0};
  bson::Element e;
  ASSERT_EQ(0, e.decode(maxkey, bson::MAXKEY));
}
TEST(Decoding, Nil)
{
  unsigned char nil[] = {0};
  bson::Element e;
  ASSERT_EQ(0, e.decode(nil, bson::NIL));
}

TEST(Decoding, RegEx)
{
  unsigned char regex[] = {'a', 'b', 'c', 0, 'd', 'e', 'f', 0};
  bson::Element e;
  ASSERT_EQ(8, e.decode(regex, bson::REGEX));
  ASSERT_EQ(std::string("abc"), e.data<bson::regex>().first);
  ASSERT_EQ(std::string("def"), e.data<bson::regex>().second);
}

TEST(Decoding, DbPtr)
{
  unsigned char dbptr[] = {2, 0, 0, 0, 'a', 0, 1,2,3,4,5,6,7,8,9,10,11,12};
  bson::Element e;
  ASSERT_EQ(18, e.decode(dbptr, bson::DBPTR));
  ASSERT_EQ(std::string("a"), e.data<bson::dbptr>().first);
  for (unsigned char i = 0; i < 12; i++)
  {

    ASSERT_EQ(i+1, e.data<bson::dbptr>().second[i]);
  }
}

TEST(Decoding, EmptyJS)
{
  unsigned char jscd[] = {14, 0, 0, 0,
                          1, 0, 0, 0, 0,
                          5, 0 ,0, 0, 0};
  bson::Element e;
  ASSERT_EQ(14, e.decode(jscd, bson::JS_SCOPE));
}

TEST(Decoding, NonEmptyJS)
{
  unsigned char jscd[] = {22, 0, 0, 0,
                          2, 0, 0, 0, '$', 0,
                          0x0c, 0, 0, 0,
                          0x10, '0', 0,
			  3, 0, 0, 0,
			  0};
  bson::Element e;
  ASSERT_EQ(22, e.decode(jscd, bson::JS_SCOPE));
  ASSERT_EQ(std::string("$"), e.data<bson::jscode_scope>().first);
  ASSERT_EQ(3, e.data<bson::jscode_scope>().second["0"].data<int>());
}

TEST(Decoding, BinaryEmpty)
{
  unsigned char bin[] = {0,0,0,0,0};
  bson::Element e;
  ASSERT_EQ(5, e.decode(bin, bson::BINARY));
}

TEST(Decoding, BinaryNonEmpty)
{
  unsigned char bin[] = {7,0,0,0,0,0,1,2,3,4,5,6};
  bson::Element e;
  ASSERT_EQ(12, e.decode(bin, bson::BINARY));
  ASSERT_EQ(0x0, e.data<bson::binary>().first);
  ASSERT_EQ(7, e.data<bson::binary>().second.size());
  for (char i = 0; i < 7; i++)
    ASSERT_EQ(i, e.data<bson::binary>().second[i]);
}<commit_msg>complete coverage of tests for decoding function<commit_after>#include "../element.h"
#include "gtest/gtest.h"
#include <sstream>
#include <string>
#include <iostream>
#include <array>
#include <vector>
#include <set>

TEST(Decoding, Int32)
{
  bson::Element e;
  unsigned char bs[4];
  for (int i=0; i<10000; i++)
  {
    memcpy(bs, &i, sizeof(i));
    e.decode(bs, bson::INT32);
    ASSERT_EQ(i, e.data<int>());
  }
}

TEST(Decoding, Int64)
{
  bson::Element e;
  unsigned char bs[8];
  for (long i=0; i<100000; i++)
  {
    memcpy(bs, &i, sizeof(i));
    e.decode(bs, bson::INT64);
    ASSERT_EQ(i, e.data<long>());
  }
}

TEST(Decoding, String)
{
  bson::Element e;
  const unsigned char bs[] = {0x7,0,0,0,'$','q','u','e','r','y', 0};
  e.decode(bs, bson::STRING);
  ASSERT_EQ(std::string("$query"), e.data<std::string>());
}

TEST(Decoding, Document)
{
  bson::Element e;
  // This is actual hex pulled from a mongodb query, not just random crap
  // I promise.
  unsigned char bs[] = {0x3c,0x0,0x0,0x0,0x7,0x5f,0x69,0x64,0x0,0x53,
                        0xd1,0x2b,0xc6,0x86,0x0,0xb0,0xad,0x4f,0xbb,
		        0x90,0x2c,0x2,0x73,0x0,0x2,0x0,0x0,0x0,0x62,
		        0x0,0x10,0x69,0x0,0xd2,0x4,0x0,0x0,0x1,0x64,
		        0x0,0x1f,0x85,0xeb,0x51,0xb8,0x1e,0x9,0x40,
		        0x12,0x6c,0x0,0x16,0xeb,0xe,0xd9,0x1c,0x1,0x0,0x0,0x0};
  e.decode(bs, bson::DOCUMENT);
  std::set<std::string> fields = e.data<bson::Document>().field_names();
  ASSERT_EQ(5, fields.size());
  ASSERT_EQ(1, fields.count("_id"));
  ASSERT_EQ(1, fields.count("s"));
  ASSERT_EQ(1, fields.count("i"));
  ASSERT_EQ(1, fields.count("d"));
  ASSERT_EQ(1, fields.count("l"));

  ASSERT_EQ(std::string("b"), std::string(e.data<bson::Document>()["s"]));
  ASSERT_EQ(1234, e.data<bson::Document>()["i"].data<int>());
  ASSERT_EQ(1223412345622, e.data<bson::Document>()["l"].data<long>());
  ASSERT_EQ(3.14000, e.data<bson::Document>()["d"].data<double>());
  ASSERT_EQ(std::string("53d12bc68600b0ad4fbb902c"), static_cast<std::string>(e.data<bson::Document>()["_id"]));
}

TEST(Decoding, BoolTrue)
{
  unsigned char abool[] = {0x1};
  bson::Element e;
  bool res;
  ASSERT_EQ(1, e.decode(abool, bson::BOOL));
  e.data(res);
  ASSERT_TRUE(res);
}

TEST(Decoding, BoolFalse)
{
  unsigned char abool[] = {0x0};
  bson::Element e;
  bool res;
  ASSERT_EQ(1, e.decode(abool, bson::BOOL));
  e.data(res);
  ASSERT_FALSE(res);
}

TEST(Decoding, ArrayEmpty)
{
  unsigned char avec[] = {5, 0, 0, 0, 0};
  bson::Element e;
  bson::array res;
  ASSERT_EQ(5, e.decode(avec, bson::ARRAY));
  e.data(res);
  ASSERT_EQ(0, res.size());
}
TEST(Decoding, ArrayNonEmpty)
{
  unsigned char avec[] = {0x0c, 0, 0, 0,
                          0x10, '0', 0,
			  3, 0, 0, 0,
			  0};
  bson::Element e;
  bson::array res;
  ASSERT_EQ(12, e.decode(avec, bson::ARRAY));
  e.data(res);
  ASSERT_EQ(1, res.size());
  ASSERT_EQ(3, res[0].data<int>());
}

TEST(Decoding, MinKey)
{
  unsigned char minkey[] = {0};
  bson::Element e;
  ASSERT_EQ(0, e.decode(minkey, bson::MINKEY));
}
TEST(Decoding, MaxKey)
{
  unsigned char maxkey[] = {0};
  bson::Element e;
  ASSERT_EQ(0, e.decode(maxkey, bson::MAXKEY));
}
TEST(Decoding, Nil)
{
  unsigned char nil[] = {0};
  bson::Element e;
  ASSERT_EQ(0, e.decode(nil, bson::NIL));
}

TEST(Decoding, RegEx)
{
  unsigned char regex[] = {'a', 'b', 'c', 0, 'd', 'e', 'f', 0};
  bson::Element e;
  ASSERT_EQ(8, e.decode(regex, bson::REGEX));
  ASSERT_EQ(std::string("abc"), e.data<bson::regex>().first);
  ASSERT_EQ(std::string("def"), e.data<bson::regex>().second);
}

TEST(Decoding, DbPtr)
{
  unsigned char dbptr[] = {2, 0, 0, 0, 'a', 0, 1,2,3,4,5,6,7,8,9,10,11,12};
  bson::Element e;
  ASSERT_EQ(18, e.decode(dbptr, bson::DBPTR));
  ASSERT_EQ(std::string("a"), e.data<bson::dbptr>().first);
  for (unsigned char i = 0; i < 12; i++)
  {

    ASSERT_EQ(i+1, e.data<bson::dbptr>().second[i]);
  }
}

TEST(Decoding, EmptyJS)
{
  unsigned char jscd[] = {14, 0, 0, 0,
                          1, 0, 0, 0, 0,
                          5, 0 ,0, 0, 0};
  bson::Element e;
  ASSERT_EQ(14, e.decode(jscd, bson::JS_SCOPE));
}

TEST(Decoding, NonEmptyJS)
{
  unsigned char jscd[] = {22, 0, 0, 0,
                          2, 0, 0, 0, '$', 0,
                          0x0c, 0, 0, 0,
                          0x10, '0', 0,
			  3, 0, 0, 0,
			  0};
  bson::Element e;
  ASSERT_EQ(22, e.decode(jscd, bson::JS_SCOPE));
  ASSERT_EQ(std::string("$"), e.data<bson::jscode_scope>().first);
  ASSERT_EQ(3, e.data<bson::jscode_scope>().second["0"].data<int>());
}

TEST(Decoding, BinaryEmpty)
{
  unsigned char bin[] = {0,0,0,0,0};
  bson::Element e;
  ASSERT_EQ(5, e.decode(bin, bson::BINARY));
}

TEST(Decoding, BinaryNonEmpty)
{
  unsigned char bin[] = {7,0,0,0,0,0,1,2,3,4,5,6};
  bson::Element e;
  ASSERT_EQ(12, e.decode(bin, bson::BINARY));
  ASSERT_EQ(0x0, e.data<bson::binary>().first);
  ASSERT_EQ(7, e.data<bson::binary>().second.size());
  for (char i = 0; i < 7; i++)
    ASSERT_EQ(i, e.data<bson::binary>().second[i]);
}

TEST(Decoding, UnknownException)
{
  unsigned char blah[] = {0};
  bson::Element e;
  ASSERT_THROW(e.decode(blah, bson::_UNKNOWN), bson::type_UNKNOWN);
}<|endoftext|>


<commit_before>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define TYPICAL_MAT_SIZES_CORE_ARITHM   ::szVGA, ::sz720p, ::sz1080p
#define TYPICAL_MAT_TYPES_CORE_ARITHM   CV_8UC1, CV_8SC1, CV_16SC1, CV_16SC2, CV_16SC3, CV_16SC4, CV_8UC4, CV_32SC1, CV_32FC1
#define TYPICAL_MATS_CORE_ARITHM        testing::Combine( testing::Values( TYPICAL_MAT_SIZES_CORE_ARITHM ), testing::Values( TYPICAL_MAT_TYPES_CORE_ARITHM ) )

PERF_TEST_P(Size_MatType, min, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, minScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, max, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, maxScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, absdiff, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, absdiffScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, add, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);
    declare.time(50);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, addScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtract, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtractScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, multiply, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);
    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //According to docs, saturation is not applied when result is 32bit integer
        a /= (2 << 16);
        b /= (2 << 16);
    }

    TEST_CYCLE() multiply(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, multiplyScale, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);
    double scale = 0.5;

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //According to docs, saturation is not applied when result is 32bit integer
        a /= (2 << 16);
        b /= (2 << 16);
    }

    TEST_CYCLE() multiply(a, b, c, scale);

    SANITY_CHECK(c, 1e-8);
}
<commit_msg>Rewrite definition/declaration of variables to be more compact<commit_after>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define TYPICAL_MAT_SIZES_CORE_ARITHM   ::szVGA, ::sz720p, ::sz1080p
#define TYPICAL_MAT_TYPES_CORE_ARITHM   CV_8UC1, CV_8SC1, CV_16SC1, CV_16SC2, CV_16SC3, CV_16SC4, CV_8UC4, CV_32SC1, CV_32FC1
#define TYPICAL_MATS_CORE_ARITHM        testing::Combine( testing::Values( TYPICAL_MAT_SIZES_CORE_ARITHM ), testing::Values( TYPICAL_MAT_TYPES_CORE_ARITHM ) )

PERF_TEST_P(Size_MatType, min, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, minScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, max, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, maxScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, absdiff, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, absdiffScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, add, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);
    declare.time(50);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, addScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtract, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtractScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, multiply, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a(sz, type), b(sz, type), c(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);
    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //According to docs, saturation is not applied when result is 32bit integer
        a /= (2 << 16);
        b /= (2 << 16);
    }

    TEST_CYCLE() multiply(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, multiplyScale, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a(sz, type), b(sz, type), c(sz, type);
    double scale = 0.5;

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //According to docs, saturation is not applied when result is 32bit integer
        a /= (2 << 16);
        b /= (2 << 16);
    }

    TEST_CYCLE() multiply(a, b, c, scale);

    SANITY_CHECK(c, 1e-8);
}
<|endoftext|>