<commit_before>/*******************************************************************************
 * tests/api/operations_test.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia_base.hpp>
#include <c7a/net/endpoint.hpp>
#include <c7a/core/job_manager.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/reduce_node.hpp>
#include <c7a/api/sum_node.hpp>
#include <c7a/api/bootstrap.hpp>

#include <algorithm>
#include <random>

#include "gtest/gtest.h"

using namespace c7a::core;
using namespace c7a::net;

TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) {
    using c7a::Context;

    Context ctx;
    std::vector<std::string> self = { "127.0.0.1:1234" };
    ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self));

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(1000, 10000);

    size_t generate_size = distribution(generator);

    auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            return std::stoi(line);
        },
        generate_size);

    size_t writer_size = 0;

    input.WriteToFileSystem("test1.out",
                           [&writer_size](const int& item) {
                                //file contains ints between 1  and 15
                                //fails if wrong integer is generated
                                EXPECT_GE(item, 1);
                                EXPECT_GE(16, item);
                                writer_size++;
                                return std::to_string(item);
                           });

    ASSERT_EQ(generate_size, writer_size);
}

TEST(Operations, ReadAndAllGatherElementsCorrect) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::vector<int> out_vec;

        integers.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, i++);
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, MapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> double_elements = [](int in) {
            return (double) 2 * in;
        };

        auto doubled = integers.Map(double_elements);

        std::vector<double> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FlatMapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto flatmap_double = [](int in, auto emit) {
            emit((double) 2 * in);
            emit((double) 2 * (in + 16));
        };

        auto doubled = integers.FlatMap(flatmap_double);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 32, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FilterResultsCorrectly) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> even = [](int in) {
            return (in % 2 == 0);
        };

        auto doubled = integers.Filter(even);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 8, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, DISABLED_ReduceModulo2CorrectResults) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto modulo_two = [](int in) {
            return (in / 2);
        };

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        auto reduced = integers.ReduceBy(modulo_two, add_function);

        std::vector<int> out_vec;

         std::cout << "starting" << std::endl;

        reduced.AllGather(&out_vec);

        std::cout << "testing" << std::endl;

        std::sort(out_vec.begin(), out_vec.end());

        std::cout << "[";
        for (int element : out_vec) {
            std::cout << element << ",";
        }
        std::cout<<"]"<<std::endl;

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, 56 + (8 * i++));
        }

        ASSERT_EQ((size_t) 2, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::uniform_int_distribution<int> distribution2(1000, 10000);

    size_t generate_size = distribution2(generator);

    std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) {

        auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            return std::stoi(line);
        },
        generate_size);

        auto ones = input.Map([](int){
                return 1;
            });

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        ASSERT_EQ((int) generate_size, ones.Sum(add_function));
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

/******************************************************************************/
<commit_msg>add print statement to see where jenkins dies<commit_after>/*******************************************************************************
 * tests/api/operations_test.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia_base.hpp>
#include <c7a/net/endpoint.hpp>
#include <c7a/core/job_manager.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/reduce_node.hpp>
#include <c7a/api/sum_node.hpp>
#include <c7a/api/bootstrap.hpp>

#include <algorithm>
#include <random>

#include "gtest/gtest.h"

using namespace c7a::core;
using namespace c7a::net;

TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) {
    using c7a::Context;

    Context ctx;
    std::vector<std::string> self = { "127.0.0.1:1234" };
    ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self));

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(1000, 10000);

    size_t generate_size = distribution(generator);

    auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            std::cout << line << std::endl;
            return std::stoi(line);
        },
        generate_size);

    size_t writer_size = 0;

    input.WriteToFileSystem("test1.out",
                           [&writer_size](const int& item) {
                                //file contains ints between 1  and 15
                                //fails if wrong integer is generated
                                EXPECT_GE(item, 1);
                                EXPECT_GE(16, item);
                                writer_size++;
                                return std::to_string(item);
                           });

    ASSERT_EQ(generate_size, writer_size);
}

TEST(Operations, ReadAndAllGatherElementsCorrect) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::vector<int> out_vec;

        integers.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, i++);
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, MapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> double_elements = [](int in) {
            return (double) 2 * in;
        };

        auto doubled = integers.Map(double_elements);

        std::vector<double> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FlatMapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto flatmap_double = [](int in, auto emit) {
            emit((double) 2 * in);
            emit((double) 2 * (in + 16));
        };

        auto doubled = integers.FlatMap(flatmap_double);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 32, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FilterResultsCorrectly) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> even = [](int in) {
            return (in % 2 == 0);
        };

        auto doubled = integers.Filter(even);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 8, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, DISABLED_ReduceModulo2CorrectResults) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto modulo_two = [](int in) {
            return (in / 2);
        };

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        auto reduced = integers.ReduceBy(modulo_two, add_function);

        std::vector<int> out_vec;

         std::cout << "starting" << std::endl;

        reduced.AllGather(&out_vec);

        std::cout << "testing" << std::endl;

        std::sort(out_vec.begin(), out_vec.end());

        std::cout << "[";
        for (int element : out_vec) {
            std::cout << element << ",";
        }
        std::cout<<"]"<<std::endl;

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, 56 + (8 * i++));
        }

        ASSERT_EQ((size_t) 2, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::uniform_int_distribution<int> distribution2(1000, 10000);

    size_t generate_size = distribution2(generator);

    std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) {

        auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            return std::stoi(line);
        },
        generate_size);

        auto ones = input.Map([](int){
                return 1;
            });

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        ASSERT_EQ((int) generate_size, ones.Sum(add_function));
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

/******************************************************************************/
<|endoftext|>


<commit_before>/*
    Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com>
    Copyright (C) 2010 Collabora Ltd.
      @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "qgsttest.h"
#include <QGst/Object>
#include <QGst/Message>
#include <QGst/Pipeline>
#include <QGst/ElementFactory>
#include <QGst/UriHandler>
#include <QGst/StreamVolume>

class RefPointerTest : public QGstTest
{
    Q_OBJECT
private Q_SLOTS:
    void refTest1();
    void refTest2();
    void dynamicCastTest();
    void dynamicCastDownObjectTest();
    void dynamicCastUpObjectTest();
    void dynamicCastObjectToIfaceTest();
    void dynamicCastIfaceToObjectTest();
    void cppWrappersTest();
    void messageDynamicCastTest();
    void equalityTest();
};

void RefPointerTest::refTest1()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL))));
    gst_object_sink(bin);
    QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin, false);
    QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1);
}

void RefPointerTest::refTest2()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL))));
    gst_object_sink(bin);
    {
        QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin);
        QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 2);
        {
            QGst::ObjectPtr object2 = object;
            QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 3);
        }
    }
    QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1);
    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastTest()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL))));
    gst_object_sink(bin);

    {
        QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin);
        QVERIFY(!object.dynamicCast<QGlib::Object>().isNull());
    }

    {
        QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin));
        QVERIFY(!object.dynamicCast<QGst::Object>().isNull());
    }

    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastDownObjectTest()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(gst_bin_new(NULL)));
    gst_object_sink(bin);

    {
        QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin));
        QVERIFY(!object.dynamicCast<QGst::Object>().isNull());
        QVERIFY(!object.dynamicCast<QGst::Bin>().isNull());
        QVERIFY(object.dynamicCast<QGst::Pipeline>().isNull());
    }

    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastUpObjectTest()
{
    GstBin *bin = GST_BIN(gst_object_ref(gst_bin_new(NULL)));
    gst_object_sink(bin);

    {
        QGst::BinPtr object = QGst::BinPtr::wrap(bin);
        QVERIFY(!object.dynamicCast<QGst::Element>().isNull());
        QVERIFY(!object.dynamicCast<QGlib::Object>().isNull());
        QVERIFY(!object.dynamicCast<QGst::ChildProxy>().isNull());
    }

    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastObjectToIfaceTest()
{
    QGst::ElementPtr e = QGst::ElementFactory::make("fakesrc");
    QGst::UriHandlerPtr u = e.dynamicCast<QGst::UriHandler>();
    QVERIFY(u.isNull());

    e = QGst::ElementFactory::make("filesrc");
    u = e.dynamicCast<QGst::UriHandler>();
    QVERIFY(!u.isNull());
}

void RefPointerTest::dynamicCastIfaceToObjectTest()
{
    GstElement *e = gst_element_factory_make("filesrc", NULL);
    gst_object_ref_sink(e);

    QGst::UriHandlerPtr u = QGst::UriHandlerPtr::wrap(GST_URI_HANDLER(e), false);
    QVERIFY(!u.isNull());
    QVERIFY(!u.dynamicCast<QGst::Element>().isNull());
}

void RefPointerTest::cppWrappersTest()
{
    QGst::ElementPtr e = QGst::ElementFactory::make("playbin2");
    QVERIFY(!e.isNull());

    {
        QGst::PipelinePtr pipeline = e.dynamicCast<QGst::Pipeline>();
        QVERIFY(!pipeline.isNull());
        //the C++ wrappers must be the same
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(pipeline.operator->()),
                 static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    {
        QGst::ChildProxyPtr proxy = e.dynamicCast<QGst::ChildProxy>();
        QVERIFY(!proxy.isNull());
        //the C++ wrappers must be the same
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(proxy.operator->()),
                 static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    { //new wrap() should give the same C++ instance
        GstElement *gobj = e;
        QGst::ElementPtr e2 = QGst::ElementPtr::wrap(gobj);
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(e2.operator->()),
                 static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    {
        QGst::StreamVolumePtr sv = e.dynamicCast<QGst::StreamVolume>();
        QVERIFY(!sv.isNull());
        //now the C++ wrapper must not be the same, since Pipeline does not inherit StreamVolume
        QVERIFY(static_cast<QGlib::RefCountedObject*>(sv.operator->())
                != static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    {
        QGst::MessagePtr msg = QGst::ApplicationMessage::create(e);
        QGst::MessagePtr msg2 = msg;
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(msg.operator->()),
                 static_cast<QGlib::RefCountedObject*>(msg2.operator->()));
        QVERIFY(msg2 == msg);

        QGst::MessagePtr msg3 = QGst::MessagePtr::wrap(msg2);
        QVERIFY(static_cast<QGlib::RefCountedObject*>(msg3.operator->())
                != static_cast<QGlib::RefCountedObject*>(msg2.operator->()));
        QVERIFY(msg3 == msg2);
    }
}

void RefPointerTest::messageDynamicCastTest()
{
    QGst::BinPtr bin = QGst::Bin::create();
    QGst::MessagePtr msg = QGst::ApplicationMessage::create(bin);
    QVERIFY(!msg.isNull());
    QVERIFY(!msg.dynamicCast<QGst::ApplicationMessage>().isNull());
    QVERIFY(msg.dynamicCast<QGst::EosMessage>().isNull());
}

void RefPointerTest::equalityTest()
{
    QGst::BinPtr bin = QGst::Bin::create();
    QGst::ElementPtr element = bin;
    QVERIFY(element == bin);
    QVERIFY(bin == element);
    QVERIFY(bin == bin);

    GstElement *e = element;
    QVERIFY(e == element);
    QVERIFY(element == e);
    QVERIFY(bin == e);
    QVERIFY(e == bin);

    e++;
    QVERIFY(e != element);
    QVERIFY(element != e);
    QVERIFY(bin != e);
    QVERIFY(e != bin);

    e = NULL;
    QVERIFY(e != element);
    QVERIFY(element != e);
    QVERIFY(bin != e);
    QVERIFY(e != bin);

    element.clear();
    QVERIFY(element != bin);
    QVERIFY(bin != element);
    QVERIFY(e == element);
    QVERIFY(element == e);

    bin.clear();
    QVERIFY(element == bin);
    QVERIFY(bin == element);
    QVERIFY(bin == bin);
    QVERIFY(bin == e);
    QVERIFY(e == bin);
}

QTEST_APPLESS_MAIN(RefPointerTest)

#include "moc_qgsttest.cpp"
#include "refpointertest.moc"
<commit_msg>tests/auto/refpointertest.cpp gst_object_sink was removed.<commit_after>/*
    Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com>
    Copyright (C) 2010 Collabora Ltd.
      @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "qgsttest.h"
#include <QGst/Object>
#include <QGst/Message>
#include <QGst/Pipeline>
#include <QGst/ElementFactory>
#include <QGst/UriHandler>
#include <QGst/StreamVolume>

class RefPointerTest : public QGstTest
{
    Q_OBJECT
private Q_SLOTS:
    void refTest1();
    void refTest2();
    void dynamicCastTest();
    void dynamicCastDownObjectTest();
    void dynamicCastUpObjectTest();
    void dynamicCastObjectToIfaceTest();
    void dynamicCastIfaceToObjectTest();
    void cppWrappersTest();
    void messageDynamicCastTest();
    void equalityTest();
};

void RefPointerTest::refTest1()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL))));
    gst_object_sink(bin);
    QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin, false);
    QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1);
}

void RefPointerTest::refTest2()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL))));

    {
        QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin);
        QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 2);
        {
            QGst::ObjectPtr object2 = object;
            QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 3);
        }
    }
    QCOMPARE(GST_OBJECT_REFCOUNT_VALUE(bin), 1);
    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastTest()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(GST_OBJECT(gst_bin_new(NULL))));

    {
        QGst::ObjectPtr object = QGst::ObjectPtr::wrap(bin);
        QVERIFY(!object.dynamicCast<QGlib::Object>().isNull());
    }

    {
        QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin));
        QVERIFY(!object.dynamicCast<QGst::Object>().isNull());
    }

    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastDownObjectTest()
{
    GstObject *bin = GST_OBJECT(gst_object_ref(gst_bin_new(NULL)));

    {
        QGlib::ObjectPtr object = QGlib::ObjectPtr::wrap(G_OBJECT(bin));
        QVERIFY(!object.dynamicCast<QGst::Object>().isNull());
        QVERIFY(!object.dynamicCast<QGst::Bin>().isNull());
        QVERIFY(object.dynamicCast<QGst::Pipeline>().isNull());
    }

    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastUpObjectTest()
{
    GstBin *bin = GST_BIN(gst_object_ref(gst_bin_new(NULL)));

    {
        QGst::BinPtr object = QGst::BinPtr::wrap(bin);
        QVERIFY(!object.dynamicCast<QGst::Element>().isNull());
        QVERIFY(!object.dynamicCast<QGlib::Object>().isNull());
        QVERIFY(!object.dynamicCast<QGst::ChildProxy>().isNull());
    }

    gst_object_unref(bin);
}

void RefPointerTest::dynamicCastObjectToIfaceTest()
{
    QGst::ElementPtr e = QGst::ElementFactory::make("fakesrc");
    QGst::UriHandlerPtr u = e.dynamicCast<QGst::UriHandler>();
    QVERIFY(u.isNull());

    e = QGst::ElementFactory::make("filesrc");
    u = e.dynamicCast<QGst::UriHandler>();
    QVERIFY(!u.isNull());
}

void RefPointerTest::dynamicCastIfaceToObjectTest()
{
    GstElement *e = gst_element_factory_make("filesrc", NULL);
    gst_object_ref_sink(e);

    QGst::UriHandlerPtr u = QGst::UriHandlerPtr::wrap(GST_URI_HANDLER(e), false);
    QVERIFY(!u.isNull());
    QVERIFY(!u.dynamicCast<QGst::Element>().isNull());
}

void RefPointerTest::cppWrappersTest()
{
    QGst::ElementPtr e = QGst::ElementFactory::make("playbin2");
    QVERIFY(!e.isNull());

    {
        QGst::PipelinePtr pipeline = e.dynamicCast<QGst::Pipeline>();
        QVERIFY(!pipeline.isNull());
        //the C++ wrappers must be the same
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(pipeline.operator->()),
                 static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    {
        QGst::ChildProxyPtr proxy = e.dynamicCast<QGst::ChildProxy>();
        QVERIFY(!proxy.isNull());
        //the C++ wrappers must be the same
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(proxy.operator->()),
                 static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    { //new wrap() should give the same C++ instance
        GstElement *gobj = e;
        QGst::ElementPtr e2 = QGst::ElementPtr::wrap(gobj);
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(e2.operator->()),
                 static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    {
        QGst::StreamVolumePtr sv = e.dynamicCast<QGst::StreamVolume>();
        QVERIFY(!sv.isNull());
        //now the C++ wrapper must not be the same, since Pipeline does not inherit StreamVolume
        QVERIFY(static_cast<QGlib::RefCountedObject*>(sv.operator->())
                != static_cast<QGlib::RefCountedObject*>(e.operator->()));
    }

    {
        QGst::MessagePtr msg = QGst::ApplicationMessage::create(e);
        QGst::MessagePtr msg2 = msg;
        QCOMPARE(static_cast<QGlib::RefCountedObject*>(msg.operator->()),
                 static_cast<QGlib::RefCountedObject*>(msg2.operator->()));
        QVERIFY(msg2 == msg);

        QGst::MessagePtr msg3 = QGst::MessagePtr::wrap(msg2);
        QVERIFY(static_cast<QGlib::RefCountedObject*>(msg3.operator->())
                != static_cast<QGlib::RefCountedObject*>(msg2.operator->()));
        QVERIFY(msg3 == msg2);
    }
}

void RefPointerTest::messageDynamicCastTest()
{
    QGst::BinPtr bin = QGst::Bin::create();
    QGst::MessagePtr msg = QGst::ApplicationMessage::create(bin);
    QVERIFY(!msg.isNull());
    QVERIFY(!msg.dynamicCast<QGst::ApplicationMessage>().isNull());
    QVERIFY(msg.dynamicCast<QGst::EosMessage>().isNull());
}

void RefPointerTest::equalityTest()
{
    QGst::BinPtr bin = QGst::Bin::create();
    QGst::ElementPtr element = bin;
    QVERIFY(element == bin);
    QVERIFY(bin == element);
    QVERIFY(bin == bin);

    GstElement *e = element;
    QVERIFY(e == element);
    QVERIFY(element == e);
    QVERIFY(bin == e);
    QVERIFY(e == bin);

    e++;
    QVERIFY(e != element);
    QVERIFY(element != e);
    QVERIFY(bin != e);
    QVERIFY(e != bin);

    e = NULL;
    QVERIFY(e != element);
    QVERIFY(element != e);
    QVERIFY(bin != e);
    QVERIFY(e != bin);

    element.clear();
    QVERIFY(element != bin);
    QVERIFY(bin != element);
    QVERIFY(e == element);
    QVERIFY(element == e);

    bin.clear();
    QVERIFY(element == bin);
    QVERIFY(bin == element);
    QVERIFY(bin == bin);
    QVERIFY(bin == e);
    QVERIFY(e == bin);
}

QTEST_APPLESS_MAIN(RefPointerTest)

#include "moc_qgsttest.cpp"
#include "refpointertest.moc"
<|endoftext|>


<commit_before>#include "core/connection.hpp"

// boost
#include <boost/test/unit_test.hpp>

/**
 * Example test cases for core connections.
 * These this test shows how connections are used in general.
 * Tests for special cases are below.
 */
BOOST_AUTO_TEST_CASE(examples)
{
	//test trivial connection of two objects
	auto increment = [](int i) -> int {return i+1;}; //just adds 1 to parameter
	auto give_one = [](void) ->int {return 1;}; //simply return 1, no parameter

	// this connection has no parameter and returns and int.
	auto one_plus_one = connect(give_one, increment);
	BOOST_CHECK(one_plus_one() == 2);

	//test chained connection,
	//take connection from above and add a new connectable as a sink.
	auto two_plus_one = connect(one_plus_one, increment);
	BOOST_CHECK(two_plus_one() == 3);

	//connections can have both, parameters and return values:
	{
		// connection of two anonymous nodes, takes and returns an int.
		auto plus_two = connect
			(
				[](int i) ->int {return i+1;},
				[](int i) ->int {return i+1;}
			);
		BOOST_CHECK(plus_two(1) == 3);
	}
	//this is completely equivalent to:
	{
		auto plus_two = connect(increment, increment);
		BOOST_CHECK(plus_two(1) == 3);
	}
}

// test cases for different pairs of parameter and result types
BOOST_AUTO_TEST_CASE(parameter_result_pairs)
{
	// this variable is captures by lambdas
	// to check if lambdas without return values work.
	int capture_ref = 0;

	auto write_param = [&](int i){ capture_ref = i; };
	auto increment = [](int i) -> int {return i+1;};

	// this connection takes a parameter and returns void
	// An int is transmitted as payload between source and sink.
	auto write_increment = connect(increment, write_param);
	write_increment(0);
	BOOST_CHECK(capture_ref == 1);

	auto do_nothing = [](){};
	auto set_two = [&](){ capture_ref = 2; };
	// This connection takes no parameter, and returns void
	// There is also no payload between source and sink.
	auto set_one_connection = connect(do_nothing, set_two);
	set_one_connection();
	BOOST_CHECK(capture_ref == 2);

	// This connection takes no paramter and returns and int.
	// An int is transmitted as payload between source and sink.
	auto give_one = [](){return 1;};
	BOOST_CHECK(connect(give_one, increment)() == 2);

	// This connection takes no paramter and returns and int.
	// There is also no payload between source and sink.
	BOOST_CHECK(connect(do_nothing, give_one)() == 1);

	// This connection takes no paramter and returns and void.
	// There is also no payload between source and sink.
	auto write_nine = [&](){ capture_ref = 9; };
	connect(do_nothing, write_nine)();
	BOOST_CHECK(capture_ref == 9);

}
<commit_msg>added last tests for connection<commit_after>#include "core/connection.hpp"

// boost
#include <boost/test/unit_test.hpp>

/**
 * Example test cases for core connections.
 * These this test shows how connections are used in general.
 * Tests for special cases are below.
 */
BOOST_AUTO_TEST_CASE(examples)
{
	//test trivial connection of two objects
	auto increment = [](int i) -> int {return i+1;}; //just adds 1 to parameter
	auto give_one = [](void) ->int {return 1;}; //simply return 1, no parameter

	// this connection has no parameter and returns and int.
	auto one_plus_one = connect(give_one, increment);
	BOOST_CHECK(one_plus_one() == 2);

	//test chained connection,
	//take connection from above and add a new connectable as a sink.
	auto two_plus_one = connect(one_plus_one, increment);
	BOOST_CHECK(two_plus_one() == 3);

	//connections can have both, parameters and return values:
	{
		// connection of two anonymous nodes, takes and returns an int.
		auto plus_two = connect
			(
				[](int i) ->int {return i+1;},
				[](int i) ->int {return i+1;}
			);
		BOOST_CHECK(plus_two(1) == 3);
	}
	//this is completely equivalent to:
	{
		auto plus_two = connect(increment, increment);
		BOOST_CHECK(plus_two(1) == 3);
	}
}

// test cases for different pairs of parameter and result types
BOOST_AUTO_TEST_CASE(parameter_result_pairs)
{
	// this variable is captures by lambdas
	// to check if lambdas without return values work.
	int capture_ref = 0;

	//named differnt sources and sinks to make tests more readable
	auto write_param = [&](int i){ capture_ref = i; };
	auto increment = [](int i) -> int {return i+1;};
	auto give_one = [](){return 1;};
	auto give_three = [](){return 3;};
	auto do_nothing = [](){};
	auto ignore_in = [](int i){};
	auto increment_ref = [&](){ capture_ref++; };

	// param int,  payload int,  result int
	auto plus_two = connect(increment, increment);
	BOOST_CHECK_EQUAL(plus_two(1), 3);

	// param int,  payload int,  result void
	// this connection takes a parameter and returns void
	// An int is transmitted as payload between source and sink.
	auto write_increment = connect(increment, write_param);
	write_increment(0);
	BOOST_CHECK_EQUAL(capture_ref,1);

	// param int,  payload void, result int
	auto ignore_input_return1 = connect(ignore_in, give_one);
	BOOST_CHECK_EQUAL(ignore_input_return1(99), 1);

	// param int,  payload void, result void
	connect(ignore_in, increment_ref)(99);
	BOOST_CHECK_EQUAL(capture_ref, 2);

	// param void, payload int,  result int
	// This connection takes no paramter and returns an int.
	// An int is transmitted as payload between source and sink.
	BOOST_CHECK_EQUAL(connect(give_one, increment)(), 2);

	// param void, payload int,  result void
	connect(give_three, write_param)();
	BOOST_CHECK_EQUAL(capture_ref, 3);

	// param void, payload void, result int
	// This connection takes no paramter and returns and int.
	// There is also no payload between source and sink.
	BOOST_CHECK_EQUAL(connect(do_nothing, give_one)(),1);

	// param void, payload void, result void
	// This connection takes no parameter, and returns void
	// There is also no payload between source and sink.
	connect(do_nothing, increment_ref)();
	BOOST_CHECK_EQUAL(capture_ref, 4);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cassert>
#include <random>
#include <tuple>
#include <map>
#include <vector>
#include <algorithm>
#include <memory>

#include <google/profiler.h>

#include <boost/timer.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <apr_mmap.h>
#include <apr_general.h>

#include "akumuli.h"
#include "page.h"
#include "storage.h"
#include "sequencer.h"

using namespace Akumuli;
using namespace std;

const int NUM_ITERATIONS = 100*1000*1000;

int main(int cnt, const char** args)
{
    aku_initialize(nullptr);
    {
        std::cout << "Sequencer perf-test, ordered timestamps" << std::endl;
        // Patience sort perf-test
        boost::timer timer;
        size_t ix_merged = 0;
        Sequencer seq(nullptr, {0, 10000, 0});
        for (int ix = 0u; ix < NUM_ITERATIONS; ix++) {
            TimeSeriesValue value({(uint64_t)ix}, ix & 0xFF, (aku_EntryOffset)ix, 8);
            int status = 0;
            int lock = 0;
            tie(status, lock) = seq.add(value);
            if (lock % 2 == 1) {
                CursorResult results[0x10000];
                BufferedCursor cursor(results, 0x10000);
                Caller caller;
                seq.merge(caller, &cursor);
                for (size_t i = 0; i < cursor.count; i++) {
                    if (cursor.results_buffer[i].data_offset != ix_merged) {
                        // report error
                        std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl;
                        return -1;
                    }
                    ix_merged++;
                }
            }
            if (ix % 1000000 == 0) {
                std::cout << ix << " " << timer.elapsed() << "s" << std::endl;
                timer.restart();
            }
        }
    }
    {
        std::cout << "Sequencer perf-test, unordered timestamps" << std::endl;
        // Patience sort perf-test
        boost::timer timer;
        size_t ix_merged = 0;
        const int buffer_size = 10000;
        int buffer[buffer_size];
        int buffer_ix = buffer_size;
        Sequencer seq(nullptr, {10000});
        for (int ix = 0u; ix < NUM_ITERATIONS; ix++) {
            buffer_ix--;
            buffer[buffer_ix] = ix;
            if (buffer_ix == 0) {
                buffer_ix = buffer_size;
                for(auto ixx: buffer) {
                    TimeSeriesValue value({(uint64_t)ixx}, ixx & 0xFF, (aku_EntryOffset)ixx, 8);
                    int status = 0;
                    int lock = 0;
                    tie(status, lock) = seq.add(value);
                    if (lock % 2 == 1) {
                        CursorResult results[0x10000];
                        BufferedCursor cursor(results, 0x10000);
                        Caller caller;
                        seq.merge(caller, &cursor);
                        for (size_t i = 0; i < cursor.count; i++) {
                            if (cursor.results_buffer[i].data_offset != ix_merged) {
                                // report error
                                std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl;
                                return -1;
                            }
                            ix_merged++;
                        }
                    }
                }
            }
            if (ix % 1000000 == 0) {
                std::cout << ix << " " << timer.elapsed() << "s" << std::endl;
                timer.restart();
            }
        }
    }
    return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <cassert>
#include <random>
#include <tuple>
#include <map>
#include <vector>
#include <algorithm>
#include <memory>

#include <boost/timer.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <apr_mmap.h>
#include <apr_general.h>

#include "akumuli.h"
#include "page.h"
#include "storage.h"
#include "sequencer.h"

using namespace Akumuli;
using namespace std;

const int NUM_ITERATIONS = 100*1000*1000;

int main(int cnt, const char** args)
{
    aku_initialize(nullptr);
    {
        std::cout << "Sequencer perf-test, ordered timestamps" << std::endl;
        // Patience sort perf-test
        boost::timer timer;
        size_t ix_merged = 0;
        Sequencer seq(nullptr, {0, 10000, 0});
        for (int ix = 0u; ix < NUM_ITERATIONS; ix++) {
            TimeSeriesValue value({(uint64_t)ix}, ix & 0xFF, (aku_EntryOffset)ix, 8);
            int status = 0;
            int lock = 0;
            tie(status, lock) = seq.add(value);
            if (lock % 2 == 1) {
                CursorResult results[0x10000];
                BufferedCursor cursor(results, 0x10000);
                Caller caller;
                seq.merge(caller, &cursor);
                for (size_t i = 0; i < cursor.count; i++) {
                    if (cursor.results_buffer[i].data_offset != ix_merged) {
                        // report error
                        std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl;
                        return -1;
                    }
                    ix_merged++;
                }
            }
            if (ix % 1000000 == 0) {
                std::cout << ix << " " << timer.elapsed() << "s" << std::endl;
                timer.restart();
            }
        }
    }
    {
        std::cout << "Sequencer perf-test, unordered timestamps" << std::endl;
        // Patience sort perf-test
        boost::timer timer;
        size_t ix_merged = 0;
        const int buffer_size = 10000;
        int buffer[buffer_size];
        int buffer_ix = buffer_size;
        Sequencer seq(nullptr, {10000});
        for (int ix = 0u; ix < NUM_ITERATIONS; ix++) {
            buffer_ix--;
            buffer[buffer_ix] = ix;
            if (buffer_ix == 0) {
                buffer_ix = buffer_size;
                for(auto ixx: buffer) {
                    TimeSeriesValue value({(uint64_t)ixx}, ixx & 0xFF, (aku_EntryOffset)ixx, 8);
                    int status = 0;
                    int lock = 0;
                    tie(status, lock) = seq.add(value);
                    if (lock % 2 == 1) {
                        CursorResult results[0x10000];
                        BufferedCursor cursor(results, 0x10000);
                        Caller caller;
                        seq.merge(caller, &cursor);
                        for (size_t i = 0; i < cursor.count; i++) {
                            if (cursor.results_buffer[i].data_offset != ix_merged) {
                                // report error
                                std::cout << "Error at: " << i << " " << cursor.results_buffer[i].data_offset << " != " << ix_merged << std::endl;
                                return -1;
                            }
                            ix_merged++;
                        }
                    }
                }
            }
            if (ix % 1000000 == 0) {
                std::cout << ix << " " << timer.elapsed() << "s" << std::endl;
                timer.restart();
            }
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <libcryptosec/ECDSAKeyPair.h>
#include <libcryptosec/ec/Curve.h>
#include <libcryptosec/ec/BrainpoolCurveFactory.h>
#include <fstream>
#include "gtest.h"
#include <stdio.h>

class BrainpoolEcTest : public ::testing::Test {

protected:
	virtual void SetUp() {
	}

	void testHardcodedCurve(BrainpoolCurveFactory::CurveName curveName){
		const Curve * curve = BrainpoolCurveFactory::getCurve(curveName);
			ECDSAKeyPair keypair (*curve);
			std::string pem = keypair.getPemEncoded();
			EXPECT_TRUE(pem.size() > 0);
			//TODO melhorar testes da chave fazendo assinatura
	}

	void testKeyPairFromFile(fstream &file){
		if(file.is_open()){
				/* Read file into ByteArray*/
				file.seekg (0, file.end);
				int length = file.tellg();
				file.seekg (0, file.beg);
				unsigned char * memblock = new unsigned char [length];
				file.read ((char*)memblock, length);
				file.close();
				ByteArray b(memblock, length);
				delete[] memblock;

				/*Do crypto*/
				ECDSAKeyPair keypair(b);
				std::string pem = keypair.getPemEncoded();
				EXPECT_TRUE(pem.size() > 0);
				//TODO melhorar testes da chave fazendo assinatura
			}
			else
			{
				FAIL();
			}
	}

};

TEST_F(BrainpoolEcTest, HardcodedBpTestBP160r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP160r1);

}

//TEST_F(BrainpoolEcTest, HardcodedBpTestBP160t1){
//
//	testHardcodedCurve(BrainpoolCurveFactory::BP160t1);
//
//}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP192r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP192r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP192t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP192t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP224r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP224r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP224t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP224t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP256r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP256r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP256t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP256t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP320r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP320r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP320t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP320t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP384r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP384r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP384t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP384t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP512r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP512r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP512t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP512t1);

}

TEST_F(BrainpoolEcTest, DerFormatedTestBp160r1){
	std::fstream file("files/BP160r1", ios::in|ios::binary|ios::ate);
	testKeyPairFromFile(file);
}

TEST_F(BrainpoolEcTest, DerFormatedTestBp512r1){
	std::fstream file("files/BP512r1", ios::in|ios::binary|ios::ate);
	testKeyPairFromFile(file);
}
<commit_msg>Remocao do comentario no teste P160t1<commit_after>#include <libcryptosec/ECDSAKeyPair.h>
#include <libcryptosec/ec/Curve.h>
#include <libcryptosec/ec/BrainpoolCurveFactory.h>
#include <fstream>
#include "gtest.h"
#include <stdio.h>

class BrainpoolEcTest : public ::testing::Test {

protected:
	virtual void SetUp() {
	}

	void testHardcodedCurve(BrainpoolCurveFactory::CurveName curveName){
		const Curve * curve = BrainpoolCurveFactory::getCurve(curveName);
			ECDSAKeyPair keypair (*curve);
			std::string pem = keypair.getPemEncoded();
			EXPECT_TRUE(pem.size() > 0);
			//TODO melhorar testes da chave fazendo assinatura
	}

	void testKeyPairFromFile(fstream &file){
		if(file.is_open()){
				/* Read file into ByteArray*/
				file.seekg (0, file.end);
				int length = file.tellg();
				file.seekg (0, file.beg);
				unsigned char * memblock = new unsigned char [length];
				file.read ((char*)memblock, length);
				file.close();
				ByteArray b(memblock, length);
				delete[] memblock;

				/*Do crypto*/
				ECDSAKeyPair keypair(b);
				std::string pem = keypair.getPemEncoded();
				EXPECT_TRUE(pem.size() > 0);
				//TODO melhorar testes da chave fazendo assinatura
			}
			else
			{
				FAIL();
			}
	}

};

TEST_F(BrainpoolEcTest, HardcodedBpTestBP160r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP160r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP160t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP160t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP192r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP192r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP192t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP192t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP224r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP224r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP224t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP224t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP256r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP256r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP256t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP256t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP320r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP320r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP320t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP320t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP384r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP384r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP384t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP384t1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP512r1){

	testHardcodedCurve(BrainpoolCurveFactory::BP512r1);

}

TEST_F(BrainpoolEcTest, HardcodedBpTestBP512t1){

	testHardcodedCurve(BrainpoolCurveFactory::BP512t1);

}

TEST_F(BrainpoolEcTest, DerFormatedTestBp160r1){
	std::fstream file("files/BP160r1", ios::in|ios::binary|ios::ate);
	testKeyPairFromFile(file);
}

TEST_F(BrainpoolEcTest, DerFormatedTestBp512r1){
	std::fstream file("files/BP512r1", ios::in|ios::binary|ios::ate);
	testKeyPairFromFile(file);
}
<|endoftext|>


<commit_before>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.

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

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

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

/* HIT_START
 * BUILD: %t %s test_common.cpp NVCC_OPTIONS -std=c++11
 * RUN: %t
 * HIT_END
 */

#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string>

using namespace std;

//./hipEnvVar -c -d 0 -h
  //putenv("SomeVariable=SomeValue");
 //putenv("export HIP_VISIBLE_DEVICES=0,1,2,3");

int getDeviceNumber(){
   FILE *in;
   char buff[512];
   string str;
   if(!(in = popen("./hipEnvVar -c", "r"))){
        return 1;
    }
    fgets(buff, sizeof(buff), in);
    pclose(in);
    return atoi(buff);
}

int getDevicePCIBusNum(int deviceID){
    FILE *in;
    char buff[512];
    string str = "./hipEnvVar -d ";
    str += std::to_string(deviceID);
    if(!(in = popen(str.c_str(), "r"))){
        return 1;
    }
    fgets(buff, sizeof(buff), in);
    pclose(in);
    return atoi(buff);
}

int main() {
    unsetenv("HIP_VISIBLE_DEVICES");
    unsetenv("CUDA_VISIBLE_DEVICES");
    //collect the device pci bus ID for all devices
    int totalDeviceNum = getDeviceNumber();
    std::cout << "The total number of available devices is " << totalDeviceNum<< std::endl
        <<"Valid index range is 0 - "<<totalDeviceNum-1<<std::endl;
    std::vector<int> devPCINum;
    for (int i = 0; i < totalDeviceNum ; i++) {
        devPCINum.push_back(getDevicePCIBusNum(i));
        std::cout <<"The collected device PCI Bus ID of Device "<<i<<" is "
            << getDevicePCIBusNum(i) << std::endl;
    }

    //select each of the available devices to be the target device,
    //query the returned device pci bus number, check if match the database
    for (int i = 0; i < totalDeviceNum ; i++) {
        setenv("HIP_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1);
        setenv("CUDA_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1);
        //cout<<"HIP_VISIBLE_DEVICES is "<<i<<" data in vector is "<<devPCINum[i]<<endl;
        //std::cout <<"Returned pci number is"<< getDevicePCIBusNum(0) << std::endl;
        if (devPCINum[i] != getDevicePCIBusNum(0)) {
            std::cout << "The returned PciBusID is not correct"
                << std::endl;
            exit(-1);
        } else {
            continue;
        }
    }

    //check when set an invalid device number
    setenv("HIP_VISIBLE_DEVICES","1000,0,1",1);
    setenv("CUDA_VISIBLE_DEVICES","1000,0,1",1);
    assert(getDeviceNumber() == 0);

    if(totalDeviceNum > 2){
        setenv("HIP_VISIBLE_DEVICES","0,1,1000,2",1);
        setenv("CUDA_VISIBLE_DEVICES","0,1,1000,2",1);
        assert(getDeviceNumber() == 2);

        setenv("HIP_VISIBLE_DEVICES","0,1,2",1);
        setenv("CUDA_VISIBLE_DEVICES","0,1,2",1);
        assert(getDeviceNumber() == 3);
        // test if CUDA_VISIBLE_DEVICES will be accepted by the runtime
        unsetenv("HIP_VISIBLE_DEVICES");
        unsetenv("CUDA_VISIBLE_DEVICES");
        setenv("CUDA_VISIBLE_DEVICES","0,1,2",1);
        assert(getDeviceNumber() == 3);
    }

    setenv("HIP_VISIBLE_DEVICES","-100,0,1",1);
    setenv("CUDA_VISIBLE_DEVICES","-100,0,1",1);
    assert(getDeviceNumber() == 0);

    std::cout << "PASSED" << std::endl;
    return 0;
}
<commit_msg>change hipEnvVarDriver to reduce communications to hipEnvVar<commit_after>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.

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

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

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

/* HIT_START
 * BUILD: %t %s test_common.cpp NVCC_OPTIONS -std=c++11
 * RUN: %t
 * HIT_END
 */

#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string>
#include <hip_runtime.h>
using namespace std;

int getDeviceNumber(){
   FILE *in;
   char buff[512];
   string str;
   if(!(in = popen("./hipEnvVar -c", "r"))){
        return 1;
    }
    fgets(buff, sizeof(buff), in);
    pclose(in);
    return atoi(buff);
}

// Query the current device ID remotely to hipEnvVar
int getDevicePCIBusNumRemote(int deviceID){
    FILE *in;
    char buff[512];
    string str = "./hipEnvVar -d ";
    str += std::to_string(deviceID);
    if(!(in = popen(str.c_str(), "r"))){
        return 1;
    }
    fgets(buff, sizeof(buff), in);
    pclose(in);
    return atoi(buff);
}

// Query the current device ID locally
int getDevicePCIBusNum(int deviceID){
    hipSetDevice(deviceID);
    hipDeviceProp_t devProp;

    hipGetDeviceProperties(&devProp, deviceID);
    if (devProp.major < 1) {
        printf("%d does not support HIP\n", deviceID);
        return -1;
    }
    return devProp.pciBusID;
}

int main() {
    unsetenv("HIP_VISIBLE_DEVICES");
    unsetenv("CUDA_VISIBLE_DEVICES");
    //collect the device pci bus ID for all devices
    int totalDeviceNum = getDeviceNumber();
    std::cout << "The total number of available devices is " << totalDeviceNum<< std::endl
        <<"Valid index range is 0 - "<<totalDeviceNum-1<<std::endl;
    std::vector<int> devPCINum;
    for (int i = 0; i < totalDeviceNum ; i++) {
        devPCINum.push_back(getDevicePCIBusNum(i));
        std::cout <<"The collected device PCI Bus ID of Device "<<i<<" is "
            << getDevicePCIBusNum(i) << std::endl;
    }

    //select each of the available devices to be the target device,
    //query the returned device pci bus number, check if match the database
    for (int i = 0; i < totalDeviceNum ; i++) {
        setenv("HIP_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1);
        setenv("CUDA_VISIBLE_DEVICES",(char*)std::to_string(i).c_str(),1);
        if (devPCINum[i] != getDevicePCIBusNumRemote(0)) {
            std::cout << "The returned PciBusID is not correct"<< std::endl;
            std::cout << "Expected "<< devPCINum[i] << ", but get " << getDevicePCIBusNum << endl;
            exit(-1);
        } else {
            continue;
        }
    }

    //check when set an invalid device number
    setenv("HIP_VISIBLE_DEVICES","1000,0,1",1);
    setenv("CUDA_VISIBLE_DEVICES","1000,0,1",1);
    assert(getDeviceNumber() == 0);

    if(totalDeviceNum > 2){
        setenv("HIP_VISIBLE_DEVICES","0,1,1000,2",1);
        setenv("CUDA_VISIBLE_DEVICES","0,1,1000,2",1);
        assert(getDeviceNumber() == 2);

        setenv("HIP_VISIBLE_DEVICES","0,1,2",1);
        setenv("CUDA_VISIBLE_DEVICES","0,1,2",1);
        assert(getDeviceNumber() == 3);
        // test if CUDA_VISIBLE_DEVICES will be accepted by the runtime
        unsetenv("HIP_VISIBLE_DEVICES");
        unsetenv("CUDA_VISIBLE_DEVICES");
        setenv("CUDA_VISIBLE_DEVICES","0,1,2",1);
        assert(getDeviceNumber() == 3);
    }

    setenv("HIP_VISIBLE_DEVICES","-100,0,1",1);
    setenv("CUDA_VISIBLE_DEVICES","-100,0,1",1);
    assert(getDeviceNumber() == 0);

    std::cout << "PASSED" << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include "main.h"

//just an example

int main()
{
	ustring addre;
	addre.fromString(string("BM-2cUwUoj9YKoxsZMKT7C5N46tC1KTdUQZpH")); //just a test address
	PubAddr address;
	bool loaded = address.loadAddr(addre);

	BitMRC bitmrc;

	bitmrc.start();

	if(loaded)
		bitmrc.getPubKey(address);

	while (1)
	{
		printf("Select a command: ");
		char command[256];
		scanf("%s", command);
		if (!strcmp("quit", command))
			break;
		else if (!strcmp("send", command))
		{
			if (bitmrc.PrivAddresses.size() == 0)
			{
				printf("No private address\n");
				continue;
			}

			if (bitmrc.PubAddresses.size() == 0)
			{
				printf("No public address\n");
				continue;
			}
			for (int i = 0; i < bitmrc.PubAddresses.size(); i++)
			{
				printf("[%d] Public key: %s Ready: %s\n", i, bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True");
			}
			printf("Select destination address: ");
			int des;
			scanf("%d", &des);
			if (des < 0 || des >= bitmrc.PubAddresses.size())
			{
				printf("Incorrect selection\n");
				continue;
			}
			for (int i = 0; i < bitmrc.PrivAddresses.size(); i++)
			{
				printf("[%d] Private key: %s\n", i, bitmrc.PrivAddresses[i].getAddress().c_str());
			}
			printf("Select from address: ");
			int fro;
			scanf("%d", &fro);
			if (fro < 0 || fro >= bitmrc.PubAddresses.size())
			{
				printf("Incorrect selection\n");
				continue;
			}

			ustring msg;
			printf("Message to send:\n");
			scanf("%s", command);
			msg.fromString(command);
			bitmrc.sendMessage(msg, bitmrc.PubAddresses[des], bitmrc.PrivAddresses[fro]); //maybe this should be done in another thread
			printf("Message sent\n");
		}
		else if (!strcmp("address", command))
		{
			scanf("%s", command);
			if (!strcmp("generate", command))
			{
				scanf("%s", command);
				if (!strcmp("deterministic", command))
				{
					scanf("%s", command);
					ustring pass;
					pass.fromString(command);
					bitmrc.generateDeterministicAddr(pass, 1); //cant print it because this function wont show the results
				}
				else if (!strcmp("random", command))
				{
					Addr privateAddr;
					privateAddr.generateRandom();

					bitmrc.saveAddr(privateAddr);
					printf("Generated %s\n", privateAddr.getAddress().c_str());
				}
			}
			else if (!strcmp("public", command))
			{
				scanf("%s", command);
				ustring addre;
				addre.fromString(string(command));
				PubAddr address;
				bool loaded = address.loadAddr(addre);
				if (loaded)
				{
					printf("Asking public key!\n");
					bitmrc.getPubKey(address);
					printf("Asked! check publickey for news on that address!\n");
				}
				else
					printf("Address not correct!\n");
			}
		}
		else if (!strcmp("check", command))
		{
			scanf("%s", command);
			if (!strcmp("message", command))
			{
				//this should be done asynchronous because this will stuck this thread if no message is incoming
				BitMRC::message mess = bitmrc.new_messages.pop();
				printf("New message:\nFrom: %s\nTo: %s\nMessage:\n%s\n", mess.from.c_str(), mess.to.c_str(), mess.info.c_str());
			}
			else if (!strcmp("connections", command))
			{
				std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_nodes);

				for (int i = 0; i < bitmrc.Nodes.size(); i++)
				{
					if (bitmrc.Nodes[i]->state == 2)
					{
						printf("Node: %s:%s Connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str());
					}
					else if (bitmrc.Nodes[i]->state == 0)
					{
						printf("Node: %s:%s Not connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str());
					}
				}

				mlock.unlock();
			}
			else if (!strcmp("privatekey", command))
			{
				std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_priv);

				if (bitmrc.PrivAddresses.size() == 0)
					printf("No private key\n");

				for (int i = 0; i < bitmrc.PrivAddresses.size(); i++)
				{
					printf("Private key: %s\n", bitmrc.PrivAddresses[i].getAddress().c_str());
				}

				mlock.unlock();
			}
			else if (!strcmp("publickey", command))
			{
				std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_pub);

				if (bitmrc.PubAddresses.size() == 0)
					printf("No public key\n");

				for (int i = 0; i < bitmrc.PubAddresses.size(); i++)
				{
					printf("Public key: %s Ready: %s\n", bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True");
				}

				mlock.unlock();
			}
		}
		printf("\n");
	}
	return 0;
}<commit_msg>changed main.cpp<commit_after>#include "main.h"

//just an example

int main()
{
	ustring addre;
	addre.fromString(string("BM-2cUwUoj9YKoxsZMKT7C5N46tC1KTdUQZpH")); //just a test address
	PubAddr address;
	bool loaded = address.loadAddr(addre);

	BitMRC bitmrc;

	bitmrc.start();

	if(loaded)
		bitmrc.getPubKey(address);

	while (1)
	{
		printf("Select a command (help): ");
		char command[256];
		scanf("%s", command);
		if (!strcmp("quit", command))
			break;
		else if (!strcmp("send", command))
		{
			if (bitmrc.PrivAddresses.size() == 0)
			{
				printf("No private address\n");
				continue;
			}

			if (bitmrc.PubAddresses.size() == 0)
			{
				printf("No public address\n");
				continue;
			}
			for (int i = 0; i < bitmrc.PubAddresses.size(); i++)
			{
				printf("[%d] Public key: %s Ready: %s\n", i, bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True");
			}
			printf("Select destination address: ");
			int des;
			scanf("%d", &des);
			if (des < 0 || des >= bitmrc.PubAddresses.size())
			{
				printf("Incorrect selection\n");
				continue;
			}
			for (int i = 0; i < bitmrc.PrivAddresses.size(); i++)
			{
				printf("[%d] Private key: %s\n", i, bitmrc.PrivAddresses[i].getAddress().c_str());
			}
			printf("Select from address: ");
			int fro;
			scanf("%d", &fro);
			if (fro < 0 || fro >= bitmrc.PubAddresses.size())
			{
				printf("Incorrect selection\n");
				continue;
			}

			ustring msg;
			printf("Message to send:\n");
			scanf("%s", command);
			msg.fromString(command);
			bitmrc.sendMessage(msg, bitmrc.PubAddresses[des], bitmrc.PrivAddresses[fro]); //maybe this should be done in another thread
			printf("Message sent\n");
		}
		else if (!strcmp("address", command))
		{
			scanf("%s", command);
			if (!strcmp("generate", command))
			{
				scanf("%s", command);
				if (!strcmp("deterministic", command))
				{
					printf("Passphrase: ");
					scanf("%s", command);
					ustring pass;
					pass.fromString(command);
					bitmrc.generateDeterministicAddr(pass, 1); //cant print it because this function wont show the results
				}
				else if (!strcmp("random", command))
				{
					Addr privateAddr;
					privateAddr.generateRandom();

					bitmrc.saveAddr(privateAddr);
					printf("Generated %s\n", privateAddr.getAddress().c_str());
				}
			}
			else if (!strcmp("public", command))
			{
				printf("Insert a public address: ");
				scanf("%s", command);
				ustring addre;
				addre.fromString(string(command));
				PubAddr address;
				bool loaded = address.loadAddr(addre);
				if (loaded)
				{
					printf("Asking public key!\n");
					bitmrc.getPubKey(address);
					printf("Asked! check publickey for news on that address!\n");
				}
				else
					printf("Address not correct!\n");
			}
		}
		else if (!strcmp("check", command))
		{
			scanf("%s", command);
			if (!strcmp("message", command))
			{
				//this should be done asynchronous because this will stuck this thread if no message is incoming
				BitMRC::message mess = bitmrc.new_messages.pop();
				printf("New message:\nFrom: %s\nTo: %s\nMessage:\n%s\n", mess.from.c_str(), mess.to.c_str(), mess.info.c_str());
			}
			else if (!strcmp("connections", command))
			{
				std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_nodes);

				for (int i = 0; i < bitmrc.Nodes.size(); i++)
				{
					if (bitmrc.Nodes[i]->state == 2)
					{
						printf("Node: %s:%s Connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str());
					}
					else if (bitmrc.Nodes[i]->state == 0)
					{
						printf("Node: %s:%s Not connected\n", bitmrc.Nodes[i]->Ip.c_str(), bitmrc.Nodes[i]->Port.c_str());
					}
				}

				mlock.unlock();
			}
			else if (!strcmp("privatekey", command))
			{
				std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_priv);

				if (bitmrc.PrivAddresses.size() == 0)
					printf("No private key\n");

				for (int i = 0; i < bitmrc.PrivAddresses.size(); i++)
				{
					printf("Private key: %s\n", bitmrc.PrivAddresses[i].getAddress().c_str());
				}

				mlock.unlock();
			}
			else if (!strcmp("publickey", command))
			{
				std::shared_lock<std::shared_timed_mutex> mlock(bitmrc.mutex_pub);

				if (bitmrc.PubAddresses.size() == 0)
					printf("No public key\n");

				for (int i = 0; i < bitmrc.PubAddresses.size(); i++)
				{
					printf("Public key: %s Ready: %s\n", bitmrc.PubAddresses[i].getAddress().c_str(), bitmrc.PubAddresses[i].waitingPubKey() ? "False" : "True");
				}

				mlock.unlock();
			}
		}
		else if (!strcmp("help", command))
		{
			printf("send:                              send a message\n");
			printf("address generate random:           generate a random address\n");
			printf("address generate deterministic:    generate a deterministic address\n");
			printf("address public:                    add public key\n");
			printf("check message:                     wait until a message is in the inbox and display it\n");
			printf("check connections:                 display information about connection nodes\n");
			printf("check privatekey:                  display all the private addresses\n");
			printf("check publickey:                   display all the public addresses\n");
		}
		printf("\n");
	}
	return 0;
}<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#define CATCH_CONFIG_RUNNER
#include "mfem.hpp"
#include "catch.hpp"

mfem::MPI_Session *GlobalMPISession;

int main(int argc, char *argv[])
{
   // There must be exactly one instance.
   Catch::Session session;

   // Apply provided command line arguments.
   int r = session.applyCommandLine(argc, argv);
   if (r != 0)
   {
      return r;
   }

#ifdef MFEM_USE_MPI
   mfem::MPI_Session mpi;
   GlobalMPISession = &mpi;

   // Force tests not tagged as [Parallel] to run only on MPI rank 0
   if (mpi.WorldRank() > 0)
   {
      auto cfg = session.configData();
      cfg.testsOrTags.push_back("[Parallel]");
      session.useConfigData(cfg);
   }
   if (mpi.WorldSize() > 1 && mpi.Root())
   {
      mfem::out
            << "WARNING: Only running the [Parallel] label on MPI ranks > 1."
            << std::endl;
   }
#endif

   int result = session.run();

   return result;
}
<commit_msg>guard GlobalMPISession<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#define CATCH_CONFIG_RUNNER
#include "mfem.hpp"
#include "catch.hpp"

#ifdef MFEM_USE_MPI
mfem::MPI_Session *GlobalMPISession;
#endif

int main(int argc, char *argv[])
{
   // There must be exactly one instance.
   Catch::Session session;

   // Apply provided command line arguments.
   int r = session.applyCommandLine(argc, argv);
   if (r != 0)
   {
      return r;
   }

#ifdef MFEM_USE_MPI
   mfem::MPI_Session mpi;
   GlobalMPISession = &mpi;

   // Force tests not tagged as [Parallel] to run only on MPI rank 0
   if (mpi.WorldRank() > 0)
   {
      auto cfg = session.configData();
      cfg.testsOrTags.push_back("[Parallel]");
      session.useConfigData(cfg);
   }
   if (mpi.WorldSize() > 1 && mpi.Root())
   {
      mfem::out
            << "WARNING: Only running the [Parallel] label on MPI ranks > 1."
            << std::endl;
   }
#endif

   int result = session.run();

   return result;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * thrill/common/fast_string.hpp
 *
 * (Hopefully) fast static-length string implementation.
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef THRILL_COMMON_FAST_STRING_HEADER
#define THRILL_COMMON_FAST_STRING_HEADER

#include <cstdlib>
#include <cstring>

#include <thrill/common/logger.hpp>
#include <thrill/data/serialization.hpp>

namespace thrill {

namespace common {

class FastString
{
public:

	FastString() : size_(0) { };

	FastString(const FastString& in_str) {
		char* begin = new char[in_str.size_];
		std::copy(in_str.data_, in_str.data_ + in_str.size_, begin);
		data_ = begin;
		size_ = in_str.size_;
		has_data_ = true;
	};

	FastString(FastString&& other) :
		FastString(other.data_, other.size_, other.has_data_) {
		other.has_data_ = false;
	};

	~FastString() {
		if (has_data_) {
			delete[](data_);
		}
	};

	static FastString Ref(const char* data, size_t size) {
		return FastString(data, size, false);
	}

	static FastString Ref(std::string::const_iterator data, size_t size) {
		return FastString(&(*data), size, false);
	}

	static FastString Take(const char* data, size_t size) {
		return FastString(data, size, true);
	}

	static FastString Copy(const char* data, size_t size) {
		char* mem = new char[size];
		std::copy(data, data + size, mem);
		return FastString(mem, size, true);
	}

	static FastString Copy(const std::string& in_str) {
		return Copy(in_str.c_str(), in_str.size());
	}

	const char* Data() const {
		return data_;
	}

	size_t Size() const {
		return size_;
	}

	FastString& operator = (const FastString& other) {
		if (has_data_) delete[] (data_);
		char* mem = new char[other.size_];
		std::copy(other.data_, other.data_ + other.size_, mem);
		data_ = mem;
		size_ = other.size_;
		has_data_ = true;
		return *this;
	}

	FastString& operator = (FastString&& other) {
		if (has_data_) delete[] (data_);
		data_ = std::move(other.data_);
		size_ = other.Size();
		has_data_ = other.has_data_;
		other.has_data_ = false;
		return *this;
	}

	bool operator == (std::string other) const {
            // REVIEW(an): use std::equal()!
		return std::equal(data_, data_ + size_, other.c_str(), other.c_str() + other.size());
	}

	bool operator != (std::string other) const {
		return !(operator == (other));
	}

	bool operator == (const FastString& other) const {
		return std::equal(data_, data_ + size_, other.data_, other.data_ + other.size_);
	}

	bool operator != (const FastString& other) const {
		return !(operator == (other));
	}

	friend std::ostream& operator << (std::ostream& os, const FastString& fs) {
		return os.write(fs.Data(), fs.Size());
	}

	std::string ToString() const {
		return std::string(data_, size_);
	}

protected:
	FastString(const char* data, size_t size, bool copy) :
		data_(data), size_(size), has_data_(copy) { };

	const char* data_ = 0;

	size_t size_;

	bool has_data_ = false;

};

} // namespace common

namespace data {

template<typename Archive>
struct Serialization<Archive, common::FastString>
{
	static void Serialize(const common::FastString& fs, Archive& ar) {
		ar.PutVarint(fs.Size()).Append(fs.Data(), fs.Size());
	}

	static common::FastString Deserialize(Archive& ar) {
		uint64_t size = ar.GetVarint();
		char* outdata = new char[size];
		ar.Read(outdata, size);
        return common::FastString::Take(outdata, size);
    }

    static const bool   is_fixed_size = false;
    static const size_t fixed_size = 0;

};

} //namespace data
} // namespace thrill

namespace std { //I am very sorry.
	template <>
	struct hash<thrill::common::FastString>
	{
		size_t operator ()(const thrill::common::FastString& fs) const {
			unsigned int hash = 0xDEADC0DE;
			for (size_t ctr = 0; ctr < fs.Size(); ctr++) {
				hash = ((hash << 5) + hash) + *(fs.Data() + ctr); /* hash * 33 + c */
			}
			return hash;
		}
	};
}

#endif // !THRILL_COMMON_FAST_STRING_HEADER

/******************************************************************************/
<commit_msg>use same hash function as g++ uses for std::string<commit_after>/*******************************************************************************
 * thrill/common/fast_string.hpp
 *
 * (Hopefully) fast static-length string implementation.
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef THRILL_COMMON_FAST_STRING_HEADER
#define THRILL_COMMON_FAST_STRING_HEADER

#include <cstdlib>
#include <cstring>
#include <bits/functional_hash.h>

#include <thrill/common/logger.hpp>
#include <thrill/data/serialization.hpp>

namespace thrill {

namespace common {

class FastString
{
public:

	/**
	 * Default constructor for a FastString.
	 * Doesn't do anything.
	 */
	FastString() : size_(0) { };

	/**
	 *
	 */
	FastString(const FastString& in_str) {
		char* begin = new char[in_str.size_];
		std::copy(in_str.data_, in_str.data_ + in_str.size_, begin);
		data_ = begin;
		size_ = in_str.size_;
		has_data_ = true;
	};

	FastString(FastString&& other) :
		FastString(other.data_, other.size_, other.has_data_) {
		other.has_data_ = false;
	};

	~FastString() {
		if (has_data_) {
			delete[](data_);
		}
	};

	static FastString Ref(const char* data, size_t size) {
		return FastString(data, size, false);
	}

	static FastString Ref(std::string::const_iterator data, size_t size) {
		return FastString(&(*data), size, false);
	}

	static FastString Take(const char* data, size_t size) {
		return FastString(data, size, true);
	}

	static FastString Copy(const char* data, size_t size) {
		char* mem = new char[size];
		std::copy(data, data + size, mem);
		return FastString(mem, size, true);
	}

	static FastString Copy(const std::string& in_str) {
		return Copy(in_str.c_str(), in_str.size());
	}

	const char* Data() const {
		return data_;
	}

	size_t Size() const {
		return size_;
	}

	FastString& operator = (const FastString& other) {
		if (has_data_) delete[] (data_);
		char* mem = new char[other.size_];
		std::copy(other.data_, other.data_ + other.size_, mem);
		data_ = mem;
		size_ = other.size_;
		has_data_ = true;
		return *this;
	}

	FastString& operator = (FastString&& other) {
		if (has_data_) delete[] (data_);
		data_ = std::move(other.data_);
		size_ = other.Size();
		has_data_ = other.has_data_;
		other.has_data_ = false;
		return *this;
	}

	bool operator == (std::string other) const {
            // REVIEW(an): use std::equal()!
		return std::equal(data_, data_ + size_, other.c_str(), other.c_str() + other.size());
	}

	bool operator != (std::string other) const {
		return !(operator == (other));
	}

	bool operator == (const FastString& other) const {
		return std::equal(data_, data_ + size_, other.data_, other.data_ + other.size_);
	}

	bool operator != (const FastString& other) const {
		return !(operator == (other));
	}

	friend std::ostream& operator << (std::ostream& os, const FastString& fs) {
		return os.write(fs.Data(), fs.Size());
	}

	std::string ToString() const {
		return std::string(data_, size_);
	}

protected:
	FastString(const char* data, size_t size, bool copy) :
		data_(data), size_(size), has_data_(copy) { };

	const char* data_ = 0;

	size_t size_;

	bool has_data_ = false;

};

} // namespace common

namespace data {

template<typename Archive>
struct Serialization<Archive, common::FastString>
{
	static void Serialize(const common::FastString& fs, Archive& ar) {
		ar.PutVarint(fs.Size()).Append(fs.Data(), fs.Size());
	}

	static common::FastString Deserialize(Archive& ar) {
		uint64_t size = ar.GetVarint();
		char* outdata = new char[size];
		ar.Read(outdata, size);
        return common::FastString::Take(outdata, size);
    }

    static const bool   is_fixed_size = false;
    static const size_t fixed_size = 0;

};

} //namespace data
} // namespace thrill

namespace std { //I am very sorry.
	template <>
	struct hash<thrill::common::FastString>
	{
		size_t operator ()(const thrill::common::FastString& fs) const {
			//unsigned int hash = 0xDEADC0DE;
			return std::_Hash_impl::hash(fs.Data(), fs.Size());
			//	hash = ((hash << 5) + hash) + *(fs.Data() + ctr); /* hash * 33 + c */
			//return hash;
		}
	};
}

#endif // !THRILL_COMMON_FAST_STRING_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Guido Tack <tack@gecode.org>
 *
 *  Copyright:
 *     Guido Tack, 2007
 *
 *  Last modified:
 *     $Date$ by $Author$
 *     $Revision$
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <iostream>
#include <fstream>
#include <gecode/flatzinc.hh>
#include <gecode/flatzinc/logbrancher.hh>

using namespace std;
using namespace Gecode;

int main(int argc, char** argv) {

  Support::Timer t_total;
  t_total.start();
  FlatZinc::FlatZincOptions opt("Gecode/FlatZinc");
  opt.parse(argc, argv);

  if (argc!=2 && argc!=3) {
    cerr << "Usage: " << argv[0] << " [options] <file>" << endl;
    cerr << "       " << argv[0] << " -help for more information" << endl;
    exit(EXIT_FAILURE);
  }

  const char* filename = argv[1];
  opt.name(filename);

  const char* logname = NULL;
  if (argc==3) {
    logname = argv[2];
  }

  FlatZinc::Printer p;
  FlatZinc::FlatZincSpace* fg = NULL;
  try {
    FlatZinc::ParseResult pr;
    if (!strcmp(filename, "-")) {
      pr = FlatZinc::parseWithSymbols(cin, p);
    } else {
      pr = FlatZinc::parseWithSymbols(filename, p);
    }
    fg = pr.s;

    if (fg) {

      ifstream logstream;

      if (logname) {
        logstream.open(logname, ifstream::in);
        branch(*fg, pr.t, pr.a, logstream);
        opt.c_d(0);
        opt.a_d(0);
      } else {
        fg->createBranchers(fg->solveAnnotations(), opt.seed(), opt.decay(),
                            false, std::cerr);
        fg->shrinkArrays(p);
      }

      if (opt.output()) {
        std::ofstream os(opt.output());
        if (!os.good()) {
          std::cerr << "Could not open file " << opt.output() << " for output."
                    << std::endl;
          exit(EXIT_FAILURE);
        }
        fg->run(os, p, opt, t_total);
        os.close();
      } else {
        fg->run(std::cout, p, opt, t_total);
      }
    } else {
      exit(EXIT_FAILURE);
    }
    delete fg;
  } catch (FlatZinc::Error& e) {
    std::cerr << "Error: " << e.toString() << std::endl;
    return 1;
  }

  return 0;
}

// STATISTICS: flatzinc-any
<commit_msg>Post original branchers after log brancher<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Guido Tack <tack@gecode.org>
 *
 *  Copyright:
 *     Guido Tack, 2007
 *
 *  Last modified:
 *     $Date$ by $Author$
 *     $Revision$
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <iostream>
#include <fstream>
#include <gecode/flatzinc.hh>
#include <gecode/flatzinc/logbrancher.hh>

using namespace std;
using namespace Gecode;

int main(int argc, char** argv) {

  Support::Timer t_total;
  t_total.start();
  FlatZinc::FlatZincOptions opt("Gecode/FlatZinc");
  opt.parse(argc, argv);

  if (argc!=2 && argc!=3) {
    cerr << "Usage: " << argv[0] << " [options] <file>" << endl;
    cerr << "       " << argv[0] << " -help for more information" << endl;
    exit(EXIT_FAILURE);
  }

  const char* filename = argv[1];
  opt.name(filename);

  const char* logname = NULL;
  if (argc==3) {
    logname = argv[2];
  }

  FlatZinc::Printer p;
  FlatZinc::FlatZincSpace* fg = NULL;
  try {
    FlatZinc::ParseResult pr;
    if (!strcmp(filename, "-")) {
      pr = FlatZinc::parseWithSymbols(cin, p);
    } else {
      pr = FlatZinc::parseWithSymbols(filename, p);
    }
    fg = pr.s;

    if (fg) {

      ifstream logstream;

      if (logname) {
        logstream.open(logname, ifstream::in);
        branch(*fg, pr.t, pr.a, logstream);
        opt.c_d(0);
        opt.a_d(0);
      }
      fg->createBranchers(fg->solveAnnotations(), opt.seed(), opt.decay(),
                          false, std::cerr);

      if (logname==NULL) {
        fg->shrinkArrays(p);
      }

      if (opt.output()) {
        std::ofstream os(opt.output());
        if (!os.good()) {
          std::cerr << "Could not open file " << opt.output() << " for output."
                    << std::endl;
          exit(EXIT_FAILURE);
        }
        fg->run(os, p, opt, t_total);
        os.close();
      } else {
        fg->run(std::cout, p, opt, t_total);
      }
    } else {
      exit(EXIT_FAILURE);
    }
    delete fg;
  } catch (FlatZinc::Error& e) {
    std::cerr << "Error: " << e.toString() << std::endl;
    return 1;
  }

  return 0;
}

// STATISTICS: flatzinc-any
<|endoftext|>


<commit_before>#ifndef _TRACER_H
#define _TRACER_H

#include "stdafx.h"

#define TRACER_ENABLED 1
#define HEAP 1
#define STACK 2

#define READ 1
#define WRITE 2
#define NOTE 3

#ifdef TRACER_ENABLED

void tracer_dump(const string& x);
void tracer_dump(const vector<string>& x);
void tracer_dump(const map<string, string>& x);
void tracer_dump(const vector<double>& x);
void tracer_dump(const int &x);
void tracer_dump(const float &x);
void tracer_dump(const double &x);
void tracer_dump(const char &x);
void tracer_dump(const IntegerSet &x);
void tracer_dump(const boost::regex &x);

namespace freicore {
namespace myrimatch {
struct SpectraList;
}
}
void tracer_dump(const freicore::myrimatch::SpectraList &x);

#define TRACER(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump"; tracer_dump(variable); cout << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_P(variable, type, representation, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << &(variable) << '\t' << type << '\t' << representation <<  '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// Reference a variable in an operation, do not dump all its info
#define TRACER_REF(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "ref" << &(variable) << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_UNLINK(variable) { cout << "[TRACER]" << '\t' << "unlink" << '\t' << &(variable) << '\t' __FILE__ << '\t' << __LINE__ << '\n'; }

// Start operation of a given name
#define TRACER_OP_START(name) { cout << "[TRACER]" << '\t' << "op_start" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// End operation of a given name
#define TRACER_OP_END(name) { cout << "[TRACER]" << '\t' << "op_end" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_S2S(variable) lexical_cast<string>(variable)

#else // !TRACER_ENABLED

#define TRACER(variable, operation, heap, note)
#define TRACER_R(variable, type, representation, operation, heap, note)
#define TRACER_UNLINK(variable)
#define TRACER_OP_START(name)
#define TRACER_OP_END(name)
#define TRACER_S2S(variable)

#endif // TRACER_ENABLED

#endif

<commit_msg>Fixing missing tabs<commit_after>#ifndef _TRACER_H
#define _TRACER_H

#include "stdafx.h"

#define TRACER_ENABLED 1
#define HEAP 1
#define STACK 2

#define READ 1
#define WRITE 2
#define NOTE 3

#ifdef TRACER_ENABLED

void tracer_dump(const string& x);
void tracer_dump(const vector<string>& x);
void tracer_dump(const map<string, string>& x);
void tracer_dump(const vector<double>& x);
void tracer_dump(const int &x);
void tracer_dump(const float &x);
void tracer_dump(const double &x);
void tracer_dump(const char &x);
void tracer_dump(const IntegerSet &x);
void tracer_dump(const boost::regex &x);

namespace freicore {
namespace myrimatch {
struct SpectraList;
}
}
void tracer_dump(const freicore::myrimatch::SpectraList &x);

#define TRACER(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t'; tracer_dump(variable); cout << '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_P(variable, type, representation, operation, heap, note) { cout << "[TRACER]" << '\t' << "dump" << '\t' << &(variable) << '\t' << type << '\t' << representation <<  '\t' << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// Reference a variable in an operation, do not dump all its info
#define TRACER_REF(variable, operation, heap, note) { cout << "[TRACER]" << '\t' << "ref" << '\t', << &(variable) << heap << '\t' << operation << '\t' << note << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_UNLINK(variable) { cout << "[TRACER]" << '\t' << "unlink" << '\t' << &(variable) << '\t' __FILE__ << '\t' << __LINE__ << '\n'; }

// Start operation of a given name
#define TRACER_OP_START(name) { cout << "[TRACER]" << '\t' << "op_start" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
// End operation of a given name
#define TRACER_OP_END(name) { cout << "[TRACER]" << '\t' << "op_end" << '\t' << name << '\t' << __FILE__ << '\t' << __LINE__ << '\n'; }
#define TRACER_S2S(variable) lexical_cast<string>(variable)

#else // !TRACER_ENABLED

#define TRACER(variable, operation, heap, note)
#define TRACER_R(variable, type, representation, operation, heap, note)
#define TRACER_UNLINK(variable)
#define TRACER_OP_START(name)
#define TRACER_OP_END(name)
#define TRACER_S2S(variable)

#endif // TRACER_ENABLED

#endif

<|endoftext|>