<commit_before>#include <reflect.hpp>
#include <iostream>
#include <QtTest>

class MetadataTest : public QObject {
    Q_OBJECT
    int var1,var2;
    static int static_var;
    void foo (int);
    int foo (int,double);
    static double static_foo(int,double, const std::string&);
public:
    using Type = MetadataTest;
    OUT_OF_CLASS_META_INFO(MetadataTest)
private slots:
    void class_name_method();
    void vars_obj_names();
    void vars_static_names();
    void vars_names();
    void method_obj_names();
    void method_static_names();
    void method_names();
    void counter_obj_vars();
    void counter_static_vars();
    void counter_vars();
    void counter_obj_method();
    void counter_static_method();
    void counter_method();
    void find_obj_vars();
    void find_static_vars();
    void find_vars();
    void find_obj_methods();
    void find_static_methods();
    void find_methods();
    void get_obj_method_types();
    void get_static_method_types();
    void get_method_types();
    void check_obj_invoke_method();
    void check_static_invoke_method();
    void check_invoke_method();
};

META_INFO(MetadataTest)
REFLECT_OBJ_VARIABLE(var1)
REFLECT_OBJ_VARIABLE(var2)
REFLECT_STATIC_VARIABLE(static_var)
END_META_INFO

void MetadataTest::class_name_method() {
    QVERIFY(reflect::utils::get_class_name<Type>() == HANA_STR("MetadataTest"));
}
void MetadataTest::vars_obj_names() {
    auto bool_tup = reflect::metautils::for_each([this](auto&& index, auto&& tuple) {
        return (reflect::utils::get_name<Type,reflect::ObjVars>(index) == boost::hana::at(tuple,index));
    },reflect::metautils::generate_tuple_indices<decltype(reflect::utils::get_count<Type,reflect::ObjVars>())>(),
    boost::hana::make_tuple(HANA_STR("var1"),HANA_STR("var2")));
    QVERIFY (bool_tup == boost::hana::make_tuple(true,true));
}

void MetadataTest::vars_static_names() {
    auto bool_tup = reflect::metautils::for_each([this](auto&& index, auto&& tuple) {
        return (reflect::utils::get_name<Type,reflect::StaticVars>(index) == boost::hana::at(tuple,index));
    },reflect::metautils::generate_tuple_indices<decltype(reflect::utils::get_count<Type,reflect::StaticVars>())>(),
    boost::hana::make_tuple(HANA_STR("static_var")));
    QVERIFY (bool_tup == boost::hana::make_tuple(true));
}

void MetadataTest::vars_names() {
    auto bool_tup = reflect::metautils::for_each([this](auto&& index, auto&& tuple) {
        return (reflect::utils::get_name<Type,reflect::AllVars>(index) == boost::hana::at(tuple,index));
    },reflect::metautils::generate_tuple_indices<decltype(reflect::utils::get_count<Type,reflect::AllVars>())>(),
    boost::hana::make_tuple(HANA_STR("var1"),HANA_STR("var2"),HANA_STR("static_var")));
    QVERIFY (bool_tup == boost::hana::make_tuple(true,true,true));
}

void MetadataTest::method_obj_names() {
    QVERIFY(false);
}

void MetadataTest::method_static_names() {
    QVERIFY(false);
}

void MetadataTest::method_names() {
    QVERIFY(false);
//    QCOMPARE(reflect::get_method_name<Type>(::boost::hana::size_c<0>),HANA_STR("foo"));
//    QCOMPARE(reflect::get_method_name<Type>(::boost::hana::size_c<1>),HANA_STR("foo"));
//    QCOMPARE(reflect::get_method_name<Type>(::boost::hana::size_c<2>),HANA_STR("static_foo"));
}

void MetadataTest::counter_obj_vars() {
    QVERIFY((reflect::utils::get_count<Type,reflect::ObjVars>()) == boost::hana::size_c<2>);
}

void MetadataTest::counter_static_vars() {
    QVERIFY((reflect::utils::get_count<Type,reflect::StaticVars>()) == boost::hana::size_c<1>);
}

void MetadataTest::counter_vars() {
    QVERIFY((reflect::utils::get_count<Type,reflect::AllVars>()) == boost::hana::size_c<3>);
}

void MetadataTest::counter_obj_method() {
    auto tuple = reflect::metautils::merge_tuple_of_tuples(reflect::metautils::for_each([this](auto&& name) {
        return reflect::utils::find_name<Type,reflect::ObjVars>(name);
    },boost::hana::make_tuple(HANA_STR("var1"),HANA_STR("var2"))));
    QVERIFY(tuple == (boost::hana::tuple_c<std::size_t,0,1>));
}

void MetadataTest::counter_static_method() {
    QVERIFY(false);
//    QVERIFY(reflect::get_methods_static_count<Type>() == 1);
}

void MetadataTest::counter_method() {
    QVERIFY(false);
//    QVERIFY(reflect::get_methods_count<Type>() == 3);
}

void MetadataTest::find_obj_vars() {
    QVERIFY(false);
//    QCOMPARE(reflect::find_obj_variable_index<Type>(HANA_STR("var1")),boost::hana::size_c<0>);
//    QCOMPARE(reflect::find_obj_variable_index<Type>(HANA_STR("var2")),boost::hana::size_c<1>);
//    QCOMPARE(reflect::find_obj_variable_index<Type>(HANA_STR("static_var")),boost::hana::nothing);
}

void MetadataTest::find_static_vars() {
    QVERIFY(false);
//    QCOMPARE(reflect::find_static_variable_index<Type>(HANA_STR("var1")),boost::hana::nothing);
//    QCOMPARE(reflect::find_static_variable_index<Type>(HANA_STR("var2")),boost::hana::nothing);
//    QCOMPARE(reflect::find_static_variable_index<Type>(HANA_STR("static_var")),boost::hana::size_c<0>);
}

void MetadataTest::find_vars() {
    QVERIFY(false);
//    QCOMPARE(reflect::find_variable_index<Type>(HANA_STR("var1")),boost::hana::size_c<0>);
//    QCOMPARE(reflect::find_variable_index<Type>(HANA_STR("var2")),boost::hana::size_c<1>);
//    QCOMPARE(reflect::find_variable_index<Type>(HANA_STR("nothing")),boost::hana::nothing);
}

void MetadataTest::find_obj_methods() {
    QVERIFY(false);
//    QVERIFY(reflect::find_obj_method_index<Type>(HANA_STR("foo")) == (boost::hana::tuple_c<std::size_t,0,1>));
//    QVERIFY(reflect::find_obj_method_index<Type>(HANA_STR("static_foo")) == boost::hana::nothing);
//    QVERIFY(reflect::find_obj_method_index<Type>(HANA_STR("nothing")) == boost::hana::nothing);
}

void MetadataTest::find_static_methods() {
    QVERIFY(false);
//    QVERIFY(reflect::find_static_method_index<Type>(HANA_STR("foo")) == boost::hana::nothing);
//    QVERIFY(reflect::find_static_method_index<Type>(HANA_STR("static_foo")) == (boost::hana::tuple_c<std::size_t,0>));
//    QVERIFY(reflect::find_static_method_index<Type>(HANA_STR("nothing")) == boost::hana::nothing);
}

void MetadataTest::find_methods() {
    QVERIFY(false);
//    QVERIFY(reflect::find_method_index<Type>(HANA_STR("foo")) == (boost::hana::tuple_c<std::size_t,0,1>));
//    QVERIFY(reflect::find_method_index<Type>(HANA_STR("static_foo")) == (boost::hana::tuple_c<std::size_t,2>));
//    QVERIFY(reflect::find_method_index<Type>(HANA_STR("nothing")) == boost::hana::nothing);
}

void MetadataTest::get_obj_method_types() {
    QVERIFY(false);
}

void MetadataTest::get_static_method_types() {
    QVERIFY(false);
}

void MetadataTest::get_method_types() {
    QVERIFY(false);
//    QVERIFY (reflect::get_method_arg_types<Type>(::boost::hana::size_c<0>) == ::boost::hana::tuple_t<int>);
//    QVERIFY (reflect::get_method_arg_types<Type>(::boost::hana::size_c<1>) == (::boost::hana::tuple_t<int,double>));
//    QVERIFY (reflect::get_method_arg_types<Type>(::boost::hana::size_c<2>) == (::boost::hana::tuple_t<int,double,const std::string&>));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,0,0>),typeid(int));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,1,0>),typeid(int));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,1,1>),typeid(double));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,2,0>),typeid(int));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,2,1>),typeid(double));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,2,2>),typeid(const std::string&));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,0,0>),typeid(std::decay_t<decltype(reflect::method_arg_type<Type>(::boost::hana::size_c<0>,::boost::hana::size_c<0>))>::type));
//    QCOMPARE(typeid(reflect::method_return_type_t<Type,0>),typeid(void));
//    QCOMPARE(typeid(reflect::method_return_type_t<Type,1>),typeid(int));
//    QCOMPARE(typeid(reflect::method_return_type_t<Type,2>),typeid(double));
}

void MetadataTest::check_obj_invoke_method() {
    QVERIFY(false);
//    QCOMPARE(reflect::check_invoke_obj_method<Type>(boost::hana::nothing),boost::hana::nothing);
//    QCOMPARE((reflect::check_invoke_obj_method<Type,int>(reflect::find_obj_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(true,false));
//    QCOMPARE((reflect::check_invoke_obj_method<Type,int,double>(reflect::find_obj_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(false,true));
//    QCOMPARE((reflect::check_invoke_obj_method<Type,int&&,double,std::string>(reflect::find_obj_method_index<Type>(HANA_STR("static_foo")))), boost::hana::nothing);
}

void MetadataTest::check_static_invoke_method() {
    QVERIFY(false);
    //QCOMPARE(reflect::check_invoke_static_method<Type>(boost::hana::nothing),boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_static_method<Type,int>(reflect::find_static_method_index<Type>(HANA_STR("foo")))), boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_static_method<Type,int,double>(reflect::find_static_method_index<Type>(HANA_STR("foo")))), boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_static_method<Type,int&&,double,std::string>(reflect::find_static_method_index<Type>(HANA_STR("static_foo")))), ::boost::hana::make_tuple(true));
}

void MetadataTest::check_invoke_method() {
    QVERIFY(false);
    //QCOMPARE(reflect::check_invoke_method<Type>(boost::hana::nothing),boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_method<Type,int>(reflect::find_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(true,false));
    //QCOMPARE((reflect::check_invoke_method<Type,int,double>(reflect::find_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(false,true));
    //QCOMPARE((reflect::check_invoke_method<Type,int&&,double,std::string>(reflect::find_method_index<Type>(HANA_STR("static_foo")))), ::boost::hana::make_tuple(true));
}

QTEST_MAIN(MetadataTest)
#include "main.moc"
<commit_msg>WIP Refactoring (add some tests)<commit_after>#include <reflect.hpp>
#include <iostream>
#include <QtTest>

class MetadataTest : public QObject {
    Q_OBJECT
    int var1,var2;
    static int static_var;
    void foo (int);
    int foo (int,double);
    static double static_foo(int,double, const std::string&);
public:
    using Type = MetadataTest;
    OUT_OF_CLASS_META_INFO(MetadataTest)
private slots:
    void class_name_method();
    void vars_obj_names();
    void vars_static_names();
    void vars_names();
    void method_obj_names();
    void method_static_names();
    void method_names();
    void counter_obj_vars();
    void counter_static_vars();
    void counter_vars();
    void counter_obj_method();
    void counter_static_method();
    void counter_method();
    void find_obj_vars();
    void find_static_vars();
    void find_vars();
    void find_obj_methods();
    void find_static_methods();
    void find_methods();
    void get_obj_method_types();
    void get_static_method_types();
    void get_method_types();
    void check_obj_invoke_method();
    void check_static_invoke_method();
    void check_invoke_method();
};

META_INFO(MetadataTest)
REFLECT_OBJ_VARIABLE(var1)
REFLECT_OBJ_VARIABLE(var2)
REFLECT_STATIC_VARIABLE(static_var)
END_META_INFO

void MetadataTest::class_name_method() {
    QVERIFY(reflect::utils::get_class_name<Type>() == HANA_STR("MetadataTest"));
}
void MetadataTest::vars_obj_names() {
    auto bool_tup = reflect::metautils::for_each([this](auto&& index, auto&& tuple) {
        return (reflect::utils::get_name<Type,reflect::ObjVars>(index) == boost::hana::at(tuple,index));
    },reflect::metautils::generate_tuple_indices<decltype(reflect::utils::get_count<Type,reflect::ObjVars>())>(),
    boost::hana::make_tuple(HANA_STR("var1"),HANA_STR("var2")));
    QVERIFY (bool_tup == boost::hana::make_tuple(true,true));
}

void MetadataTest::vars_static_names() {
    auto bool_tup = reflect::metautils::for_each([this](auto&& index, auto&& tuple) {
        return (reflect::utils::get_name<Type,reflect::StaticVars>(index) == boost::hana::at(tuple,index));
    },reflect::metautils::generate_tuple_indices<decltype(reflect::utils::get_count<Type,reflect::StaticVars>())>(),
    boost::hana::make_tuple(HANA_STR("static_var")));
    QVERIFY (bool_tup == boost::hana::make_tuple(true));
}

void MetadataTest::vars_names() {
    auto bool_tup = reflect::metautils::for_each([this](auto&& index, auto&& tuple) {
        return (reflect::utils::get_name<Type,reflect::AllVars>(index) == boost::hana::at(tuple,index));
    },reflect::metautils::generate_tuple_indices<decltype(reflect::utils::get_count<Type,reflect::AllVars>())>(),
    boost::hana::make_tuple(HANA_STR("var1"),HANA_STR("var2"),HANA_STR("static_var")));
    QVERIFY (bool_tup == boost::hana::make_tuple(true,true,true));
}

void MetadataTest::method_obj_names() {
    QVERIFY(false);
}

void MetadataTest::method_static_names() {
    QVERIFY(false);
}

void MetadataTest::method_names() {
    QVERIFY(false);
//    QCOMPARE(reflect::get_method_name<Type>(::boost::hana::size_c<0>),HANA_STR("foo"));
//    QCOMPARE(reflect::get_method_name<Type>(::boost::hana::size_c<1>),HANA_STR("foo"));
//    QCOMPARE(reflect::get_method_name<Type>(::boost::hana::size_c<2>),HANA_STR("static_foo"));
}

void MetadataTest::counter_obj_vars() {
    QVERIFY((reflect::utils::get_count<Type,reflect::ObjVars>()) == boost::hana::size_c<2>);
}

void MetadataTest::counter_static_vars() {
    QVERIFY((reflect::utils::get_count<Type,reflect::StaticVars>()) == boost::hana::size_c<1>);
}

void MetadataTest::counter_vars() {
    QVERIFY((reflect::utils::get_count<Type,reflect::AllVars>()) == boost::hana::size_c<3>);
}

void MetadataTest::counter_obj_method() {
    auto tuple = reflect::metautils::merge_tuple_of_tuples(reflect::metautils::for_each([this](auto&& name) {
        return reflect::utils::find_name<Type,reflect::ObjVars>(name);
    },boost::hana::make_tuple(HANA_STR("var1"),HANA_STR("var2"))));
    QVERIFY(tuple == (boost::hana::tuple_c<std::size_t,0,1>));
}

void MetadataTest::counter_static_method() {
    auto tuple = reflect::metautils::merge_tuple_of_tuples(reflect::metautils::for_each([this](auto&& name) {
        return reflect::utils::find_name<Type,reflect::StaticVars>(name);
    },boost::hana::make_tuple(HANA_STR("static_var"))));
    QVERIFY(tuple == (boost::hana::tuple_c<std::size_t,0>));
}

void MetadataTest::counter_method() {
    auto tuple = reflect::metautils::merge_tuple_of_tuples(reflect::metautils::for_each([this](auto&& name) {
        return reflect::utils::find_name<Type,reflect::AllVars>(name);
    },boost::hana::make_tuple(HANA_STR("var1"),HANA_STR("var2"),HANA_STR("static_var"))));
    QVERIFY(tuple == (boost::hana::tuple_c<std::size_t,0,1,2>));
}

void MetadataTest::find_obj_vars() {
    QVERIFY(false);
//    QCOMPARE(reflect::find_obj_variable_index<Type>(HANA_STR("var1")),boost::hana::size_c<0>);
//    QCOMPARE(reflect::find_obj_variable_index<Type>(HANA_STR("var2")),boost::hana::size_c<1>);
//    QCOMPARE(reflect::find_obj_variable_index<Type>(HANA_STR("static_var")),boost::hana::nothing);
}

void MetadataTest::find_static_vars() {
    QVERIFY(false);
//    QCOMPARE(reflect::find_static_variable_index<Type>(HANA_STR("var1")),boost::hana::nothing);
//    QCOMPARE(reflect::find_static_variable_index<Type>(HANA_STR("var2")),boost::hana::nothing);
//    QCOMPARE(reflect::find_static_variable_index<Type>(HANA_STR("static_var")),boost::hana::size_c<0>);
}

void MetadataTest::find_vars() {
    QVERIFY(false);
//    QCOMPARE(reflect::find_variable_index<Type>(HANA_STR("var1")),boost::hana::size_c<0>);
//    QCOMPARE(reflect::find_variable_index<Type>(HANA_STR("var2")),boost::hana::size_c<1>);
//    QCOMPARE(reflect::find_variable_index<Type>(HANA_STR("nothing")),boost::hana::nothing);
}

void MetadataTest::find_obj_methods() {
    QVERIFY(false);
//    QVERIFY(reflect::find_obj_method_index<Type>(HANA_STR("foo")) == (boost::hana::tuple_c<std::size_t,0,1>));
//    QVERIFY(reflect::find_obj_method_index<Type>(HANA_STR("static_foo")) == boost::hana::nothing);
//    QVERIFY(reflect::find_obj_method_index<Type>(HANA_STR("nothing")) == boost::hana::nothing);
}

void MetadataTest::find_static_methods() {
    QVERIFY(false);
//    QVERIFY(reflect::find_static_method_index<Type>(HANA_STR("foo")) == boost::hana::nothing);
//    QVERIFY(reflect::find_static_method_index<Type>(HANA_STR("static_foo")) == (boost::hana::tuple_c<std::size_t,0>));
//    QVERIFY(reflect::find_static_method_index<Type>(HANA_STR("nothing")) == boost::hana::nothing);
}

void MetadataTest::find_methods() {
    QVERIFY(false);
//    QVERIFY(reflect::find_method_index<Type>(HANA_STR("foo")) == (boost::hana::tuple_c<std::size_t,0,1>));
//    QVERIFY(reflect::find_method_index<Type>(HANA_STR("static_foo")) == (boost::hana::tuple_c<std::size_t,2>));
//    QVERIFY(reflect::find_method_index<Type>(HANA_STR("nothing")) == boost::hana::nothing);
}

void MetadataTest::get_obj_method_types() {
    QVERIFY(false);
}

void MetadataTest::get_static_method_types() {
    QVERIFY(false);
}

void MetadataTest::get_method_types() {
    QVERIFY(false);
//    QVERIFY (reflect::get_method_arg_types<Type>(::boost::hana::size_c<0>) == ::boost::hana::tuple_t<int>);
//    QVERIFY (reflect::get_method_arg_types<Type>(::boost::hana::size_c<1>) == (::boost::hana::tuple_t<int,double>));
//    QVERIFY (reflect::get_method_arg_types<Type>(::boost::hana::size_c<2>) == (::boost::hana::tuple_t<int,double,const std::string&>));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,0,0>),typeid(int));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,1,0>),typeid(int));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,1,1>),typeid(double));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,2,0>),typeid(int));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,2,1>),typeid(double));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,2,2>),typeid(const std::string&));
//    QCOMPARE(typeid(reflect::method_arg_type_t<Type,0,0>),typeid(std::decay_t<decltype(reflect::method_arg_type<Type>(::boost::hana::size_c<0>,::boost::hana::size_c<0>))>::type));
//    QCOMPARE(typeid(reflect::method_return_type_t<Type,0>),typeid(void));
//    QCOMPARE(typeid(reflect::method_return_type_t<Type,1>),typeid(int));
//    QCOMPARE(typeid(reflect::method_return_type_t<Type,2>),typeid(double));
}

void MetadataTest::check_obj_invoke_method() {
    QVERIFY(false);
//    QCOMPARE(reflect::check_invoke_obj_method<Type>(boost::hana::nothing),boost::hana::nothing);
//    QCOMPARE((reflect::check_invoke_obj_method<Type,int>(reflect::find_obj_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(true,false));
//    QCOMPARE((reflect::check_invoke_obj_method<Type,int,double>(reflect::find_obj_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(false,true));
//    QCOMPARE((reflect::check_invoke_obj_method<Type,int&&,double,std::string>(reflect::find_obj_method_index<Type>(HANA_STR("static_foo")))), boost::hana::nothing);
}

void MetadataTest::check_static_invoke_method() {
    QVERIFY(false);
    //QCOMPARE(reflect::check_invoke_static_method<Type>(boost::hana::nothing),boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_static_method<Type,int>(reflect::find_static_method_index<Type>(HANA_STR("foo")))), boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_static_method<Type,int,double>(reflect::find_static_method_index<Type>(HANA_STR("foo")))), boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_static_method<Type,int&&,double,std::string>(reflect::find_static_method_index<Type>(HANA_STR("static_foo")))), ::boost::hana::make_tuple(true));
}

void MetadataTest::check_invoke_method() {
    QVERIFY(false);
    //QCOMPARE(reflect::check_invoke_method<Type>(boost::hana::nothing),boost::hana::nothing);
    //QCOMPARE((reflect::check_invoke_method<Type,int>(reflect::find_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(true,false));
    //QCOMPARE((reflect::check_invoke_method<Type,int,double>(reflect::find_method_index<Type>(HANA_STR("foo")))), ::boost::hana::make_tuple(false,true));
    //QCOMPARE((reflect::check_invoke_method<Type,int&&,double,std::string>(reflect::find_method_index<Type>(HANA_STR("static_foo")))), ::boost::hana::make_tuple(true));
}

QTEST_MAIN(MetadataTest)
#include "main.moc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: autoregisterhelper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-11-02 10:25:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include "autoregisterhelper.hxx"

#include <rtl/ustring.hxx>

#include <cppunit/autoregister/registerfunc.h>
#include <cppunit/autoregister/callbackstructure.h>
#include <cppunit/result/callbackfunc.h>
#include <cppunit/autoregister/testfunc.h>
#include "filehelper.hxx"

FunctionList m_Functions;
// osl::Mutex   m_Mutex;

void SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)
{
    // printf("Function register call for func(%s) successful.\n", _sFuncName);
    m_Functions.push_back(_pFunc);
}

// -----------------------------------------------------------------------------
AutomaticRegisterHelper::AutomaticRegisterHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions /*, JobList * _pJobList*/)
        :DynamicLibraryHelper(_sDLLName, _aOptions),
         m_bLoadLibraryOK(false)
{
    // try to get the entry pointer
    FktRegAllPtr pFunc = (FktRegAllPtr) m_pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) );

    if (pFunc)
    {
        m_bLoadLibraryOK = true;
        // FktRegFuncPtr pRegisterFunc = &DynamicLibraryHelper::registerFunc;
        // pFunc(pRegisterFunc);
        // osl::Guard aGuard(m_Mutex);
        FktRegFuncPtr pRegisterFunc = &registerFunc;

        CallbackStructure aCallback;
        aCallback.aRegisterFunction = pRegisterFunc;

        aCallback.aCallbackDispatch  = &CallbackDispatch;

        // special parameter for API testing
        if (_aOptions.hasOpt("-forward"))
        {
            aCallback.psForward = _aOptions.getOpt("-forward").getStr();
        }

        // aCallback.pJobList = _pJobList;

        //# aCallback.aStartTest  = &TestResult_startTest;
        //# aCallback.aAddFailure = &TestResult_addFailure;
        //# aCallback.aAddError   = &TestResult_addError;
        //# aCallback.aEndTest    = &TestResult_endTest;
        //# aCallback.aShouldStop = &TestResult_shouldStop;
        //# aCallback.aAddInfo    = &TestResult_addInfo;
        //# aCallback.aEnterNode  = &TestResult_enterNode;
        //# aCallback.aLeaveNode  = &TestResult_leaveNode;

        aCallback.nBits       = FileHelper::createFlags(_aOptions);

        pFunc(&aCallback);

        if (aCallback.nMagic == aCallback.nMagic2)
        {
            // ok internal simple test done.
            m_aFunctionList = m_Functions;
        }
        else
        {
            // ERROR, the function seams not to be what we thing it's to be.
            fprintf(stderr, "error: Internal check failed. Structure inconsistent, Value Magic2 != Magic.\nPlease recompile your test libraries.");
            exit(-1);
        }
    }
    else
    {
        fprintf(stderr, "warning: Function 'registerAllTestFunction' not found.\n");
        fprintf(stderr, "If you think, you are right, build testshl2 completly new.\n");
    }
}

void AutomaticRegisterHelper::CallAll(hTestResult _hResult) const
{
    // can't load the module, break the tests.
    if (m_bLoadLibraryOK == false)
    {
        return;
    }

    for (FunctionList::const_iterator it = m_aFunctionList.begin();
         it != m_aFunctionList.end();
         ++it)
    {
        FktPtr pFunc = *it;
        if (pFunc)
        {
            (pFunc)(_hResult);
        }
    }
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.6); FILE MERGED 2005/09/05 17:28:43 rt 1.6.6.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: autoregisterhelper.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:05:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include "autoregisterhelper.hxx"

#include <rtl/ustring.hxx>

#include <cppunit/autoregister/registerfunc.h>
#include <cppunit/autoregister/callbackstructure.h>
#include <cppunit/result/callbackfunc.h>
#include <cppunit/autoregister/testfunc.h>
#include "filehelper.hxx"

FunctionList m_Functions;
// osl::Mutex   m_Mutex;

void SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)
{
    // printf("Function register call for func(%s) successful.\n", _sFuncName);
    m_Functions.push_back(_pFunc);
}

// -----------------------------------------------------------------------------
AutomaticRegisterHelper::AutomaticRegisterHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions /*, JobList * _pJobList*/)
        :DynamicLibraryHelper(_sDLLName, _aOptions),
         m_bLoadLibraryOK(false)
{
    // try to get the entry pointer
    FktRegAllPtr pFunc = (FktRegAllPtr) m_pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) );

    if (pFunc)
    {
        m_bLoadLibraryOK = true;
        // FktRegFuncPtr pRegisterFunc = &DynamicLibraryHelper::registerFunc;
        // pFunc(pRegisterFunc);
        // osl::Guard aGuard(m_Mutex);
        FktRegFuncPtr pRegisterFunc = &registerFunc;

        CallbackStructure aCallback;
        aCallback.aRegisterFunction = pRegisterFunc;

        aCallback.aCallbackDispatch  = &CallbackDispatch;

        // special parameter for API testing
        if (_aOptions.hasOpt("-forward"))
        {
            aCallback.psForward = _aOptions.getOpt("-forward").getStr();
        }

        // aCallback.pJobList = _pJobList;

        //# aCallback.aStartTest  = &TestResult_startTest;
        //# aCallback.aAddFailure = &TestResult_addFailure;
        //# aCallback.aAddError   = &TestResult_addError;
        //# aCallback.aEndTest    = &TestResult_endTest;
        //# aCallback.aShouldStop = &TestResult_shouldStop;
        //# aCallback.aAddInfo    = &TestResult_addInfo;
        //# aCallback.aEnterNode  = &TestResult_enterNode;
        //# aCallback.aLeaveNode  = &TestResult_leaveNode;

        aCallback.nBits       = FileHelper::createFlags(_aOptions);

        pFunc(&aCallback);

        if (aCallback.nMagic == aCallback.nMagic2)
        {
            // ok internal simple test done.
            m_aFunctionList = m_Functions;
        }
        else
        {
            // ERROR, the function seams not to be what we thing it's to be.
            fprintf(stderr, "error: Internal check failed. Structure inconsistent, Value Magic2 != Magic.\nPlease recompile your test libraries.");
            exit(-1);
        }
    }
    else
    {
        fprintf(stderr, "warning: Function 'registerAllTestFunction' not found.\n");
        fprintf(stderr, "If you think, you are right, build testshl2 completly new.\n");
    }
}

void AutomaticRegisterHelper::CallAll(hTestResult _hResult) const
{
    // can't load the module, break the tests.
    if (m_bLoadLibraryOK == false)
    {
        return;
    }

    for (FunctionList::const_iterator it = m_aFunctionList.begin();
         it != m_aFunctionList.end();
         ++it)
    {
        FktPtr pFunc = *it;
        if (pFunc)
        {
            (pFunc)(_hResult);
        }
    }
}

<|endoftext|>


<commit_before>//
//  main.cpp
//  PerfTestDriver
//
//  Created by Enrico Granata on 3/6/13.
//  Copyright (c) 2013 Apple Inc. All rights reserved.
//

#include <CoreFoundation/CoreFoundation.h>

#include "lldb-perf/lib/Timer.h"
#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/Measurement.h"
#include "lldb-perf/lib/TestCase.h"
#include "lldb-perf/lib/Xcode.h"

#include <iostream>
#include <unistd.h>
#include <fstream>

using namespace lldb::perf;

class SketchTest : public TestCase
{
public:
    SketchTest () :
    m_fetch_frames_measurement ([this] (SBProcess process) -> void {
        Xcode::FetchFrames (process,false,false);
    }, "fetch-frames"),
    m_file_line_bp_measurement([] (SBTarget target,const char* file, uint32_t line) -> void {
        Xcode::CreateFileLineBreakpoint(target, file, line);
    }, "file-line-bkpt"),
    m_fetch_modules_measurement ([] (SBTarget target) -> void {
        Xcode::FetchModules(target);
    }, "fetch-modules"),
    m_fetch_vars_measurement([this] (SBProcess process, int depth) -> void {
        auto threads_count = process.GetNumThreads();
        for (size_t thread_num = 0; thread_num < threads_count; thread_num++)
        {
            SBThread thread(process.GetThreadAtIndex(thread_num));
            SBFrame frame(thread.GetFrameAtIndex(0));
            Xcode::FetchVariables(frame,depth,GetVerbose());

        }
    }, "fetch-vars"),
    m_run_expr_measurement([this] (SBFrame frame, const char* expr) -> void {
        SBValue value(frame.EvaluateExpression(expr, lldb::eDynamicCanRunTarget));
        Xcode::FetchVariable(value,0,GetVerbose());
    }, "run-expr")
    {}

    virtual
    ~SketchTest ()
    {
    }

    virtual void
	Setup (int argc, const char** argv)
    {
        m_app_path.assign(argv[1]); // "~/perf/Small_ObjC/Sketch/build/Debug/Sketch.app"
        m_doc_path.assign(argv[2]); // "/Volumes/work/egranata/perf/Small_ObjC/TesterApp/foobar.sketch2";
        m_out_path.assign(argv[3]);
        TestCase::Setup(argc,argv);
        m_target = m_debugger.CreateTarget(m_app_path.c_str());
        const char* file_arg = m_doc_path.c_str();
        const char* persist_arg = "-ApplePersistenceIgnoreState";
        const char* persist_skip = "YES";
        const char* empty = nullptr;
        const char* args[] = {file_arg,persist_arg,persist_skip,empty};
        m_file_line_bp_measurement(m_target, "SKTDocument.m",245);
        m_file_line_bp_measurement(m_target, "SKTDocument.m",283);
        m_file_line_bp_measurement(m_target, "SKTText.m",326);

        Launch (args,".");
    }

    void
    DoTest ()
    {
        m_fetch_frames_measurement(m_process);
        m_fetch_modules_measurement(m_target);
        m_fetch_vars_measurement(m_process,1);
    }

	virtual ActionWanted
	TestStep (int counter)
    {
#define STEP(n) if (counter == n)
#define NEXT(s) return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWNext,SelectMyThread(s)}
#define FINISH(s) return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWFinish,SelectMyThread(s)}
#define CONT return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWContinue,SBThread()}
#define KILL return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWKill,SBThread()}
        STEP(0) {
            DoTest ();
            m_file_line_bp_measurement(m_target, "SKTDocument.m",254);
            CONT;
        }
        STEP(1) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTDocument.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"properties");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[properties description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"typeName");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"data");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[data description]");
            CONT;
        }
        STEP(2) {
            DoTest ();
            CONT;
        }
        STEP(3) {
            DoTest ();
            NEXT("SKTText.m");
        }
        STEP(4) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTText.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"layoutManager");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"contents");
            NEXT("SKTText.m");
        }
        STEP(5) {
            DoTest ();
            NEXT("SKTText.m");
        }
        STEP(6) {
            DoTest ();
            NEXT("SKTText.m");
        }
        STEP(7) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTText.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"@\"an NSString\"");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[(id)@\"an NSString\" description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"@[@1,@2,@3]");
            FINISH("SKTText.m");
        }
        STEP(8) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTGraphicView.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[graphics description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[selectionIndexes description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"(BOOL)NSIntersectsRect(rect, graphicDrawingBounds)");
            KILL;
        }
        KILL;
#undef STEP
#undef NEXT
#undef CONT
#undef KILL
    }

    void
    Results ()
    {
        auto ff_metric = m_fetch_frames_measurement.metric();
        auto fl_metric = m_file_line_bp_measurement.metric();
        auto md_metric = m_fetch_modules_measurement.metric();
        auto fv_metric = m_fetch_vars_measurement.metric();
        auto xp_metric = m_run_expr_measurement.metric();

        CFCMutableArray array;
        ff_metric.Write(array);
        fl_metric.Write(array);
        md_metric.Write(array);
        fv_metric.Write(array);
        xp_metric.Write(array);

        CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, array.get(), kCFPropertyListXMLFormat_v1_0, 0, NULL);

        CFURLRef file = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8*)m_out_path.c_str(), m_out_path.size(), FALSE);

        CFURLWriteDataAndPropertiesToResource(file,xmlData,NULL,NULL);
    }

private:
    Measurement<lldb::perf::TimeGauge, std::function<void(SBProcess)>> m_fetch_frames_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBTarget, const char*, uint32_t)>> m_file_line_bp_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBTarget)>> m_fetch_modules_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBProcess,int)>> m_fetch_vars_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBFrame,const char*)>> m_run_expr_measurement;

    SBThread
	SelectMyThread (const char* file_name)
	{
		auto threads_count = m_process.GetNumThreads();
		for (auto thread_num = 0; thread_num < threads_count; thread_num++)
		{
			SBThread thread(m_process.GetThreadAtIndex(thread_num));
			auto local_file_name = thread.GetFrameAtIndex(0).GetCompileUnit().GetFileSpec().GetFilename();
			if (!local_file_name)
				continue;
			if (strcmp(local_file_name,file_name))
				continue;
			return thread;
		}
		Xcode::RunCommand(m_debugger,"bt all",true);
		assert(false);
	}
    std::string m_app_path;
    std::string m_doc_path;
    std::string m_out_path;
};

// argv[1] == path to app
// argv[2] == path to document
// argv[3] == path to result
int main(int argc, const char * argv[])
{
    SketchTest skt;
    TestCase::Run(skt,argc,argv);
    return 0;
}

<commit_msg>Dump the measurements directly instead of getting their metrics first (this code needs to be pushed up so that in the basic scenarios TestCase knows to dump all its measurements directly)<commit_after>//
//  main.cpp
//  PerfTestDriver
//
//  Created by Enrico Granata on 3/6/13.
//  Copyright (c) 2013 Apple Inc. All rights reserved.
//

#include <CoreFoundation/CoreFoundation.h>

#include "lldb-perf/lib/Timer.h"
#include "lldb-perf/lib/Metric.h"
#include "lldb-perf/lib/Measurement.h"
#include "lldb-perf/lib/TestCase.h"
#include "lldb-perf/lib/Xcode.h"

#include <iostream>
#include <unistd.h>
#include <fstream>

using namespace lldb::perf;

class SketchTest : public TestCase
{
public:
    SketchTest () :
    m_fetch_frames_measurement ([this] (SBProcess process) -> void {
        Xcode::FetchFrames (process,false,false);
    }, "fetch-frames"),
    m_file_line_bp_measurement([] (SBTarget target,const char* file, uint32_t line) -> void {
        Xcode::CreateFileLineBreakpoint(target, file, line);
    }, "file-line-bkpt"),
    m_fetch_modules_measurement ([] (SBTarget target) -> void {
        Xcode::FetchModules(target);
    }, "fetch-modules"),
    m_fetch_vars_measurement([this] (SBProcess process, int depth) -> void {
        auto threads_count = process.GetNumThreads();
        for (size_t thread_num = 0; thread_num < threads_count; thread_num++)
        {
            SBThread thread(process.GetThreadAtIndex(thread_num));
            SBFrame frame(thread.GetFrameAtIndex(0));
            Xcode::FetchVariables(frame,depth,GetVerbose());

        }
    }, "fetch-vars"),
    m_run_expr_measurement([this] (SBFrame frame, const char* expr) -> void {
        SBValue value(frame.EvaluateExpression(expr, lldb::eDynamicCanRunTarget));
        Xcode::FetchVariable(value,0,GetVerbose());
    }, "run-expr")
    {}

    virtual
    ~SketchTest ()
    {
    }

    virtual void
	Setup (int argc, const char** argv)
    {
        m_app_path.assign(argv[1]); // "~/perf/Small_ObjC/Sketch/build/Debug/Sketch.app"
        m_doc_path.assign(argv[2]); // "/Volumes/work/egranata/perf/Small_ObjC/TesterApp/foobar.sketch2";
        m_out_path.assign(argv[3]);
        TestCase::Setup(argc,argv);
        m_target = m_debugger.CreateTarget(m_app_path.c_str());
        const char* file_arg = m_doc_path.c_str();
        const char* persist_arg = "-ApplePersistenceIgnoreState";
        const char* persist_skip = "YES";
        const char* empty = nullptr;
        const char* args[] = {file_arg,persist_arg,persist_skip,empty};
        m_file_line_bp_measurement(m_target, "SKTDocument.m",245);
        m_file_line_bp_measurement(m_target, "SKTDocument.m",283);
        m_file_line_bp_measurement(m_target, "SKTText.m",326);

        Launch (args,".");
    }

    void
    DoTest ()
    {
        m_fetch_frames_measurement(m_process);
        m_fetch_modules_measurement(m_target);
        m_fetch_vars_measurement(m_process,1);
    }

	virtual ActionWanted
	TestStep (int counter)
    {
#define STEP(n) if (counter == n)
#define NEXT(s) return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWNext,SelectMyThread(s)}
#define FINISH(s) return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWFinish,SelectMyThread(s)}
#define CONT return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWContinue,SBThread()}
#define KILL return TestCase::ActionWanted{TestCase::ActionWanted::Type::eAWKill,SBThread()}
        STEP(0) {
            DoTest ();
            m_file_line_bp_measurement(m_target, "SKTDocument.m",254);
            CONT;
        }
        STEP(1) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTDocument.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"properties");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[properties description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"typeName");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"data");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[data description]");
            CONT;
        }
        STEP(2) {
            DoTest ();
            CONT;
        }
        STEP(3) {
            DoTest ();
            NEXT("SKTText.m");
        }
        STEP(4) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTText.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"layoutManager");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"contents");
            NEXT("SKTText.m");
        }
        STEP(5) {
            DoTest ();
            NEXT("SKTText.m");
        }
        STEP(6) {
            DoTest ();
            NEXT("SKTText.m");
        }
        STEP(7) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTText.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"@\"an NSString\"");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[(id)@\"an NSString\" description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"@[@1,@2,@3]");
            FINISH("SKTText.m");
        }
        STEP(8) {
            DoTest ();
            SBThread thread(SelectMyThread("SKTGraphicView.m"));
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[graphics description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"[selectionIndexes description]");
            m_run_expr_measurement(thread.GetFrameAtIndex(0),"(BOOL)NSIntersectsRect(rect, graphicDrawingBounds)");
            KILL;
        }
        KILL;
#undef STEP
#undef NEXT
#undef CONT
#undef KILL
    }

    void
    Results ()
    {
        CFCMutableArray array;
        m_fetch_frames_measurement.Write(array);
        m_file_line_bp_measurement.Write(array);
        m_fetch_modules_measurement.Write(array);
        m_fetch_vars_measurement.Write(array);
        m_run_expr_measurement.Write(array);

        CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, array.get(), kCFPropertyListXMLFormat_v1_0, 0, NULL);

        CFURLRef file = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8*)m_out_path.c_str(), m_out_path.size(), FALSE);

        CFURLWriteDataAndPropertiesToResource(file,xmlData,NULL,NULL);
    }

private:
    Measurement<lldb::perf::TimeGauge, std::function<void(SBProcess)>> m_fetch_frames_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBTarget, const char*, uint32_t)>> m_file_line_bp_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBTarget)>> m_fetch_modules_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBProcess,int)>> m_fetch_vars_measurement;
    Measurement<lldb::perf::TimeGauge, std::function<void(SBFrame,const char*)>> m_run_expr_measurement;

    SBThread
	SelectMyThread (const char* file_name)
	{
		auto threads_count = m_process.GetNumThreads();
		for (auto thread_num = 0; thread_num < threads_count; thread_num++)
		{
			SBThread thread(m_process.GetThreadAtIndex(thread_num));
			auto local_file_name = thread.GetFrameAtIndex(0).GetCompileUnit().GetFileSpec().GetFilename();
			if (!local_file_name)
				continue;
			if (strcmp(local_file_name,file_name))
				continue;
			return thread;
		}
		Xcode::RunCommand(m_debugger,"bt all",true);
		assert(false);
	}
    std::string m_app_path;
    std::string m_doc_path;
    std::string m_out_path;
};

// argv[1] == path to app
// argv[2] == path to document
// argv[3] == path to result
int main(int argc, const char * argv[])
{
    SketchTest skt;
    TestCase::Run(skt,argc,argv);
    return 0;
}

<|endoftext|>


<commit_before>#ifndef __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__
#define __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__

#include "array.hpp"

namespace MultidimensionalArray {
  template <class T>
  Array<T>::Array():
    values_(nullptr),
    deallocate_on_destruction_(true) { }

  template <class T>
  Array<T>::Array(Array const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(other.deallocate_on_destruction_) {
      if (other.deallocate_on_destruction_) {
        if (get_total_size() > 0) {
          values_ = new T[get_total_size()];
          copy(other.values_);
        }
      }
      else {
        values_ = other.values_;
        deallocate_on_destruction_ = false;
      }
    }

  template <class T>
  Array<T>::Array(Array&& other):
    size_(std::move(other.size_)),
    values_(std::move(other.values_)),
    deallocate_on_destruction_(std::move(other.deallocate_on_destruction_)) {
      other.values_ = nullptr;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Array<T2> const& other):
    Array() {
      size_ = other.get_size();
      deallocate_on_destruction_ = true;
      if (get_total_size() > 0)
        values_ = new T[get_total_size()];

      copy(other.get_pointer());
    }

  template <class T>
  Array<T>::Array(ConstArray<T> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstArray<T2> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  Array<T>::Array(View<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(View<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(ConstView<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstView<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(Size const& size):
    Array() {
      size_ = size;
      deallocate_on_destruction_ = true;

      if (get_total_size() > 0)
        values_ = new T[get_total_size()];
    }

  template <class T>
  Array<T>::Array(Size const& size, T const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Size const& size, T2 const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  Array<T>::Array(Size::SizeType const& size):
    Array(Size(size)) { }

  template <class T>
  Array<T>::Array(Size::SizeType const& size, T const* other):
    Array(Size(size), other) { }

  template <class T>
  template <class T2>
  Array<T>::Array(Size::SizeType const& size, T2 const* other):
    Array(Size(size), other) { }

  template <class T>
  Array<T>::~Array() {
    cleanup();
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array const& other) {
    assert(size_.same(other.get_size()));
    copy(other.values_);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array&& other) {
    assert(size_.same(other.get_size()));

    if (values_ != nullptr)
      delete[] values_;

    values_ = other.values_;
    other.values_ = nullptr;
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(Array<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstArray<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstArray<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(View<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(View<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstView<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstView<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  View<T> Array<T>::view() {
    return View<T>(*this);
  }

  template <class T>
  ConstView<T> Array<T>::view() const {
    return ConstView<T>(*this);
  }

  template <class T>
  bool Array<T>::resize(Size const& size, bool allow_allocation) {
    if (size.get_total_size() != get_total_size()) {
      if (!deallocate_on_destruction_)
        return false;

      if (values_) {
        delete[] values_;
        values_ = nullptr;
      }
      if (size.get_total_size() > 0 && allow_allocation)
        values_ = new T[size.get_total_size()];
    }

    size_ = size;

    return true;
  }

  template <class T>
  bool Array<T>::resize(Size::SizeType const& size, bool allow_allocation) {
    return resize(Size(size), allow_allocation);
  }

  template <class T>
  void Array<T>::set_pointer(T* p, bool responsible_for_deleting) {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    values_ = p;
    deallocate_on_destruction_ = responsible_for_deleting;
  }

  template <class T>
  template <class... Args>
  T& Array<T>::operator()(Args const&... args) {
    return values_[get_position_variadic(args...)];
  }

  template <class T>
  template <class... Args>
  T const& Array<T>::operator()(Args const&... args) const {
    return values_[get_position_variadic(args...)];
  }

  template <class T>
  T& Array<T>::get(Size::SizeType const& index) {
    assert(index.size() == size().size());
    return values_[get_position(&index[0])];
  }

  template <class T>
  T const& Array<T>::get(Size::SizeType const& index) const {
    assert(index.size() == size().size());
    return values_[get_position(&index[0])];
  }

  template <class T>
  template <class... Args>
  size_t Array<T>::get_position_variadic(Args const&... args) const {
    assert(sizeof...(args) == size().size());
    Size::SizeType::value_type indexes[] =
    {static_cast<Size::SizeType::value_type>(args)...};

    return get_position(indexes);
  }

  template <class T>
  size_t Array<T>::get_position(
      Size::SizeType::value_type const* indexes) const {
    assert(indexes != nullptr);
    assert(values_ != nullptr);
    assert(size_.check_index(indexes, size().size()));

    size_t position = indexes[0];
    for (size_t i = 0; i < size().size()-1; i++) {
      position *= size_[i+1];
      position += indexes[i+1];
    }

    return position;
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(T2 const* other) {
    assert(values_ != nullptr);
    for (size_t i = 0; i < get_total_size(); i++)
      values_[i] = other[i];
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(View<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(ConstView<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  void Array<T>::cleanup() {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    size_ = Size();
  }
};

#endif
<commit_msg>Added assertion to Array::copy.<commit_after>#ifndef __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__
#define __MULTIDIMENSIONAL_ARRAY__ARRAY_IMPL_HPP__

#include "array.hpp"

namespace MultidimensionalArray {
  template <class T>
  Array<T>::Array():
    values_(nullptr),
    deallocate_on_destruction_(true) { }

  template <class T>
  Array<T>::Array(Array const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(other.deallocate_on_destruction_) {
      if (other.deallocate_on_destruction_) {
        if (get_total_size() > 0) {
          values_ = new T[get_total_size()];
          copy(other.values_);
        }
      }
      else {
        values_ = other.values_;
        deallocate_on_destruction_ = false;
      }
    }

  template <class T>
  Array<T>::Array(Array&& other):
    size_(std::move(other.size_)),
    values_(std::move(other.values_)),
    deallocate_on_destruction_(std::move(other.deallocate_on_destruction_)) {
      other.values_ = nullptr;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Array<T2> const& other):
    Array() {
      size_ = other.get_size();
      deallocate_on_destruction_ = true;
      if (get_total_size() > 0)
        values_ = new T[get_total_size()];

      copy(other.get_pointer());
    }

  template <class T>
  Array<T>::Array(ConstArray<T> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstArray<T2> const& other):
    size_(other.size_),
    values_(nullptr),
    deallocate_on_destruction_(true) {
      if (get_total_size() > 0) {
        values_ = new T[get_total_size()];
        copy(other.values_);
      }
    }

  template <class T>
  Array<T>::Array(View<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(View<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(ConstView<T> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  template <class T2>
  Array<T>::Array(ConstView<T2> const& other):
    Array(other.get_size()) {
      *this = other;
    }

  template <class T>
  Array<T>::Array(Size const& size):
    Array() {
      size_ = size;
      deallocate_on_destruction_ = true;

      if (get_total_size() > 0)
        values_ = new T[get_total_size()];
    }

  template <class T>
  Array<T>::Array(Size const& size, T const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  template <class T2>
  Array<T>::Array(Size const& size, T2 const* other):
    Array(size) {
      copy(other);
    }

  template <class T>
  Array<T>::Array(Size::SizeType const& size):
    Array(Size(size)) { }

  template <class T>
  Array<T>::Array(Size::SizeType const& size, T const* other):
    Array(Size(size), other) { }

  template <class T>
  template <class T2>
  Array<T>::Array(Size::SizeType const& size, T2 const* other):
    Array(Size(size), other) { }

  template <class T>
  Array<T>::~Array() {
    cleanup();
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array const& other) {
    assert(size_.same(other.get_size()));
    copy(other.values_);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(Array&& other) {
    assert(size_.same(other.get_size()));

    if (values_ != nullptr)
      delete[] values_;

    values_ = other.values_;
    other.values_ = nullptr;
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(Array<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstArray<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstArray<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other.get_pointer());
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(View<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(View<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  Array<T> const& Array<T>::operator=(ConstView<T> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  template <class T2>
  Array<T> const& Array<T>::operator=(ConstView<T2> const& other) {
    assert(size_.same(other.get_size()));
    copy(other);
    return *this;
  }

  template <class T>
  View<T> Array<T>::view() {
    return View<T>(*this);
  }

  template <class T>
  ConstView<T> Array<T>::view() const {
    return ConstView<T>(*this);
  }

  template <class T>
  bool Array<T>::resize(Size const& size, bool allow_allocation) {
    if (size.get_total_size() != get_total_size()) {
      if (!deallocate_on_destruction_)
        return false;

      if (values_) {
        delete[] values_;
        values_ = nullptr;
      }
      if (size.get_total_size() > 0 && allow_allocation)
        values_ = new T[size.get_total_size()];
    }

    size_ = size;

    return true;
  }

  template <class T>
  bool Array<T>::resize(Size::SizeType const& size, bool allow_allocation) {
    return resize(Size(size), allow_allocation);
  }

  template <class T>
  void Array<T>::set_pointer(T* p, bool responsible_for_deleting) {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    values_ = p;
    deallocate_on_destruction_ = responsible_for_deleting;
  }

  template <class T>
  template <class... Args>
  T& Array<T>::operator()(Args const&... args) {
    return values_[get_position_variadic(args...)];
  }

  template <class T>
  template <class... Args>
  T const& Array<T>::operator()(Args const&... args) const {
    return values_[get_position_variadic(args...)];
  }

  template <class T>
  T& Array<T>::get(Size::SizeType const& index) {
    assert(index.size() == size().size());
    return values_[get_position(&index[0])];
  }

  template <class T>
  T const& Array<T>::get(Size::SizeType const& index) const {
    assert(index.size() == size().size());
    return values_[get_position(&index[0])];
  }

  template <class T>
  template <class... Args>
  size_t Array<T>::get_position_variadic(Args const&... args) const {
    assert(sizeof...(args) == size().size());
    Size::SizeType::value_type indexes[] =
    {static_cast<Size::SizeType::value_type>(args)...};

    return get_position(indexes);
  }

  template <class T>
  size_t Array<T>::get_position(
      Size::SizeType::value_type const* indexes) const {
    assert(indexes != nullptr);
    assert(values_ != nullptr);
    assert(size_.check_index(indexes, size().size()));

    size_t position = indexes[0];
    for (size_t i = 0; i < size().size()-1; i++) {
      position *= size_[i+1];
      position += indexes[i+1];
    }

    return position;
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(T2 const* other) {
    assert(values_ != nullptr);
    assert(other != nullptr);
    for (size_t i = 0; i < get_total_size(); i++)
      values_[i] = other[i];
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(View<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  template <class T2>
  void Array<T>::copy(ConstView<T2> const& other) {
    assert(values_ != nullptr);
    auto it1 = other.get_size().cbegin();
    auto it2 = other.get_size().cend();
    for (size_t i = 0; i < get_total_size() && it1 != it2; i++, ++it1)
      values_[i] = other.get(*it1);
  }

  template <class T>
  void Array<T>::cleanup() {
    if (values_ != nullptr && deallocate_on_destruction_) {
      delete[] values_;
      values_ = nullptr;
    }

    size_ = Size();
  }
};

#endif
<|endoftext|>


<commit_before>/*
 *
 * Author: Jeffrey Leung
 * Last edited: 2015-09-19
 *
 * This C++ header file contains the implementation of a Coordinate struct
 * used by the Labyrinth class.
 *
 */

#pragma once

struct Coordinate
{
  unsigned int x;
  unsigned int y;

  // Operator overload for ==
  bool operator==( const Coordinate& c ) const
  {
    return( x == c.x &&
            y == c.y );
  }
};
<commit_msg>Adding = overload for Coordinate.<commit_after>/*
 *
 * Author: Jeffrey Leung
 * Last edited: 2015-12-25
 *
 * This C++ header file contains the implementation of a Coordinate struct
 * used by the Labyrinth class.
 *
 */

#pragma once

struct Coordinate
{
  unsigned int x;
  unsigned int y;

  // Operator overload for ==
  bool operator==( const Coordinate& c ) const
  {
    return( x == c.x &&
            y == c.y );
  }

  // Operator overload for =
  Coordinate& operator=( const Coordinate& c )
  {
    x = c.x;
    y = c.y;
    return *this;
  }
};
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

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

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

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

#ifndef FLUSSPFERD_HPP
#define FLUSSPFERD_HPP

/**
 * @file flusspferd.hpp
 *
 * Include most Flusspferd headers.
 */

#include "flusspferd/arguments.hpp"
#include "flusspferd/array.hpp"
#include "flusspferd/binary.hpp"
#include "flusspferd/call_context.hpp"
#include "flusspferd/class.hpp"
#include "flusspferd/class_description.hpp"
#include "flusspferd/context.hpp"
#include "flusspferd/convert.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/create/array.hpp"
#include "flusspferd/create/object.hpp"
#include "flusspferd/current_context_scope.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/evaluate.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/function_adapter.hpp"
#include "flusspferd/function.hpp"
#include "flusspferd/getopt.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/init.hpp"
#include "flusspferd/load_core.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/native_function_base.hpp"
#include "flusspferd/native_function.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/properties_functions.hpp"
#include "flusspferd/property_attributes.hpp"
#include "flusspferd/property_iterator.hpp"
#include "flusspferd/root.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/system.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/value.hpp"
#include "flusspferd/value_io.hpp"
#include "flusspferd/version.hpp"

#endif
<commit_msg>new_create: add missing include to flusspferd.hpp<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

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

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

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

#ifndef FLUSSPFERD_HPP
#define FLUSSPFERD_HPP

/**
 * @file flusspferd.hpp
 *
 * Include most Flusspferd headers.
 */

#include "flusspferd/arguments.hpp"
#include "flusspferd/array.hpp"
#include "flusspferd/binary.hpp"
#include "flusspferd/call_context.hpp"
#include "flusspferd/class.hpp"
#include "flusspferd/class_description.hpp"
#include "flusspferd/context.hpp"
#include "flusspferd/convert.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/create/array.hpp"
#include "flusspferd/create/object.hpp"
#include "flusspferd/create/function.hpp"
#include "flusspferd/current_context_scope.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/evaluate.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/function_adapter.hpp"
#include "flusspferd/function.hpp"
#include "flusspferd/getopt.hpp"
#include "flusspferd/modules.hpp"
#include "flusspferd/init.hpp"
#include "flusspferd/load_core.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/native_function_base.hpp"
#include "flusspferd/native_function.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/properties_functions.hpp"
#include "flusspferd/property_attributes.hpp"
#include "flusspferd/property_iterator.hpp"
#include "flusspferd/root.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/system.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/value.hpp"
#include "flusspferd/value_io.hpp"
#include "flusspferd/version.hpp"

#endif
<|endoftext|>


<commit_before>#include <fstream>
#include <range/v3/all.hpp>

namespace triplet_match {

template <typename Point>
struct model<Point>::impl {
    impl(typename cloud_t::ConstPtr cloud, discretization_params params) : cloud_(cloud), params_(params), init_(false) {
    }

    ~impl() {}

    std::future<void>
    init(const subset_t& subset, const sample_parameters& params) {
        if (subset.empty()) {
            subset_.resize(cloud_->size());
            std::iota(subset_.begin(), subset_.end(), 0u);
        } else {
            subset_ = subset;
        }

        s_params_ = params;

        return std::async(std::launch::async, [&] () {
            this->build_model_();
        });
    }

    template <typename PointQuery>
    std::pair<triplet_iter_t, triplet_iter_t>
    query(const PointQuery& p1, const PointQuery& p2, const PointQuery& p3) {
        if (!init_) {
            throw std::runtime_error("Cannot query uninitialized model");
        }

        float lower = s_params_.min_diameter_factor * diameter_;
        float upper = s_params_.max_diameter_factor * diameter_;
        //float lower = s_params_.min_triplet_ratio;
        //float upper = s_params_.max_triplet_ratio;
        discrete_feature df = compute_discrete<PointQuery>(p1, p2, p3, params_, lower, upper-lower);

        return map_.equal_range(df);
    }

    float diameter() const {
        return diameter_;
    }

    uint32_t point_count() const {
        return point_count_;
    }

    uint64_t triplet_count() const {
        return triplet_count_;
    }

    typename cloud_t::ConstPtr cloud() const {
        return cloud_;
    }

    void
    build_model_() {
        bbox3_t bbox;
        std::set<uint32_t> valid;
        for (uint32_t i : subset_) {
            const Point& p = cloud_->points[i];
            if (pcl::isFinite(p)) {
                valid.insert(i);
                bbox.extend(p.getVector3fMap());
            }
        }
        diameter_ = (bbox.max() - bbox.min()).norm();

        float lower = s_params_.min_triplet_ratio;
        float upper = s_params_.max_triplet_ratio;
        float lower_radius = s_params_.min_diameter_factor * diameter_;
        float upper_radius = s_params_.max_diameter_factor * diameter_;
        //float range = upper-lower;
        triplet_count_ = 0;
        for (uint32_t i : valid) {
            const Point& p1 = cloud_->points[i];

            for (uint32_t j : valid) {
                const Point& p2 = cloud_->points[j];
                if (i == j) {
                    continue;
                }

                vec3f_t d1 = p2.getVector3fMap() - p1.getVector3fMap();
                float dist1 = d1.norm();
                if (dist1 < lower_radius || dist1 > upper_radius) {
                    continue;
                }

                for (uint32_t k : valid) {
                    const Point& p3 = cloud_->points[k];
                    if (i == k || j == k) {
                        continue;
                    }

                    vec3f_t d2 = (p3.getVector3fMap() - p2.getVector3fMap());
                    vec3f_t d3 = (p3.getVector3fMap() - p1.getVector3fMap());
                    float dist2 = d2.norm();
                    float dist3 = d3.norm();
                    if (dist2 < lower_radius || dist2 > upper_radius || dist3 < lower_radius || dist3 > upper_radius) {
                        continue;
                    }
                    //float rat0 = dist2 / dist1;
                    //float rat1 = dist3 / dist1;
                    //if (rat0 < lower || rat0 > upper || rat1 < lower || rat1 > upper) {
                        //continue;
                    //}

                    ++triplet_count_;

                    used_points_.insert(i);
                    used_points_.insert(j);
                    used_points_.insert(k);
                    discrete_feature df = compute_discrete<Point>(p1, p2, p3, params_, lower_radius, upper_radius - lower_radius);

                    map_.insert({df, triplet_t{i, j, k}});
                }
            }
        }

        point_count_ = valid.size();
        init_ = true;
    }

    typename cloud_t::ConstPtr cloud_;
    discretization_params params_;
    bool init_;

    subset_t subset_;
    sample_parameters s_params_;
    hash_map_t map_;
    float diameter_;
    uint32_t point_count_;
    uint64_t triplet_count_;
    std::set<uint32_t> used_points_;
};

template <typename Point>
inline
model<Point>::model(typename cloud_t::ConstPtr cloud, discretization_params params) {
    impl_ = std::make_unique<impl>(cloud, params);
}

template <typename Point>
inline
model<Point>::~model() {
}

template <typename Point>
inline std::future<void>
model<Point>::init(const sample_parameters& sample_params) {
    return impl_->init(subset_t(), sample_params);
}

template <typename Point>
inline std::future<void>
model<Point>::init(const subset_t& subset, const sample_parameters& sample_params) {
    return impl_->init(subset, sample_params);
}

template <typename Point>
template <typename PointQuery>
inline std::pair<typename model<Point>::triplet_iter_t, typename model<Point>::triplet_iter_t>
model<Point>::query(const PointQuery& p1, const PointQuery& p2, const PointQuery& p3) {
    return range<triplet_iter_t>(impl_->template query<PointQuery>(p1, p2, p3));
}

template <typename Point>
inline float
model<Point>::diameter() const {
    return impl_->diameter();
}

template <typename Point>
inline uint32_t
model<Point>::point_count() const {
    return impl_->point_count();
}

template <typename Point>
inline uint64_t
model<Point>::triplet_count() const {
    return impl_->triplet_count();
}

template <typename Point>
inline typename model<Point>::cloud_t::ConstPtr
model<Point>::cloud() const {
    return impl_->cloud();
}

template <typename Point>
inline std::set<uint32_t>
model<Point>::used_points() const {
    return impl_->used_points_;
}

template <typename Point>
void
model<Point>::write_octave_density_maps(const std::string& folder, const std::string& data_file_prefix, const std::string& script_file) const {
    const discretization_params& ps = impl_->params_;
    const hash_map_t& map = impl_->map_;

    const float max_angle = static_cast<float>(M_PI);
    const uint32_t angle_count = static_cast<uint32_t>(max_angle / ps.angle_step) + 1;
    const uint32_t dist_count = static_cast<uint32_t>(ps.distance_step_count);

    std::vector<std::vector<uint32_t>> hists(5);
    hists[0] = std::vector<uint32_t>(dist_count, 0);
    hists[1] = std::vector<uint32_t>(dist_count, 0);
    hists[2] = std::vector<uint32_t>(angle_count, 0);
    hists[3] = std::vector<uint32_t>(angle_count, 0);
    hists[4] = std::vector<uint32_t>(angle_count, 0);
    auto missing_dims = ranges::view::cartesian_product(
        ranges::view::ints(0u, dist_count),
        ranges::view::ints(0u, dist_count),
        ranges::view::ints(0u, angle_count),
        ranges::view::ints(0u, angle_count),
        ranges::view::ints(0u, angle_count)
    );
    for (auto && [a,b,c,d,e] : missing_dims) {
        discrete_feature feat;
        feat[0] = a;
        feat[1] = b;
        feat[2] = c;
        feat[3] = d;
        feat[4] = e;
        auto && [fst,lst] = map.equal_range(feat);
        uint32_t count = std::distance(fst, lst);
        hists[0][a] += count;
        hists[1][b] += count;
        hists[2][c] += count;
        hists[3][d] += count;
        hists[4][e] += count;
    }

    auto name = [&] (uint32_t i) { return data_file_prefix + "_" + std::to_string(i); };

    std::ofstream out;
    for (uint32_t i = 0; i < 5; ++i) {
        out.open(folder + "/" + name(i) + ".dat");
        for (const auto& count : hists[i]) {
            out << count << "\n";
        }
        out.close();
    }

    out.open(folder + "/" + script_file);
    for (uint32_t i = 0; i < 5; ++i) {
        out << "load " << name(i) << ".dat" << "\n";
        out << "figure(" << (i+1) << ")" << "\n";
        out << "plot(0:numel(" << name(i) << ")-1, " << name(i) << ", '-')" << "\n";
    }
    out.close();
}

}  // namespace triplet_match
<commit_msg>compare commit<commit_after>#include <fstream>
#include <range/v3/all.hpp>

namespace triplet_match {

template <typename Point>
struct model<Point>::impl {
    impl(typename cloud_t::ConstPtr cloud, discretization_params params) : cloud_(cloud), params_(params), init_(false) {
    }

    ~impl() {}

    std::future<void>
    init(const subset_t& subset, const sample_parameters& params) {
        if (subset.empty()) {
            subset_.resize(cloud_->size());
            std::iota(subset_.begin(), subset_.end(), 0u);
        } else {
            subset_ = subset;
        }

        s_params_ = params;

        return std::async(std::launch::async, [&] () {
            this->build_model_();
        });
    }

    template <typename PointQuery>
    std::pair<triplet_iter_t, triplet_iter_t>
    query(const PointQuery& p1, const PointQuery& p2, const PointQuery& p3) {
        if (!init_) {
            throw std::runtime_error("Cannot query uninitialized model");
        }

        float lower = s_params_.min_diameter_factor * diameter_;
        float upper = s_params_.max_diameter_factor * diameter_;
        //float lower = s_params_.min_triplet_ratio;
        //float upper = s_params_.max_triplet_ratio;
        discrete_feature df = compute_discrete<PointQuery>(p1, p2, p3, params_, lower, upper-lower);

        return map_.equal_range(df);
    }

    float diameter() const {
        return diameter_;
    }

    uint32_t point_count() const {
        return point_count_;
    }

    uint64_t triplet_count() const {
        return triplet_count_;
    }

    typename cloud_t::ConstPtr cloud() const {
        return cloud_;
    }

    void
    build_model_() {
        bbox3_t bbox;
        std::set<uint32_t> valid;
        for (uint32_t i : subset_) {
            const Point& p = cloud_->points[i];
            if (pcl::isFinite(p)) {
                valid.insert(i);
                bbox.extend(p.getVector3fMap());
            }
        }
        diameter_ = (bbox.max() - bbox.min()).norm();

        //float lower = s_params_.min_triplet_ratio;
        //float upper = s_params_.max_triplet_ratio;
        float lower_radius = s_params_.min_diameter_factor * diameter_;
        float upper_radius = s_params_.max_diameter_factor * diameter_;
        //float range = upper-lower;
        triplet_count_ = 0;
        for (uint32_t i : valid) {
            const Point& p1 = cloud_->points[i];

            for (uint32_t j : valid) {
                const Point& p2 = cloud_->points[j];
                if (i == j) {
                    continue;
                }

                vec3f_t d1 = p2.getVector3fMap() - p1.getVector3fMap();
                float dist1 = d1.norm();
                if (dist1 < lower_radius || dist1 > upper_radius) {
                    continue;
                }

                for (uint32_t k : valid) {
                    const Point& p3 = cloud_->points[k];
                    if (i == k || j == k) {
                        continue;
                    }

                    vec3f_t d2 = (p3.getVector3fMap() - p2.getVector3fMap());
                    vec3f_t d3 = (p3.getVector3fMap() - p1.getVector3fMap());
                    float dist2 = d2.norm();
                    float dist3 = d3.norm();
                    if (dist2 < lower_radius || dist2 > upper_radius || dist3 < lower_radius || dist3 > upper_radius) {
                        continue;
                    }
                    //float rat0 = dist2 / dist1;
                    //float rat1 = dist3 / dist1;
                    //if (rat0 < lower || rat0 > upper || rat1 < lower || rat1 > upper) {
                        //continue;
                    //}

                    ++triplet_count_;

                    used_points_.insert(i);
                    used_points_.insert(j);
                    used_points_.insert(k);
                    discrete_feature df = compute_discrete<Point>(p1, p2, p3, params_, lower_radius, upper_radius - lower_radius);

                    map_.insert({df, triplet_t{i, j, k}});
                }
            }
        }

        point_count_ = valid.size();
        init_ = true;
    }

    typename cloud_t::ConstPtr cloud_;
    discretization_params params_;
    bool init_;

    subset_t subset_;
    sample_parameters s_params_;
    hash_map_t map_;
    float diameter_;
    uint32_t point_count_;
    uint64_t triplet_count_;
    std::set<uint32_t> used_points_;
};

template <typename Point>
inline
model<Point>::model(typename cloud_t::ConstPtr cloud, discretization_params params) {
    impl_ = std::make_unique<impl>(cloud, params);
}

template <typename Point>
inline
model<Point>::~model() {
}

template <typename Point>
inline std::future<void>
model<Point>::init(const sample_parameters& sample_params) {
    return impl_->init(subset_t(), sample_params);
}

template <typename Point>
inline std::future<void>
model<Point>::init(const subset_t& subset, const sample_parameters& sample_params) {
    return impl_->init(subset, sample_params);
}

template <typename Point>
template <typename PointQuery>
inline std::pair<typename model<Point>::triplet_iter_t, typename model<Point>::triplet_iter_t>
model<Point>::query(const PointQuery& p1, const PointQuery& p2, const PointQuery& p3) {
    return range<triplet_iter_t>(impl_->template query<PointQuery>(p1, p2, p3));
}

template <typename Point>
inline float
model<Point>::diameter() const {
    return impl_->diameter();
}

template <typename Point>
inline uint32_t
model<Point>::point_count() const {
    return impl_->point_count();
}

template <typename Point>
inline uint64_t
model<Point>::triplet_count() const {
    return impl_->triplet_count();
}

template <typename Point>
inline typename model<Point>::cloud_t::ConstPtr
model<Point>::cloud() const {
    return impl_->cloud();
}

template <typename Point>
inline std::set<uint32_t>
model<Point>::used_points() const {
    return impl_->used_points_;
}

template <typename Point>
void
model<Point>::write_octave_density_maps(const std::string& folder, const std::string& data_file_prefix, const std::string& script_file) const {
    const discretization_params& ps = impl_->params_;
    const hash_map_t& map = impl_->map_;

    const float max_angle = static_cast<float>(M_PI);
    const uint32_t angle_count = static_cast<uint32_t>(max_angle / ps.angle_step) + 1;
    const uint32_t dist_count = static_cast<uint32_t>(ps.distance_step_count);

    std::vector<std::vector<uint32_t>> hists(5);
    hists[0] = std::vector<uint32_t>(dist_count, 0);
    hists[1] = std::vector<uint32_t>(dist_count, 0);
    hists[2] = std::vector<uint32_t>(angle_count, 0);
    hists[3] = std::vector<uint32_t>(angle_count, 0);
    hists[4] = std::vector<uint32_t>(angle_count, 0);
    auto missing_dims = ranges::view::cartesian_product(
        ranges::view::ints(0u, dist_count),
        ranges::view::ints(0u, dist_count),
        ranges::view::ints(0u, angle_count),
        ranges::view::ints(0u, angle_count),
        ranges::view::ints(0u, angle_count)
    );
    for (auto && [a,b,c,d,e] : missing_dims) {
        discrete_feature feat;
        feat[0] = a;
        feat[1] = b;
        feat[2] = c;
        feat[3] = d;
        feat[4] = e;
        auto && [fst,lst] = map.equal_range(feat);
        uint32_t count = std::distance(fst, lst);
        hists[0][a] += count;
        hists[1][b] += count;
        hists[2][c] += count;
        hists[3][d] += count;
        hists[4][e] += count;
    }

    auto name = [&] (uint32_t i) { return data_file_prefix + "_" + std::to_string(i); };

    std::ofstream out;
    for (uint32_t i = 0; i < 5; ++i) {
        out.open(folder + "/" + name(i) + ".dat");
        for (const auto& count : hists[i]) {
            out << count << "\n";
        }
        out.close();
    }

    out.open(folder + "/" + script_file);
    for (uint32_t i = 0; i < 5; ++i) {
        out << "load " << name(i) << ".dat" << "\n";
        out << "figure(" << (i+1) << ")" << "\n";
        out << "plot(0:numel(" << name(i) << ")-1, " << name(i) << ", '-')" << "\n";
    }
    out.close();
}

}  // namespace triplet_match
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif

#include "main.h"

#define EIGEN_TESTMAP_MAX_SIZE 256

template<typename VectorType> void map_class_vector(const VectorType& m)
{
  typedef typename VectorType::Index Index;
  typedef typename VectorType::Scalar Scalar;

  Index size = m.size();

  // test Map.h
  Scalar* array1 = internal::aligned_new<Scalar>(size);
  Scalar* array2 = internal::aligned_new<Scalar>(size);
  Scalar* array3 = new Scalar[size+1];
  Scalar* array3unaligned = size_t(array3)%EIGEN_ALIGN_BYTES == 0 ? array3+1 : array3;
  Scalar  array4[EIGEN_TESTMAP_MAX_SIZE];

  Map<VectorType, Aligned>(array1, size) = VectorType::Random(size);
  Map<VectorType, Aligned>(array2, size) = Map<VectorType,Aligned>(array1, size);
  Map<VectorType>(array3unaligned, size) = Map<VectorType>(array1, size);
  Map<VectorType>(array4, size)          = Map<VectorType,Aligned>(array1, size);
  VectorType ma1 = Map<VectorType, Aligned>(array1, size);
  VectorType ma2 = Map<VectorType, Aligned>(array2, size);
  VectorType ma3 = Map<VectorType>(array3unaligned, size);
  VectorType ma4 = Map<VectorType>(array4, size);
  VERIFY_IS_EQUAL(ma1, ma2);
  VERIFY_IS_EQUAL(ma1, ma3);
  VERIFY_IS_EQUAL(ma1, ma4);
  #ifdef EIGEN_VECTORIZE
  if(internal::packet_traits<Scalar>::Vectorizable)
    VERIFY_RAISES_ASSERT((Map<VectorType,Aligned>(array3unaligned, size)))
  #endif

  internal::aligned_delete(array1, size);
  internal::aligned_delete(array2, size);
  delete[] array3;
}

template<typename MatrixType> void map_class_matrix(const MatrixType& m)
{
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;

  Index rows = m.rows(), cols = m.cols(), size = rows*cols;

  // test Map.h
  Scalar* array1 = internal::aligned_new<Scalar>(size);
  for(int i = 0; i < size; i++) array1[i] = Scalar(1);
  Scalar* array2 = internal::aligned_new<Scalar>(size);
  for(int i = 0; i < size; i++) array2[i] = Scalar(1);
  Scalar* array3 = new Scalar[size+1];
  for(int i = 0; i < size+1; i++) array3[i] = Scalar(1);
  Scalar* array3unaligned = size_t(array3)%EIGEN_ALIGN_BYTES == 0 ? array3+1 : array3;
  Map<MatrixType, Aligned>(array1, rows, cols) = MatrixType::Ones(rows,cols);
  Map<MatrixType>(array2, rows, cols) = Map<MatrixType>(array1, rows, cols);
  Map<MatrixType>(array3unaligned, rows, cols) = Map<MatrixType>(array1, rows, cols);
  MatrixType ma1 = Map<MatrixType>(array1, rows, cols);
  MatrixType ma2 = Map<MatrixType, Aligned>(array2, rows, cols);
  VERIFY_IS_EQUAL(ma1, ma2);
  MatrixType ma3 = Map<MatrixType>(array3unaligned, rows, cols);
  VERIFY_IS_EQUAL(ma1, ma3);

  internal::aligned_delete(array1, size);
  internal::aligned_delete(array2, size);
  delete[] array3;
}

template<typename VectorType> void map_static_methods(const VectorType& m)
{
  typedef typename VectorType::Index Index;
  typedef typename VectorType::Scalar Scalar;

  Index size = m.size();

  // test Map.h
  Scalar* array1 = internal::aligned_new<Scalar>(size);
  Scalar* array2 = internal::aligned_new<Scalar>(size);
  Scalar* array3 = new Scalar[size+1];
  Scalar* array3unaligned = size_t(array3)%EIGEN_ALIGN_BYTES == 0 ? array3+1 : array3;

  VectorType::MapAligned(array1, size) = VectorType::Random(size);
  VectorType::Map(array2, size) = VectorType::Map(array1, size);
  VectorType::Map(array3unaligned, size) = VectorType::Map(array1, size);
  VectorType ma1 = VectorType::Map(array1, size);
  VectorType ma2 = VectorType::MapAligned(array2, size);
  VectorType ma3 = VectorType::Map(array3unaligned, size);
  VERIFY_IS_EQUAL(ma1, ma2);
  VERIFY_IS_EQUAL(ma1, ma3);

  internal::aligned_delete(array1, size);
  internal::aligned_delete(array2, size);
  delete[] array3;
}

template<typename PlainObjectType> void check_const_correctness(const PlainObjectType&)
{
  // there's a lot that we can't test here while still having this test compile!
  // the only possible approach would be to run a script trying to compile stuff and checking that it fails.
  // CMake can help with that.

  // verify that map-to-const don't have LvalueBit
  typedef typename internal::add_const<PlainObjectType>::type ConstPlainObjectType;
  VERIFY( !(internal::traits<Map<ConstPlainObjectType> >::Flags & LvalueBit) );
  VERIFY( !(internal::traits<Map<ConstPlainObjectType, Aligned> >::Flags & LvalueBit) );
  VERIFY( !(Map<ConstPlainObjectType>::Flags & LvalueBit) );
  VERIFY( !(Map<ConstPlainObjectType, Aligned>::Flags & LvalueBit) );
}

void test_mapped_matrix()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( map_class_vector(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_1( check_const_correctness(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( map_class_vector(Vector4d()) );
    CALL_SUBTEST_2( map_class_vector(VectorXd(13)) );
    CALL_SUBTEST_2( check_const_correctness(Matrix4d()) );
    CALL_SUBTEST_3( map_class_vector(RowVector4f()) );
    CALL_SUBTEST_4( map_class_vector(VectorXcf(8)) );
    CALL_SUBTEST_5( map_class_vector(VectorXi(12)) );
    CALL_SUBTEST_5( check_const_correctness(VectorXi(12)) );

    CALL_SUBTEST_1( map_class_matrix(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( map_class_matrix(Matrix4d()) );
    CALL_SUBTEST_11( map_class_matrix(Matrix<float,3,5>()) );
    CALL_SUBTEST_4( map_class_matrix(MatrixXcf(internal::random<int>(1,10),internal::random<int>(1,10))) );
    CALL_SUBTEST_5( map_class_matrix(MatrixXi(internal::random<int>(1,10),internal::random<int>(1,10))) );

    CALL_SUBTEST_6( map_static_methods(Matrix<double, 1, 1>()) );
    CALL_SUBTEST_7( map_static_methods(Vector3f()) );
    CALL_SUBTEST_8( map_static_methods(RowVector3d()) );
    CALL_SUBTEST_9( map_static_methods(VectorXcd(8)) );
    CALL_SUBTEST_10( map_static_methods(VectorXf(12)) );
  }
}
<commit_msg>Extend unit test of Map<> with stack allocated buffers and less trivial operations.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif

#include "main.h"

#define EIGEN_TESTMAP_MAX_SIZE 256

template<typename VectorType> void map_class_vector(const VectorType& m)
{
  typedef typename VectorType::Index Index;
  typedef typename VectorType::Scalar Scalar;

  Index size = m.size();

  Scalar* array1 = internal::aligned_new<Scalar>(size);
  Scalar* array2 = internal::aligned_new<Scalar>(size);
  Scalar* array3 = new Scalar[size+1];
  Scalar* array3unaligned = size_t(array3)%EIGEN_ALIGN_BYTES == 0 ? array3+1 : array3;
  Scalar  array4[EIGEN_TESTMAP_MAX_SIZE];

  Map<VectorType, Aligned>(array1, size) = VectorType::Random(size);
  Map<VectorType, Aligned>(array2, size) = Map<VectorType,Aligned>(array1, size);
  Map<VectorType>(array3unaligned, size) = Map<VectorType>(array1, size);
  Map<VectorType>(array4, size)          = Map<VectorType,Aligned>(array1, size);
  VectorType ma1 = Map<VectorType, Aligned>(array1, size);
  VectorType ma2 = Map<VectorType, Aligned>(array2, size);
  VectorType ma3 = Map<VectorType>(array3unaligned, size);
  VectorType ma4 = Map<VectorType>(array4, size);
  VERIFY_IS_EQUAL(ma1, ma2);
  VERIFY_IS_EQUAL(ma1, ma3);
  VERIFY_IS_EQUAL(ma1, ma4);
  #ifdef EIGEN_VECTORIZE
  if(internal::packet_traits<Scalar>::Vectorizable)
    VERIFY_RAISES_ASSERT((Map<VectorType,Aligned>(array3unaligned, size)))
  #endif

  internal::aligned_delete(array1, size);
  internal::aligned_delete(array2, size);
  delete[] array3;
}

template<typename MatrixType> void map_class_matrix(const MatrixType& m)
{
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;

  Index rows = m.rows(), cols = m.cols(), size = rows*cols;
  Scalar s1 = internal::random<Scalar>();

  // array1 and array2 -> aligned heap allocation
  Scalar* array1 = internal::aligned_new<Scalar>(size);
  for(int i = 0; i < size; i++) array1[i] = Scalar(1);
  Scalar* array2 = internal::aligned_new<Scalar>(size);
  for(int i = 0; i < size; i++) array2[i] = Scalar(1);
  // array3unaligned -> unaligned pointer to heap
  Scalar* array3 = new Scalar[size+1];
  for(int i = 0; i < size+1; i++) array3[i] = Scalar(1);
  Scalar* array3unaligned = size_t(array3)%EIGEN_ALIGN_BYTES == 0 ? array3+1 : array3;
  Scalar array4[256];
  if(size<=256)
    for(int i = 0; i < size; i++) array4[i] = Scalar(1);

  Map<MatrixType> map1(array1, rows, cols);
  Map<MatrixType, Aligned> map2(array2, rows, cols);
  Map<MatrixType> map3(array3unaligned, rows, cols);
  Map<MatrixType> map4(array4, rows, cols);

  VERIFY_IS_EQUAL(map1, MatrixType::Ones(rows,cols));
  VERIFY_IS_EQUAL(map2, MatrixType::Ones(rows,cols));
  VERIFY_IS_EQUAL(map3, MatrixType::Ones(rows,cols));
  map1 = MatrixType::Random(rows,cols);
  map2 = map1;
  map3 = map1;
  MatrixType ma1 = map1;
  MatrixType ma2 = map2;
  MatrixType ma3 = map3;
  VERIFY_IS_EQUAL(map1, map2);
  VERIFY_IS_EQUAL(map1, map3);
  VERIFY_IS_EQUAL(ma1, ma2);
  VERIFY_IS_EQUAL(ma1, ma3);
  VERIFY_IS_EQUAL(ma1, map3);

  VERIFY_IS_APPROX(s1*map1, s1*map2);
  VERIFY_IS_APPROX(s1*ma1, s1*ma2);
  VERIFY_IS_EQUAL(s1*ma1, s1*ma3);
  VERIFY_IS_APPROX(s1*map1, s1*map3);

  map2 *= s1;
  map3 *= s1;
  VERIFY_IS_APPROX(s1*map1, map2);
  VERIFY_IS_APPROX(s1*map1, map3);

  if(size<=256)
  {
    VERIFY_IS_EQUAL(map4, MatrixType::Ones(rows,cols));
    map4 = map1;
    MatrixType ma4 = map4;
    VERIFY_IS_EQUAL(map1, map4);
    VERIFY_IS_EQUAL(ma1, map4);
    VERIFY_IS_EQUAL(ma1, ma4);
    VERIFY_IS_APPROX(s1*map1, s1*map4);

    map4 *= s1;
    VERIFY_IS_APPROX(s1*map1, map4);
  }

  internal::aligned_delete(array1, size);
  internal::aligned_delete(array2, size);
  delete[] array3;
}

template<typename VectorType> void map_static_methods(const VectorType& m)
{
  typedef typename VectorType::Index Index;
  typedef typename VectorType::Scalar Scalar;

  Index size = m.size();

  Scalar* array1 = internal::aligned_new<Scalar>(size);
  Scalar* array2 = internal::aligned_new<Scalar>(size);
  Scalar* array3 = new Scalar[size+1];
  Scalar* array3unaligned = size_t(array3)%EIGEN_ALIGN_BYTES == 0 ? array3+1 : array3;

  VectorType::MapAligned(array1, size) = VectorType::Random(size);
  VectorType::Map(array2, size) = VectorType::Map(array1, size);
  VectorType::Map(array3unaligned, size) = VectorType::Map(array1, size);
  VectorType ma1 = VectorType::Map(array1, size);
  VectorType ma2 = VectorType::MapAligned(array2, size);
  VectorType ma3 = VectorType::Map(array3unaligned, size);
  VERIFY_IS_EQUAL(ma1, ma2);
  VERIFY_IS_EQUAL(ma1, ma3);

  internal::aligned_delete(array1, size);
  internal::aligned_delete(array2, size);
  delete[] array3;
}

template<typename PlainObjectType> void check_const_correctness(const PlainObjectType&)
{
  // there's a lot that we can't test here while still having this test compile!
  // the only possible approach would be to run a script trying to compile stuff and checking that it fails.
  // CMake can help with that.

  // verify that map-to-const don't have LvalueBit
  typedef typename internal::add_const<PlainObjectType>::type ConstPlainObjectType;
  VERIFY( !(internal::traits<Map<ConstPlainObjectType> >::Flags & LvalueBit) );
  VERIFY( !(internal::traits<Map<ConstPlainObjectType, Aligned> >::Flags & LvalueBit) );
  VERIFY( !(Map<ConstPlainObjectType>::Flags & LvalueBit) );
  VERIFY( !(Map<ConstPlainObjectType, Aligned>::Flags & LvalueBit) );
}

void test_mapped_matrix()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( map_class_vector(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_1( check_const_correctness(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( map_class_vector(Vector4d()) );
    CALL_SUBTEST_2( map_class_vector(VectorXd(13)) );
    CALL_SUBTEST_2( check_const_correctness(Matrix4d()) );
    CALL_SUBTEST_3( map_class_vector(RowVector4f()) );
    CALL_SUBTEST_4( map_class_vector(VectorXcf(8)) );
    CALL_SUBTEST_5( map_class_vector(VectorXi(12)) );
    CALL_SUBTEST_5( check_const_correctness(VectorXi(12)) );

    CALL_SUBTEST_1( map_class_matrix(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( map_class_matrix(Matrix4d()) );
    CALL_SUBTEST_11( map_class_matrix(Matrix<float,3,5>()) );
    CALL_SUBTEST_4( map_class_matrix(MatrixXcf(internal::random<int>(1,10),internal::random<int>(1,10))) );
    CALL_SUBTEST_5( map_class_matrix(MatrixXi(internal::random<int>(1,10),internal::random<int>(1,10))) );

    CALL_SUBTEST_6( map_static_methods(Matrix<double, 1, 1>()) );
    CALL_SUBTEST_7( map_static_methods(Vector3f()) );
    CALL_SUBTEST_8( map_static_methods(RowVector3d()) );
    CALL_SUBTEST_9( map_static_methods(VectorXcd(8)) );
    CALL_SUBTEST_10( map_static_methods(VectorXf(12)) );
  }
}
<|endoftext|>