<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AccessiblePresentationShape.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:27:39 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX
#include "AccessiblePresentationShape.hxx"
#endif

#include "SdShapeTypes.hxx"

#include <svx/DescriptionGenerator.hxx>
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessiblePresentationShape::AccessiblePresentationShape (
    const AccessibleShapeInfo& rShapeInfo,
    const AccessibleShapeTreeInfo& rShapeTreeInfo)
    : AccessibleShape (rShapeInfo, rShapeTreeInfo)
{
}

AccessiblePresentationShape::~AccessiblePresentationShape (void)
{
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessiblePresentationShape::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessiblePresentationShape"));
}

/// Set this object's name if is different to the current name.
::rtl::OUString
    AccessiblePresentationShape::CreateAccessibleBaseName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::rtl::OUString sName;

    ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
    switch (nShapeType)
    {
        case PRESENTATION_TITLE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressTitle"));
            break;
        case PRESENTATION_OUTLINER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressOutliner"));
            break;
        case PRESENTATION_SUBTITLE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressSubtitle"));
            break;
        case PRESENTATION_PAGE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPage"));
            break;
        case PRESENTATION_NOTES:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressNotes"));
            break;
        case PRESENTATION_HANDOUT:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHandout"));
            break;
        case PRESENTATION_HEADER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHeader"));
            break;
        case PRESENTATION_FOOTER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressFooter"));
            break;
        case PRESENTATION_DATETIME:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressDateAndTime"));
            break;
        case PRESENTATION_PAGENUMBER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPageNumber"));
            break;
        default:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleImpressShape"));
            uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
            if (xDescriptor.is())
                sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": "))
                    + xDescriptor->getShapeType();
    }

    return sName;
}

::rtl::OUString
    AccessiblePresentationShape::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    //    return createAccessibleName ();
    DescriptionGenerator aDG (mxShape);
    ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
    switch (nShapeType)
    {
        case PRESENTATION_TITLE:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationTitleShape"));
            break;
        case PRESENTATION_OUTLINER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationOutlinerShape"));
            break;
        case PRESENTATION_SUBTITLE:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationSubtitleShape"));
            break;
        case PRESENTATION_PAGE:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageShape"));
            break;
        case PRESENTATION_NOTES:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationNotesShape"));
            break;
        case PRESENTATION_HANDOUT:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHandoutShape"));
            break;
        case PRESENTATION_HEADER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHeaderShape"));
            break;
        case PRESENTATION_FOOTER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationFooterShape"));
            break;
        case PRESENTATION_DATETIME:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationDateAndTimeShape"));
            break;
        case PRESENTATION_PAGENUMBER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageNumberShape"));
            break;
        default:
            aDG.Initialize (::rtl::OUString::createFromAscii ("Unknown accessible presentation shape"));
            uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
            if (xDescriptor.is())
            {
                aDG.AppendString (::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("service name=")));
                aDG.AppendString (xDescriptor->getShapeType());
            }
    }

    return aDG();
}

} // end of namespace accessibility
<commit_msg>INTEGRATION: CWS pchfix02 (1.16.282); FILE MERGED 2006/09/01 17:36:50 kaib 1.16.282.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AccessiblePresentationShape.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:25:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX
#include "AccessiblePresentationShape.hxx"
#endif

#include "SdShapeTypes.hxx"

#include <svx/DescriptionGenerator.hxx>
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessiblePresentationShape::AccessiblePresentationShape (
    const AccessibleShapeInfo& rShapeInfo,
    const AccessibleShapeTreeInfo& rShapeTreeInfo)
    : AccessibleShape (rShapeInfo, rShapeTreeInfo)
{
}

AccessiblePresentationShape::~AccessiblePresentationShape (void)
{
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessiblePresentationShape::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessiblePresentationShape"));
}

/// Set this object's name if is different to the current name.
::rtl::OUString
    AccessiblePresentationShape::CreateAccessibleBaseName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    ::rtl::OUString sName;

    ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
    switch (nShapeType)
    {
        case PRESENTATION_TITLE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressTitle"));
            break;
        case PRESENTATION_OUTLINER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressOutliner"));
            break;
        case PRESENTATION_SUBTITLE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressSubtitle"));
            break;
        case PRESENTATION_PAGE:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPage"));
            break;
        case PRESENTATION_NOTES:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressNotes"));
            break;
        case PRESENTATION_HANDOUT:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHandout"));
            break;
        case PRESENTATION_HEADER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressHeader"));
            break;
        case PRESENTATION_FOOTER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressFooter"));
            break;
        case PRESENTATION_DATETIME:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressDateAndTime"));
            break;
        case PRESENTATION_PAGENUMBER:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("ImpressPageNumber"));
            break;
        default:
            sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleImpressShape"));
            uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
            if (xDescriptor.is())
                sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": "))
                    + xDescriptor->getShapeType();
    }

    return sName;
}

::rtl::OUString
    AccessiblePresentationShape::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    //    return createAccessibleName ();
    DescriptionGenerator aDG (mxShape);
    ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape);
    switch (nShapeType)
    {
        case PRESENTATION_TITLE:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationTitleShape"));
            break;
        case PRESENTATION_OUTLINER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationOutlinerShape"));
            break;
        case PRESENTATION_SUBTITLE:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationSubtitleShape"));
            break;
        case PRESENTATION_PAGE:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageShape"));
            break;
        case PRESENTATION_NOTES:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationNotesShape"));
            break;
        case PRESENTATION_HANDOUT:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHandoutShape"));
            break;
        case PRESENTATION_HEADER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationHeaderShape"));
            break;
        case PRESENTATION_FOOTER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationFooterShape"));
            break;
        case PRESENTATION_DATETIME:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationDateAndTimeShape"));
            break;
        case PRESENTATION_PAGENUMBER:
            aDG.Initialize (::rtl::OUString::createFromAscii ("PresentationPageNumberShape"));
            break;
        default:
            aDG.Initialize (::rtl::OUString::createFromAscii ("Unknown accessible presentation shape"));
            uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY);
            if (xDescriptor.is())
            {
                aDG.AppendString (::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("service name=")));
                aDG.AppendString (xDescriptor->getShapeType());
            }
    }

    return aDG();
}

} // end of namespace accessibility
<|endoftext|>


<commit_before>

#include <iostream>
//#include <boost/bind.hpp>
//
//#include <boost/test/included/unit_test.hpp>

#include <FFLLAPI.h>
#include <DefuzzVarObj.h>
#include <FFLLBase.h>
#include <FuzzyModelBase.h>
#include <FuzzyVariableBase.h>
#include <FuzzyOutVariable.h>
#include <RuleArray.h>
#include <MemberFuncTrap.h>
#include <MemberFuncTri.h>
#include <MemberFuncSCurve.h>
#include <MemberFuncSingle.h>
#include <FuzzySetBase.h>

int main( int argc, char* argv[] )
{
	FuzzyModelBase* testModel = new FuzzyModelBase();// = new FuzzyModelBase();
	testModel->init(); //create model with empty rule array
	//const Char* c = model->get_model_name();

	testModel->FuzzyModelBase::set_defuzz_method(0); // set DEFUZZ_COG method
	testModel->FuzzyModelBase::set_inference_method(0);
	testModel->FuzzyModelBase::set_composition_method(0);

	//FuzzyModelBase* pmodel = &model;

	std::wstring name1(L"inputVariable1");
	const wchar_t* szInputVariable1 = name1.c_str();

	std::wstring name2(L"outVariable1");
	const wchar_t* szOutVariable1 = name2.c_str();

	std::wstring name3(L"inputVariable2");
	const wchar_t* szInputVariable2 = name3.c_str();

	std::wstring nameSet(L"set1Var1");
	wchar_t* wset_name1 = convert_to_wide_char("set1Var1");

	FuzzyVariableBase* inputVar1 = new FuzzyVariableBase(testModel);// create new inputVar
	int i = inputVar1->init(szInputVariable1, 34.5, 45.3, true);//left x value, right x value? 	// if no name is passed in name it "Variable 0"
	inputVar1->add_set(inputVar1->new_set(wset_name1,25,inputVar1,0,30,2));

	inputVar1->set_x_array_count(100);
//	inputVar1->set_right_x(25);
//	inputVar1->set_ramp(1,0,0);
	//inputVar1->set_dom_array_count(20);
//	inputVar1->set_left_x(0);

//	ASSERT(i == -1);
	FuzzyVariableBase* inputVar2  = new FuzzyVariableBase(testModel);
	int k = inputVar2->init(szInputVariable2, 34.5, 45.3, true);
//	ASSERT(k == -1);
	FuzzyOutVariable* outVariable1 = new FuzzyOutVariable(testModel); // create new outVar
	int j = outVariable1->init(szOutVariable1, 23.4, 56.5, true); //return 0 if success
//	ASSERT(j == -1);

	testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
	testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
	testModel->add_output_variable(szOutVariable1, 23.4, 56.5, true);

	// set atributes for InputVariable1

	inputVar1->set_dom_array_count(100); // discrete y
	inputVar1->set_x_array_count(100); //discrete x

	inputVar1->set_index(0);

	// FuzzySets for InputVariable1
	FuzzySetBase* set1Var1 = new FuzzySetBase(inputVar1);
	// Set attributes for set1Var1

	FuzzySetBase* set2Var1 = new FuzzySetBase(inputVar1);
	FuzzySetBase* set3Var1 = new FuzzySetBase(inputVar1);

	// FuzzySets for InputVariable2
	FuzzySetBase* set1Var2 = new FuzzySetBase(inputVar2);
	FuzzySetBase* set2Var2 = new FuzzySetBase(inputVar2);
	FuzzySetBase* set3Var2 = new FuzzySetBase(inputVar2);

	// Membership functions for sets in InputVariable1

	MemberFuncTrap* functionTrap1 = new MemberFuncTrap(set1Var1);
	functionTrap1->init();
	functionTrap1->set_ramp(1,0); // RAMP_NA
	functionTrap1->init();
	functionTrap1->set_node(0,25,0);
	functionTrap1->set_node(1,27,1);  // 4 point for trap
	functionTrap1->set_node(2,30,1);
	functionTrap1->set_node(3,32,0);

	wchar_t* wset_name = convert_to_wide_char("Set1Var1");
//	FuzzySetBase* set = new_set(wset_name, 0, inputVar1, 3, 0, 2);

	functionTrap1->get_start_x();
	functionTrap1->get_end_x();
	functionTrap1->get_node_x(2);
	functionTrap1->get_node_y(2);
	functionTrap1->get_ramp();
	functionTrap1->get_center_x();
//	functionTrap1->get_dom();
//	functionTrap1->get_value();

	DOMType* arrayDegreeOfMembership = new DOMType[];
//	arrayDegreeOfMembership = (1,2,4,5,6,7,8,9,8,7,6,5,4,3,2,1);

	//FuzzyVariableBase *var = testModel->get_var(OUTPUT_IDX);

	// this code used for automaic create model from api

}<commit_msg> - тест<commit_after>

#include <iostream>
//#include <boost/bind.hpp>
//
//#include <boost/test/included/unit_test.hpp>

#include <FFLLAPI.h>
#include <DefuzzVarObj.h>
#include <FFLLBase.h>
#include <FuzzyModelBase.h>
#include <FuzzyVariableBase.h>
#include <FuzzyOutVariable.h>
#include <RuleArray.h>
#include <MemberFuncTrap.h>
#include <MemberFuncTri.h>
#include <MemberFuncSCurve.h>
#include <MemberFuncSingle.h>
#include <FuzzySetBase.h>

int main( int argc, char* argv[] )
{
	FuzzyModelBase* testModel = new FuzzyModelBase();// = new FuzzyModelBase();
//	testModel->init(); //create model with empty rule array
	RuleArray* ruleArray = new RuleArray(testModel);
	ruleArray->alloc(10); // number of rules;
//	testModel->get_num_of_rules();
	//const Char* c = model->get_model_name();

	testModel->FuzzyModelBase::set_defuzz_method(0); // set DEFUZZ_COG method
	testModel->FuzzyModelBase::set_inference_method(0);
	testModel->FuzzyModelBase::set_composition_method(0);

	//FuzzyModelBase* pmodel = &model;

	std::wstring name1(L"inputVariable1");
	const wchar_t* szInputVariable1 = name1.c_str();

	std::wstring name2(L"outVariable1");
	const wchar_t* szOutVariable1 = name2.c_str();

	std::wstring name3(L"inputVariable2");
	const wchar_t* szInputVariable2 = name3.c_str();

	std::wstring nameSet(L"set1Var1");
	wchar_t* wset_name1 = convert_to_wide_char("set1Var1");

	FuzzyVariableBase* inputVar1 = new FuzzyVariableBase(testModel);// create new inputVar
	int i = inputVar1->init(szInputVariable1, 34.5, 45.3, true);//left x value, right x value? 	// if no name is passed in name it "Variable 0"
	inputVar1->add_set(inputVar1->new_set(wset_name1,25,inputVar1,0,30,2));

	inputVar1->set_x_array_count(100);
//	inputVar1->set_right_x(25);
//	inputVar1->set_ramp(1,0,0);
	//inputVar1->set_dom_array_count(20);
//	inputVar1->set_left_x(0);

//	ASSERT(i == -1);
	FuzzyVariableBase* inputVar2  = new FuzzyVariableBase(testModel);
	int k = inputVar2->init(szInputVariable2, 40, 55, true);
//	ASSERT(k == -1);
	FuzzyOutVariable* outVariable1 = new FuzzyOutVariable(testModel); // create new outVar
	int j = outVariable1->init(szOutVariable1, 23.4, 56.5, true); //return 0 if success
//	ASSERT(j == -1);

	testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
	testModel->add_input_variable(szInputVariable2, 40, 55, true);
	testModel->add_output_variable(szOutVariable1, 23.4, 56.5, true);

	// set atributes for InputVariable1

	inputVar1->set_dom_array_count(100); // discrete y
	inputVar1->set_x_array_count(100); //discrete x

	inputVar1->set_index(0);

	// FuzzySets for InputVariable1
	FuzzySetBase* set1Var1 = new FuzzySetBase(inputVar1);
	// Set attributes for set1Var1

	FuzzySetBase* set2Var1 = new FuzzySetBase(inputVar1);
	FuzzySetBase* set3Var1 = new FuzzySetBase(inputVar1);

	// FuzzySets for InputVariable2
	FuzzySetBase* set1Var2 = new FuzzySetBase(inputVar2);
	FuzzySetBase* set2Var2 = new FuzzySetBase(inputVar2);
	FuzzySetBase* set3Var2 = new FuzzySetBase(inputVar2);

	FuzzySetBase* outSet1 = new FuzzySetBase(outVariable1);
	FuzzySetBase* outSet2 = new FuzzySetBase(outVariable1);
	FuzzySetBase* outSet3 = new FuzzySetBase(outVariable1);
	outSet1->set_index(0);
	outSet2->set_index(1);
	outSet2->set_index(2);
	// Membership functions for sets in InputVariable1

	MemberFuncTrap* functionTrap1 = new MemberFuncTrap(set1Var1);
	functionTrap1->init();
	functionTrap1->set_ramp(1,0); // RAMP_NA
	functionTrap1->init();
	functionTrap1->set_node(0,25,0);
	functionTrap1->set_node(1,27,1);  // 4 point for trap
	functionTrap1->set_node(2,30,1);
	functionTrap1->set_node(3,32,0);

	wchar_t* wset_name = convert_to_wide_char("Set1Var1");
//	FuzzySetBase* set = new_set(wset_name, 0, inputVar1, 3, 0, 2);

	functionTrap1->get_start_x();
	functionTrap1->get_end_x();
	functionTrap1->get_node_x(2);
	functionTrap1->get_node_y(2);
	functionTrap1->get_ramp();
	functionTrap1->get_center_x();
//	functionTrap1->get_dom();
//	functionTrap1->get_value();

	int o = testModel->get_input_var_count();

	//if inputVar1 term1 and inputVar2 term1 then outputVar term1
	//if inputVar1 term1 and inputVar2 term2 then outputVar term2
	//if inputVar1 term1 and inputVar2 term3 then outputVar term3
	//if inputVar1 term2 and inputVar2 term1 then outputVar term1
	//if inputVar1 term2 and inputVar2 term2 then outputVar term2
	//if inputVar1 term2 and inputVar2 term3 then outputVar term3
	//if inputVar1 term3 and inputVar2 term1 then outputVar term1
	//if inputVar1 term3 and inputVar2 term2 then outputVar term2
	//if inputVar1 term3 and inputVar2 term3 then outputVar term3

	int oo = testModel->get_input_var_count()+1;

	std::string* rule_components = new std::string[oo + 1]; // +1 for output var

	testModel->add_rule(0, outSet1->get_index());
	testModel->add_rule(1, outSet2->get_index());
	testModel->add_rule(2, outSet3->get_index());
	testModel->add_rule(3, outSet1->get_index());
	testModel->add_rule(4, outSet2->get_index());
	testModel->add_rule(5, outSet3->get_index());
	testModel->add_rule(6, outSet1->get_index());
	testModel->add_rule(7, outSet2->get_index());
	testModel->add_rule(8, outSet3->get_index());

	DOMType* arrayDegreeOfMembership = new DOMType[];
//	arrayDegreeOfMembership = (1,2,4,5,6,7,8,9,8,7,6,5,4,3,2,1);

	//FuzzyVariableBase *var = testModel->get_var(OUTPUT_IDX);

	// this code used for automaic create model from api

}<|endoftext|>


<commit_before>//
// ByteOrder.cpp
//
// Copyright (c) 2001 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//

#include <stdio.h>
#include <stdlib.h>  /*  For abort()  */
#include "ByteOrder.h"

static int GetDataTypeSize( DataType type )
{
	int tsize;
	switch ( type )
	{
		case DT_SHORT  : tsize = sizeof(short) ; break;
		case DT_INT	: tsize = sizeof(int)   ; break;
		case DT_LONG   : tsize = sizeof(long)  ; break;
		case DT_FLOAT  : tsize = sizeof(float) ; break;
		case DT_DOUBLE : tsize = sizeof(double); break;
		/*  FIXME:  What is the appropriate VTP code bug reporting method?  */
		default: abort();
	}
	return tsize;
}

/**
 * If the byte orders differ, swap bytes; if not, don't; return the result.
 * This is the memory buffer version of the SwapBytes() macros, and as such
 * supports an array of data.  It also parametizes the element type to avoid
 * function explosion.
 * \param items the data items to order
 * \param type the type of each item in the array
 * \param nitems the number if items in the array
 * \param data_order the byte order of the data
 * \param desired_order the desired byte ordering
 *
 */
void SwapMemBytes( void *items, DataType type, size_t nitems,
				   ByteOrder data_order, ByteOrder desired_order )
{
	size_t tsize;
	char  *base = (char *) items,
		*p;

	if ( data_order	== BO_MACHINE ) data_order	= NativeByteOrder();
	if ( desired_order == BO_MACHINE ) desired_order = NativeByteOrder();
	if ( data_order == desired_order )
		return;

	tsize = GetDataTypeSize( type );

	switch ( type )
	{
		case DT_SHORT  :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(short *)p = SwapShort( *(short *)p );
			break;
		case DT_INT	:
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(int   *)p = SwapInt( *(int   *)p );
			break;
		case DT_LONG   :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(long  *)p = SwapLong( *(long  *)p );
			break;
		case DT_FLOAT  :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(float *)p = SwapFloat( *(float *)p );
			break;
		case DT_DOUBLE :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(double *)p = SwapDouble( *(double *)p );
			break;
		/*  FIXME:  What is the appropriate VTP code bug reporting method? */
		default: abort();
	}
}

/**
 * Like stdio's fread(), but adds an optional byte swapping phase for
 * the data read.
 * \param ptr data buffer to read items into
 * \param type the data type of items to be read
 * \param nitems the number of items to read
 * \param stream the stdio stream open for read
 * \param file_order the byte ordering of data read from the file
 * \param desired_order the desired byte ordering
 * \return fread() return value (num items read, or negative for error)
 *
 */
size_t FRead( void *ptr, DataType type, size_t nitems, FILE *stream,
			  ByteOrder file_order, ByteOrder desired_order )
{
	int tsize  = GetDataTypeSize( type );
	size_t ret = fread( ptr, tsize, nitems, stream );

	if ( (int)ret >= 0 )
		SwapMemBytes( ptr, type, ret, file_order, desired_order );
	return ret;
}

/**
 * Like stdio's fread(), but adds an optional byte swapping phase for
 * the data read. File access is done via zlib's gzip IO routines to
 * be compatible with gzopen(), etc.
 * \param ptr data buffer to read items into
 * \param type the data type of items to be read
 * \param nitems the number of items to read
 * \param stream the stdio stream open for read
 * \param file_order the byte ordering of data read from the file
 * \param desired_order the desired byte ordering
 * \return fread() return value (num items read, or negative for error)
 *
 */
size_t GZFRead( void *ptr, DataType type, size_t nitems, gzFile gzstream,
			  ByteOrder file_order, ByteOrder desired_order )
{
	int tsize  = GetDataTypeSize( type );
	size_t ret = gzread(gzstream, ptr, tsize * nitems);

	if ( (int)ret >= 0 )
		SwapMemBytes( ptr, type, ret, file_order, desired_order );
	return ret;
}
<commit_msg>fixed length bug which caused crash on non-Intel machines<commit_after>//
// ByteOrder.cpp
//
// Copyright (c) 2001-2004 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//

#include "ByteOrder.h"

static int GetDataTypeSize( DataType type )
{
	int tsize;
	switch ( type )
	{
		case DT_SHORT:	tsize = sizeof(short);	break;
		case DT_INT:	tsize = sizeof(int);	break;
		case DT_LONG:	tsize = sizeof(long);	break;
		case DT_FLOAT:	tsize = sizeof(float);	break;
		case DT_DOUBLE:	tsize = sizeof(double);	break;
		default: assert(false);
	}
	return tsize;
}

/**
 * If the byte orders differ, swap bytes; if not, don't; return the result.
 * This is the memory buffer version of the SwapBytes() macros, and as such
 * supports an array of data.  It also parametizes the element type to avoid
 * function explosion.
 * \param items the data items to order
 * \param type the type of each item in the array
 * \param nitems the number if items in the array
 * \param data_order the byte order of the data
 * \param desired_order the desired byte ordering
 *
 */
void SwapMemBytes( void *items, DataType type, size_t nitems,
				   ByteOrder data_order, ByteOrder desired_order )
{
	size_t tsize;
	char  *base = (char *) items,
		*p;

	if ( data_order	== BO_MACHINE ) data_order	= NativeByteOrder();
	if ( desired_order == BO_MACHINE ) desired_order = NativeByteOrder();
	if ( data_order == desired_order )
		return;

	tsize = GetDataTypeSize( type );

	switch ( type )
	{
		case DT_SHORT  :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(short *)p = SwapShort( *(short *)p );
			break;
		case DT_INT	:
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(int   *)p = SwapInt( *(int   *)p );
			break;
		case DT_LONG   :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(long  *)p = SwapLong( *(long  *)p );
			break;
		case DT_FLOAT  :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(float *)p = SwapFloat( *(float *)p );
			break;
		case DT_DOUBLE :
			for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
				*(double *)p = SwapDouble( *(double *)p );
			break;
		default:
			assert(false);
	}
}

/**
 * Like stdio's fread(), but adds an optional byte swapping phase for
 * the data read.
 * \param ptr data buffer to read items into
 * \param type the data type of items to be read
 * \param nitems the number of items to read
 * \param stream the stdio stream open for read
 * \param file_order the byte ordering of data read from the file
 * \param desired_order the desired byte ordering
 * \return fread() return value (num items read, or negative for error)
 *
 */
size_t FRead( void *ptr, DataType type, size_t nitems, FILE *stream,
			  ByteOrder file_order, ByteOrder desired_order )
{
	int tsize  = GetDataTypeSize( type );
	size_t ret = fread( ptr, tsize, nitems, stream );

	if ( (int)ret >= 0 )
		SwapMemBytes( ptr, type, ret/tsize, file_order, desired_order );
	return ret;
}

/**
 * Like stdio's fread(), but adds an optional byte swapping phase for
 * the data read. File access is done via zlib's gzip IO routines to
 * be compatible with gzopen(), etc.
 * \param ptr data buffer to read items into
 * \param type the data type of items to be read
 * \param nitems the number of items to read
 * \param stream the stdio stream open for read
 * \param file_order the byte ordering of data read from the file
 * \param desired_order the desired byte ordering
 * \return fread() return value (num items read, or negative for error)
 *
 */
size_t GZFRead( void *ptr, DataType type, size_t nitems, gzFile gzstream,
			  ByteOrder file_order, ByteOrder desired_order )
{
	int tsize  = GetDataTypeSize( type );
	size_t ret = gzread(gzstream, ptr, tsize * nitems);

	if ( (int)ret >= 0 )
		SwapMemBytes( ptr, type, ret/tsize, file_order, desired_order );
	return ret;
}
<|endoftext|>


<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/searchcore/proton/matching/fakesearchcontext.h>
#include <vespa/searchcorespi/index/warmupindexcollection.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/testclock.h>
#include <vespa/log/log.h>
LOG_SETUP("indexcollection_test");

using namespace proton;
using namespace searchcorespi;
using search::FixedSourceSelector;
using search::index::FieldLengthInfo;
using search::queryeval::FakeSearchable;
using search::queryeval::ISourceSelector;
using searchcorespi::index::WarmupConfig;

class MockIndexSearchable : public FakeIndexSearchable {
private:
    FieldLengthInfo _field_length_info;

public:
    MockIndexSearchable()
        : _field_length_info()
    {}
    explicit MockIndexSearchable(const FieldLengthInfo& field_length_info)
        : _field_length_info(field_length_info)
    {}
    FieldLengthInfo get_field_length_info(const vespalib::string& field_name) const override {
        (void) field_name;
        return _field_length_info;
    }
};

class IndexCollectionTest : public ::testing::Test,
                            public IWarmupDone
{
public:
    std::shared_ptr<ISourceSelector> _selector;
    std::shared_ptr<IndexSearchable> _source1;
    std::shared_ptr<IndexSearchable> _source2;
    std::shared_ptr<IndexSearchable> _fusion_source;
    vespalib::ThreadStackExecutor    _executor;
    vespalib::TestClock              _clock;
    std::shared_ptr<IndexSearchable> _warmup;

    void expect_searchable_can_be_appended(IndexCollection::UP collection) {
        const uint32_t id = 42;

        collection->append(id, _source1);
        EXPECT_EQ(1u, collection->getSourceCount());
        EXPECT_EQ(id, collection->getSourceId(0));
    }

    void expect_searchable_can_be_replaced(IndexCollection::UP collection) {
        const uint32_t id = 42;

        collection->append(id, _source1);
        EXPECT_EQ(1u, collection->getSourceCount());
        EXPECT_EQ(id, collection->getSourceId(0));
        EXPECT_EQ(_source1.get(), &collection->getSearchable(0));

        collection->replace(id, _source2);
        EXPECT_EQ(1u, collection->getSourceCount());
        EXPECT_EQ(id, collection->getSourceId(0));
        EXPECT_EQ(_source2.get(), &collection->getSearchable(0));
    }

    IndexCollection::UP make_unique_collection() const {
        return std::make_unique<IndexCollection>(_selector);
    }

    IndexCollection::SP make_shared_collection() const {
        return std::make_shared<IndexCollection>(_selector);
    }

    IndexCollection::UP create_warmup(const IndexCollection::SP& prev, const IndexCollection::SP& next) {
        return std::make_unique<WarmupIndexCollection>(WarmupConfig(1s, false), prev, next, *_warmup, _executor, _clock.clock(), *this);
    }

    void warmupDone(std::shared_ptr<WarmupIndexCollection> current) override {
        (void) current;
    }

    IndexCollectionTest()
        : _selector(std::make_shared<FixedSourceSelector>(0, "fs1")),
          _source1(std::make_shared<MockIndexSearchable>(FieldLengthInfo(3, 5))),
          _source2(std::make_shared<MockIndexSearchable>(FieldLengthInfo(7, 11))),
          _fusion_source(std::make_shared<FakeIndexSearchable>()),
          _executor(1, 128_Ki),
          _warmup(std::make_shared<FakeIndexSearchable>())
    {}
    ~IndexCollectionTest() = default;
};

TEST_F(IndexCollectionTest, searchable_can_be_appended_to_normal_collection)
{
    expect_searchable_can_be_appended(make_unique_collection());
}

TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_normal_collection)
{
    expect_searchable_can_be_replaced(make_unique_collection());
}

TEST_F(IndexCollectionTest, searchable_can_be_appended_to_warmup_collection)
{
    auto prev = make_shared_collection();
    auto next = make_shared_collection();
    expect_searchable_can_be_appended(create_warmup(prev, next));
    EXPECT_EQ(0u, prev->getSourceCount());
    EXPECT_EQ(1u, next->getSourceCount());
}

TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_warmup_collection)
{
    auto prev = make_shared_collection();
    auto next = make_shared_collection();
    expect_searchable_can_be_replaced(create_warmup(prev, next));
    EXPECT_EQ(0u, prev->getSourceCount());
    EXPECT_EQ(1u, next->getSourceCount());
}

TEST_F(IndexCollectionTest, replace_and_renumber_updates_collection_after_fusion)
{
    IndexCollection fsc(_selector);

    fsc.append(0, _source1);
    fsc.append(1, _source1);
    fsc.append(2, _source1);
    fsc.append(3, _source2);
    EXPECT_EQ(4u, fsc.getSourceCount());

    const uint32_t id_diff = 2;
    auto new_fsc = IndexCollection::replaceAndRenumber(_selector, fsc, id_diff, _fusion_source);
    EXPECT_EQ(2u, new_fsc->getSourceCount());
    EXPECT_EQ(0u, new_fsc->getSourceId(0));
    EXPECT_EQ(_fusion_source.get(), &new_fsc->getSearchable(0));
    EXPECT_EQ(1u, new_fsc->getSourceId(1));
    EXPECT_EQ(_source2.get(), &new_fsc->getSearchable(1));
}

TEST_F(IndexCollectionTest, returns_field_length_info_for_last_added_searchable)
{
    auto collection = make_unique_collection();

    collection->append(3, _source1);
    collection->append(4, _source2);

    EXPECT_DOUBLE_EQ(7, collection->get_field_length_info("foo").get_average_field_length());
    EXPECT_EQ(11, collection->get_field_length_info("foo").get_num_samples());
}

TEST_F(IndexCollectionTest, returns_empty_field_length_info_when_no_searchables_exists)
{
    auto collection = make_unique_collection();

    EXPECT_DOUBLE_EQ(0, collection->get_field_length_info("foo").get_average_field_length());
    EXPECT_EQ(0, collection->get_field_length_info("foo").get_num_samples());
}

GTEST_MAIN_RUN_ALL_TESTS()
<commit_msg>Ensure that we can create blueprint for warmup collections too.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/searchcore/proton/matching/fakesearchcontext.h>
#include <vespa/searchlib/queryeval/fake_requestcontext.h>
#include <vespa/searchlib/query/tree/simplequery.h>
#include <vespa/searchcorespi/index/warmupindexcollection.h>
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/size_literals.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/testclock.h>
#include <vespa/log/log.h>
LOG_SETUP("indexcollection_test");

using namespace proton;
using namespace searchcorespi;
using search::FixedSourceSelector;
using search::index::FieldLengthInfo;
using search::queryeval::FakeSearchable;
using search::queryeval::ISourceSelector;
using search::queryeval::FakeRequestContext;
using search::queryeval::FieldSpecList;
using search::queryeval::FieldSpec;
using searchcorespi::index::WarmupConfig;

class MockIndexSearchable : public FakeIndexSearchable {
private:
    FieldLengthInfo _field_length_info;

public:
    MockIndexSearchable()
        : _field_length_info()
    {}
    explicit MockIndexSearchable(const FieldLengthInfo& field_length_info)
        : _field_length_info(field_length_info)
    {}
    FieldLengthInfo get_field_length_info(const vespalib::string& field_name) const override {
        (void) field_name;
        return _field_length_info;
    }
};

class IndexCollectionTest : public ::testing::Test,
                            public IWarmupDone
{
public:
    std::shared_ptr<ISourceSelector> _selector;
    std::shared_ptr<IndexSearchable> _source1;
    std::shared_ptr<IndexSearchable> _source2;
    std::shared_ptr<IndexSearchable> _fusion_source;
    vespalib::ThreadStackExecutor    _executor;
    vespalib::TestClock              _clock;
    std::shared_ptr<IndexSearchable> _warmup;

    void expect_searchable_can_be_appended(ISearchableIndexCollection & collection) {
        const uint32_t id = 42;

        collection.append(id, _source1);
        EXPECT_EQ(1u, collection.getSourceCount());
        EXPECT_EQ(id, collection.getSourceId(0));
    }

    void expect_searchable_can_be_replaced(ISearchableIndexCollection & collection) {
        const uint32_t id = 42;

        collection.append(id, _source1);
        EXPECT_EQ(1u, collection.getSourceCount());
        EXPECT_EQ(id, collection.getSourceId(0));
        EXPECT_EQ(_source1.get(), &collection.getSearchable(0));

        collection.replace(id, _source2);
        EXPECT_EQ(1u, collection.getSourceCount());
        EXPECT_EQ(id, collection.getSourceId(0));
        EXPECT_EQ(_source2.get(), &collection.getSearchable(0));
    }

    std::unique_ptr<IndexCollection>
    make_unique_collection() const {
        return std::make_unique<IndexCollection>(_selector);
    }

    std::shared_ptr<IndexCollection>
    make_shared_collection() const {
        return std::make_shared<IndexCollection>(_selector);
    }

    std::shared_ptr<WarmupIndexCollection>
    create_warmup(const IndexCollection::SP& prev, const IndexCollection::SP& next) {
        return std::make_shared<WarmupIndexCollection>(WarmupConfig(1s, false), prev, next, *_warmup, _executor, _clock.clock(), *this);
    }

    void warmupDone(std::shared_ptr<WarmupIndexCollection> current) override {
        (void) current;
    }

    IndexCollectionTest()
        : _selector(std::make_shared<FixedSourceSelector>(0, "fs1")),
          _source1(std::make_shared<MockIndexSearchable>(FieldLengthInfo(3, 5))),
          _source2(std::make_shared<MockIndexSearchable>(FieldLengthInfo(7, 11))),
          _fusion_source(std::make_shared<FakeIndexSearchable>()),
          _executor(1, 128_Ki),
          _warmup(std::make_shared<FakeIndexSearchable>())
    {}
    ~IndexCollectionTest() = default;
};

TEST_F(IndexCollectionTest, searchable_can_be_appended_to_normal_collection)
{
    expect_searchable_can_be_appended(*make_unique_collection());
}

TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_normal_collection)
{
    expect_searchable_can_be_replaced(*make_unique_collection());
}

TEST_F(IndexCollectionTest, searchable_can_be_appended_to_warmup_collection)
{
    auto prev = make_shared_collection();
    auto next = make_shared_collection();
    expect_searchable_can_be_appended(*create_warmup(prev, next));
    EXPECT_EQ(0u, prev->getSourceCount());
    EXPECT_EQ(1u, next->getSourceCount());
}

TEST_F(IndexCollectionTest, searchable_can_be_replaced_in_warmup_collection)
{
    auto prev = make_shared_collection();
    auto next = make_shared_collection();
    expect_searchable_can_be_replaced(*create_warmup(prev, next));
    EXPECT_EQ(0u, prev->getSourceCount());
    EXPECT_EQ(1u, next->getSourceCount());
}

TEST_F(IndexCollectionTest, replace_and_renumber_updates_collection_after_fusion)
{
    IndexCollection fsc(_selector);

    fsc.append(0, _source1);
    fsc.append(1, _source1);
    fsc.append(2, _source1);
    fsc.append(3, _source2);
    EXPECT_EQ(4u, fsc.getSourceCount());

    const uint32_t id_diff = 2;
    auto new_fsc = IndexCollection::replaceAndRenumber(_selector, fsc, id_diff, _fusion_source);
    EXPECT_EQ(2u, new_fsc->getSourceCount());
    EXPECT_EQ(0u, new_fsc->getSourceId(0));
    EXPECT_EQ(_fusion_source.get(), &new_fsc->getSearchable(0));
    EXPECT_EQ(1u, new_fsc->getSourceId(1));
    EXPECT_EQ(_source2.get(), &new_fsc->getSearchable(1));
}

TEST_F(IndexCollectionTest, returns_field_length_info_for_last_added_searchable)
{
    auto collection = make_unique_collection();

    collection->append(3, _source1);
    collection->append(4, _source2);

    EXPECT_DOUBLE_EQ(7, collection->get_field_length_info("foo").get_average_field_length());
    EXPECT_EQ(11, collection->get_field_length_info("foo").get_num_samples());
}

TEST_F(IndexCollectionTest, returns_empty_field_length_info_when_no_searchables_exists)
{
    auto collection = make_unique_collection();

    EXPECT_DOUBLE_EQ(0, collection->get_field_length_info("foo").get_average_field_length());
    EXPECT_EQ(0, collection->get_field_length_info("foo").get_num_samples());
}

TEST_F(IndexCollectionTest, warmup_can_create_blueprint)
{
    auto prev = make_shared_collection();
    auto next = make_shared_collection();
    auto indexcollection = create_warmup(prev, next);
    const uint32_t id = 42;
    indexcollection->append(id, _source1);

    FakeRequestContext requestContext;
    FieldSpecList fields;
    fields.add(FieldSpec("dummy", 1, search::fef::IllegalHandle));
    search::query::SimpleStringTerm term("what", "dummy", 1, search::query::Weight(100));
    auto blueprint = indexcollection->createBlueprint(requestContext, fields, term);
    EXPECT_TRUE(blueprint);
}

GTEST_MAIN_RUN_ALL_TESTS()
<|endoftext|>


<commit_before>/*
 * DbgTracePort.cpp
 *
 *  Created on: 16.03.2015
 *      Author: niklausd
 */

#include "DbgTraceContext.h"
#include "DbgTraceOut.h"
#include "DbgTracePort.h"
#include "DbgCliCommand.h"

#ifdef ARDUINO
#include <Arduino.h>
#else
#include <time.h>
#endif
#include <stdio.h>
#include <string.h>

//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeOut
//-----------------------------------------------------------------------------

class DbgCli_Command_ChangeOut : public DbgCli_Command
{

private:
  DbgTrace_Port* m_tracePort;

public:
  DbgCli_Command_ChangeOut(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
  : DbgCli_Command(parentNode, nodeName, helpText)
  , m_tracePort(port)
  { }

  void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
  {
    const char* cmd = args[idxToFirstArgToHandle];
    DbgTrace_Context* context = DbgTrace_Context::getContext();

    if(0 == strncmp(cmd, "get", 4))
    {
      if((0 !=  m_tracePort) && (0 != m_tracePort->getOut()))
      {
        char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
        snprintf(buf, sizeof(buf), "Out: \"%s\"" , m_tracePort->getOut()->getName());
#ifdef ARDUINO
        Serial.print(buf);
#else
        println(buf);
#endif
      }
    }
    else if(0 == strncmp(cmd, "set", 4))
    {
      if((0 !=  m_tracePort) && (0 != m_tracePort->getOut()) && (0 != context))
      {
        DbgTrace_Out* newOut = context->getTraceOut(args[idxToFirstArgToHandle+1]);
        char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];

        if(0 != newOut)
        {
          m_tracePort->setOut(newOut);
          snprintf(buf, sizeof(buf),"OK! Out: \"%s\"" , m_tracePort->getOut()->getName());
        }
        else
        {
          snprintf(buf, sizeof(buf), "Fail! Out: \"%s\"" , m_tracePort->getOut()->getName());
        }
 #ifdef ARDUINO
          Serial.print(buf);
 #else
          println(buf);
 #endif
      }
    }
    else if((0 == strncmp(cmd, "list", 5)) && (0 != context))
    {
      DbgTrace_Out* tmpOut = context->getFirstTraceOut();
      if((0 !=  m_tracePort) && (0 != m_tracePort->getOut()))
      {
        char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
        while(0 != tmpOut)
        {
          if((0 != m_tracePort->getOut()) &&
             (0 == strncmp(tmpOut->getName(), m_tracePort->getOut()->getName(), DbgTrace_Out::s_cMaxOutNameLength)))
          {
            // mark currently used out
            snprintf(buf, sizeof(buf),">%s" , tmpOut->getName());
          }
          else
          {
            snprintf(buf, sizeof(buf), " %s" , tmpOut->getName());
          }
#ifdef ARDUINO
          Serial.println(buf);
 #else
          println(buf);
 #endif
          tmpOut = tmpOut->getNextOut();
        }
      }
    }
    else
    {
#ifdef ARDUINO
  Serial.print(F("Unknown command: "));
  Serial.println(cmd);
  Serial.println(this->getHelpText());
#else
  println("Unknown command: %s", cmd);
  printf(this->getHelpText());
#endif
    }
  }
private:
  DbgCli_Command_ChangeOut();
};

//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeLevel
//-----------------------------------------------------------------------------

class DbgCli_Command_ChangeLevel : public DbgCli_Command
{

private:
  DbgTrace_Port* m_tracePort;

public:
  DbgCli_Command_ChangeLevel(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
  : DbgCli_Command(parentNode, nodeName, helpText)
  , m_tracePort(port)
  { }

  void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
  {
    const char* cmd = args[idxToFirstArgToHandle];

    if(0 == strncmp(cmd, "get", 4))
    {
      if(0 !=  m_tracePort)
      {
        char buf[20 + DbgTrace_Level::s_cMaxLevelLength];
        snprintf(buf, sizeof(buf), "Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
#ifdef ARDUINO
        Serial.println(buf);
#else
        printfln(buf);
#endif
      }
    }
    else if(0 == strncmp(cmd, "set", 4))
    {
      if(0 !=  m_tracePort)
      {
        char buf[20 + DbgTrace_Level::s_cMaxLevelLength];

        DbgTrace_Level::Level newLevel = DbgTrace_Level::stringToLevel(args[idxToFirstArgToHandle+1]);
        if(DbgTrace_Level::none != newLevel)
        {
          m_tracePort->setLevel(newLevel);
          snprintf(buf, sizeof(buf),"OK! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
        }
        else
        {
          snprintf(buf, sizeof(buf), "Fail! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
        }
 #ifdef ARDUINO
          Serial.print(buf);
 #else
          printfln(buf);
 #endif
      }
    }
    else if(0 == strncmp(cmd, "list", 5))
    {
      if(0 !=  m_tracePort)
      {
        unsigned int level = 0;
        char buf[4 + DbgTrace_Level::s_cMaxLevelLength];
        while(DbgTrace_Level::LEVEL_ENUM_LIMIT != level)
        {
          if(level == m_tracePort->getLevel())
          {
            // mark currently used out
            snprintf(buf, sizeof(buf),">%s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
          }
          else
          {
            snprintf(buf, sizeof(buf)," %s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
          }
#ifdef ARDUINO
          Serial.println(buf);
 #else
          println(buf);
 #endif
          level++;
        }
      }
    }
    else
    {
    #ifdef ARDUINO
      Serial.print(F("Unknown command: "));
      Serial.println(cmd);
      Serial.println(this->getHelpText());
    #else
      println("Unknown command: %s", cmd);
      printf(this->getHelpText());
    #endif
    }
  }
private:
  DbgCli_Command_ChangeLevel();
};

//-----------------------------------------------------------------------------
// Class DbgTrace_Port
//-----------------------------------------------------------------------------

DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const char* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(tag)
{
  if(0 != context)
  {
    context->addTracePort(this);
  }
}

#ifdef ARDUINO
DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const __FlashStringHelper* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(reinterpret_cast<const char*>(tag))
{
  if(0 != context)
  {
    context->addTracePort(this);
  }
}
#endif

DbgTrace_Port::~DbgTrace_Port()
{
  //Delete tracePort in single linked list
  DbgTrace_Context* context = DbgTrace_Context::getContext();
  if(0 != context)
  {
    context->deleteTracePort(m_tag);
  }
}

void DbgTrace_Port::printStr(const char* str)
{
  if(0 != m_out)
  {
#ifdef ARDUINO
    char timeStr[s_cArduinoTimeStamp];
#else
    char timeStr[s_cTestTimeStamp];
#endif
    char stream[s_cTraceBufSize];
    getTime(timeStr);
    snprintf(stream, sizeof(stream), "%s - %s: %s", timeStr, getTag(), str);

    m_out->print(stream);
  }
}

void DbgTrace_Port::printLong(long num)
{
  if(0 != m_out)
  {
#ifdef ARDUINO
    char timeStr[s_cArduinoTimeStamp];
#else
    char timeStr[s_cTestTimeStamp];
#endif
    char stream[s_cTraceBufSize];
    getTime(timeStr);
    snprintf(stream, sizeof(stream), "%s - %s: %ld", timeStr, getTag(), num);

    m_out->print(stream);
  }
}

void DbgTrace_Port::printDbl(double val)
{
  if(0 != m_out)
  {
#ifdef ARDUINO
    char timeStr[s_cArduinoTimeStamp];
#else
    char timeStr[s_cTestTimeStamp];
#endif
    getTime(timeStr);
    char stream[s_cTraceBufSize];
    snprintf(stream, sizeof(stream), "%s - %s: %f", timeStr, getTag(), val);

    m_out->print(stream);
  }
}

void DbgTrace_Port::getTime(char* timeStr)
{
#ifdef ARDUINO
  sprintf(timeStr,"%ld", millis());
#else
  _strtime(timeStr);
#endif
}

void DbgTrace_Port::createCliNodes(DbgCli_Topic* contextTopic)
{
  DbgCli_Topic* portTopic = new DbgCli_Topic(contextTopic, m_tag, "Offers get/set access to output and level");
  if(0 != m_out)
  {
    // Create DbgCli commands for out and level of this port
    new DbgCli_Command_ChangeOut(this, portTopic, "outCmd", "Cmd's: get, set outName, list");
    new DbgCli_Command_ChangeLevel(this, portTopic, "levelCmd", "Cmd's: get, set levelName, list");
  }
}

<commit_msg>Shorter lvlCmd<commit_after>/*
 * DbgTracePort.cpp
 *
 *  Created on: 16.03.2015
 *      Author: niklausd
 */

#include "DbgTraceContext.h"
#include "DbgTraceOut.h"
#include "DbgTracePort.h"
#include "DbgCliCommand.h"

#ifdef ARDUINO
#include <Arduino.h>
#else
#include <time.h>
#endif
#include <stdio.h>
#include <string.h>

//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeOut
//-----------------------------------------------------------------------------

class DbgCli_Command_ChangeOut : public DbgCli_Command
{

private:
  DbgTrace_Port* m_tracePort;

public:
  DbgCli_Command_ChangeOut(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
  : DbgCli_Command(parentNode, nodeName, helpText)
  , m_tracePort(port)
  { }

  void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
  {
    const char* cmd = args[idxToFirstArgToHandle];
    DbgTrace_Context* context = DbgTrace_Context::getContext();

    if(0 == strncmp(cmd, "get", 4))
    {
      if((0 !=  m_tracePort) && (0 != m_tracePort->getOut()))
      {
        char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
        snprintf(buf, sizeof(buf), "Out: \"%s\"" , m_tracePort->getOut()->getName());
#ifdef ARDUINO
        Serial.print(buf);
#else
        println(buf);
#endif
      }
    }
    else if(0 == strncmp(cmd, "set", 4))
    {
      if((0 !=  m_tracePort) && (0 != m_tracePort->getOut()) && (0 != context))
      {
        DbgTrace_Out* newOut = context->getTraceOut(args[idxToFirstArgToHandle+1]);
        char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];

        if(0 != newOut)
        {
          m_tracePort->setOut(newOut);
          snprintf(buf, sizeof(buf),"OK! Out: \"%s\"" , m_tracePort->getOut()->getName());
        }
        else
        {
          snprintf(buf, sizeof(buf), "Fail! Out: \"%s\"" , m_tracePort->getOut()->getName());
        }
 #ifdef ARDUINO
          Serial.print(buf);
 #else
          println(buf);
 #endif
      }
    }
    else if((0 == strncmp(cmd, "list", 5)) && (0 != context))
    {
      DbgTrace_Out* tmpOut = context->getFirstTraceOut();
      if((0 !=  m_tracePort) && (0 != m_tracePort->getOut()))
      {
        char buf[20 + DbgTrace_Out::s_cMaxOutNameLength];
        while(0 != tmpOut)
        {
          if((0 != m_tracePort->getOut()) &&
             (0 == strncmp(tmpOut->getName(), m_tracePort->getOut()->getName(), DbgTrace_Out::s_cMaxOutNameLength)))
          {
            // mark currently used out
            snprintf(buf, sizeof(buf),">%s" , tmpOut->getName());
          }
          else
          {
            snprintf(buf, sizeof(buf), " %s" , tmpOut->getName());
          }
#ifdef ARDUINO
          Serial.println(buf);
 #else
          println(buf);
 #endif
          tmpOut = tmpOut->getNextOut();
        }
      }
    }
    else
    {
#ifdef ARDUINO
  Serial.print(F("Unknown command: "));
  Serial.println(cmd);
  Serial.println(this->getHelpText());
#else
  println("Unknown command: %s", cmd);
  printf(this->getHelpText());
#endif
    }
  }
private:
  DbgCli_Command_ChangeOut();
};

//-----------------------------------------------------------------------------
// concrete command class DbgCli_Command_ChangeLevel
//-----------------------------------------------------------------------------

class DbgCli_Command_ChangeLevel : public DbgCli_Command
{

private:
  DbgTrace_Port* m_tracePort;

public:
  DbgCli_Command_ChangeLevel(DbgTrace_Port* port, DbgCli_Node* parentNode, const char* nodeName, const char* helpText)
  : DbgCli_Command(parentNode, nodeName, helpText)
  , m_tracePort(port)
  { }

  void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
  {
    const char* cmd = args[idxToFirstArgToHandle];

    if(0 == strncmp(cmd, "get", 4))
    {
      if(0 !=  m_tracePort)
      {
        char buf[20 + DbgTrace_Level::s_cMaxLevelLength];
        snprintf(buf, sizeof(buf), "Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
#ifdef ARDUINO
        Serial.println(buf);
#else
        printfln(buf);
#endif
      }
    }
    else if(0 == strncmp(cmd, "set", 4))
    {
      if(0 !=  m_tracePort)
      {
        char buf[20 + DbgTrace_Level::s_cMaxLevelLength];

        DbgTrace_Level::Level newLevel = DbgTrace_Level::stringToLevel(args[idxToFirstArgToHandle+1]);
        if(DbgTrace_Level::none != newLevel)
        {
          m_tracePort->setLevel(newLevel);
          snprintf(buf, sizeof(buf),"OK! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
        }
        else
        {
          snprintf(buf, sizeof(buf), "Fail! Level: \"%s\"" , DbgTrace_Level::levelToString(m_tracePort->getLevel()));
        }
 #ifdef ARDUINO
          Serial.print(buf);
 #else
          printfln(buf);
 #endif
      }
    }
    else if(0 == strncmp(cmd, "list", 5))
    {
      if(0 !=  m_tracePort)
      {
        unsigned int level = 0;
        char buf[4 + DbgTrace_Level::s_cMaxLevelLength];
        while(DbgTrace_Level::LEVEL_ENUM_LIMIT != level)
        {
          if(level == m_tracePort->getLevel())
          {
            // mark currently used out
            snprintf(buf, sizeof(buf),">%s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
          }
          else
          {
            snprintf(buf, sizeof(buf)," %s" , DbgTrace_Level::levelToString(static_cast<DbgTrace_Level::Level>(level)));
          }
#ifdef ARDUINO
          Serial.println(buf);
 #else
          println(buf);
 #endif
          level++;
        }
      }
    }
    else
    {
    #ifdef ARDUINO
      Serial.print(F("Unknown command: "));
      Serial.println(cmd);
      Serial.println(this->getHelpText());
    #else
      println("Unknown command: %s", cmd);
      printf(this->getHelpText());
    #endif
    }
  }
private:
  DbgCli_Command_ChangeLevel();
};

//-----------------------------------------------------------------------------
// Class DbgTrace_Port
//-----------------------------------------------------------------------------

DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const char* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(tag)
{
  if(0 != context)
  {
    context->addTracePort(this);
  }
}

#ifdef ARDUINO
DbgTrace_Port::DbgTrace_Port(DbgTrace_Context* context, const __FlashStringHelper* tag, DbgTrace_Out* out, DbgTrace_Level::Level level)
: m_out(out)
, m_level(level)
, m_nextPort(0)
, m_tag(reinterpret_cast<const char*>(tag))
{
  if(0 != context)
  {
    context->addTracePort(this);
  }
}
#endif

DbgTrace_Port::~DbgTrace_Port()
{
  //Delete tracePort in single linked list
  DbgTrace_Context* context = DbgTrace_Context::getContext();
  if(0 != context)
  {
    context->deleteTracePort(m_tag);
  }
}

void DbgTrace_Port::printStr(const char* str)
{
  if(0 != m_out)
  {
#ifdef ARDUINO
    char timeStr[s_cArduinoTimeStamp];
#else
    char timeStr[s_cTestTimeStamp];
#endif
    char stream[s_cTraceBufSize];
    getTime(timeStr);
    snprintf(stream, sizeof(stream), "%s - %s: %s", timeStr, getTag(), str);

    m_out->print(stream);
  }
}

void DbgTrace_Port::printLong(long num)
{
  if(0 != m_out)
  {
#ifdef ARDUINO
    char timeStr[s_cArduinoTimeStamp];
#else
    char timeStr[s_cTestTimeStamp];
#endif
    char stream[s_cTraceBufSize];
    getTime(timeStr);
    snprintf(stream, sizeof(stream), "%s - %s: %ld", timeStr, getTag(), num);

    m_out->print(stream);
  }
}

void DbgTrace_Port::printDbl(double val)
{
  if(0 != m_out)
  {
#ifdef ARDUINO
    char timeStr[s_cArduinoTimeStamp];
#else
    char timeStr[s_cTestTimeStamp];
#endif
    getTime(timeStr);
    char stream[s_cTraceBufSize];
    snprintf(stream, sizeof(stream), "%s - %s: %f", timeStr, getTag(), val);

    m_out->print(stream);
  }
}

void DbgTrace_Port::getTime(char* timeStr)
{
#ifdef ARDUINO
  sprintf(timeStr,"%ld", millis());
#else
  _strtime(timeStr);
#endif
}

void DbgTrace_Port::createCliNodes(DbgCli_Topic* contextTopic)
{
  DbgCli_Topic* portTopic = new DbgCli_Topic(contextTopic, m_tag, "Offers get/set access to output and level");
  if(0 != m_out)
  {
    // Create DbgCli commands for out and level of this port
    new DbgCli_Command_ChangeOut(this, portTopic, "outCmd", "Cmds: get, set <outName>, list");
    new DbgCli_Command_ChangeLevel(this, portTopic, "lvlCmd", "Cmds: get, set <levelName>, list");
  }
}

<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2003-2012
  \file      WordListUtil.cpp
  \author      (robot.xet@gmail.com)
  \date      29.09.2012
  \brief
  \indent    4T
*/

#include <vector>
#include <map>
#include <boost\algorithm\string.hpp>

#include "utils\rdotypes.h"

#include "WordListUtil.h"

WordListUtil::WordListUtil(const WordList& wordlist)
	: wl(wordlist)
{}

//tstring WordListUtil::GetNearestWord (const char *wordStart, int searchLen) const
//{
//}

std::vector<tstring> WordListUtil::GetNearestWords(const char *wordStart) const
{
	struct keyword
	{
		tstring value;
		int     priority;

		keyword()
			: priority(0)
		{}
		keyword(const tstring& value, int priority)
			: value   (value   )
			, priority(priority)
		{}

		rbool operator< (const keyword& other) const
		{
			return priority < other.priority;
		}
	};

	int start = 0;
	int end = wl.len - 1;
	std::vector<tstring> res;
	std::vector<keyword> pres;
	if (0 == wl.words)
	{
		res.push_back("");
		return res;
	}
	if( boost::iequals(wordStart, ""))
	{
		for(int i = start; i < end; i++)
		{
			res.push_back(wl.words[i]);
		}
		return res;
	}

	for (int i = start; i < end; i++)
	{
		if (boost::ifind_first(wl.words[i], wordStart))
		{
			pres.push_back(keyword(wl.words[i], tstring(wl.words[i]).length()));
		}
	}

	std::sort(pres.begin(), pres.end());
	std::vector<keyword>::iterator it;

	for (it = pres.begin(); it != pres.end(); ++it)
	{
		res.push_back(it->value);
	}
	return res;
}<commit_msg> - приоритет должен быть float<commit_after>/*!
  \copyright (c) RDO-Team, 2003-2012
  \file      WordListUtil.cpp
  \author      (robot.xet@gmail.com)
  \date      29.09.2012
  \brief
  \indent    4T
*/

#include <vector>
#include <map>
#include <boost\algorithm\string.hpp>

#include "utils\rdotypes.h"

#include "WordListUtil.h"

WordListUtil::WordListUtil(const WordList& wordlist)
	: wl(wordlist)
{}

//tstring WordListUtil::GetNearestWord (const char *wordStart, int searchLen) const
//{
//}

std::vector<tstring> WordListUtil::GetNearestWords(const char *wordStart) const
{
	struct keyword
	{
		tstring value;
		float   priority;

		keyword()
			: priority(0.0)
		{}
		keyword(const tstring& value, float priority)
			: value   (value   )
			, priority(priority)
		{}

		rbool operator< (const keyword& other) const
		{
			return priority < other.priority;
		}
	};

	int start = 0;
	int end = wl.len - 1;
	std::vector<tstring> res;
	std::vector<keyword> pres;
	if (0 == wl.words)
	{
		res.push_back("");
		return res;
	}
	if( boost::iequals(wordStart, ""))
	{
		for(int i = start; i < end; i++)
		{
			res.push_back(wl.words[i]);
		}
		return res;
	}

	for (int i = start; i < end; i++)
	{
		if (boost::ifind_first(wl.words[i], wordStart))
		{
			pres.push_back(keyword(wl.words[i], tstring(wl.words[i]).length()));
		}
	}

	std::sort(pres.begin(), pres.end());
	std::vector<keyword>::iterator it;

	for (it = pres.begin(); it != pres.end(); ++it)
	{
		res.push_back(it->value);
	}
	return res;
}<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "attributenode.h"
#include <vespa/searchlib/attribute/singleenumattribute.h>

namespace search::expression {

using namespace vespalib;
using search::attribute::IAttributeContext;
using search::attribute::IAttributeVector;
using search::attribute::BasicType;

IMPLEMENT_EXPRESSIONNODE(AttributeNode, FunctionNode);
IMPLEMENT_RESULTNODE(AttributeResult, ResultNode);

namespace {

class EnumAttributeResult : public AttributeResult
{
public:
    DECLARE_RESULTNODE(EnumAttributeResult);
    EnumAttributeResult(const attribute::IAttributeVector * attribute, DocId docId) :
        AttributeResult(attribute, docId),
        _enumAttr(dynamic_cast<const SingleValueEnumAttributeBase *>(attribute))
    {
    }
private:
    EnumAttributeResult() :
        AttributeResult(),
        _enumAttr(NULL)
    { }
    int64_t onGetEnum(size_t index) const override { (void) index; return (static_cast<int64_t>(_enumAttr->getE(getDocId()))); }
    const SingleValueEnumAttributeBase * _enumAttr;
};

IMPLEMENT_RESULTNODE(EnumAttributeResult, AttributeResult);

std::unique_ptr<AttributeResult> createResult(const IAttributeVector * attribute)
{
    return (dynamic_cast<const SingleValueEnumAttributeBase *>(attribute) != NULL)
        ? std::make_unique<EnumAttributeResult>(attribute, 0)
        : std::make_unique<AttributeResult>(attribute, 0);
}

}

AttributeNode::AttributeNode() :
    FunctionNode(),
    _scratchResult(new AttributeResult()),
    _hasMultiValue(false),
    _useEnumOptimization(false),
    _handler(),
    _attributeName()
{}

AttributeNode::~AttributeNode() {}

AttributeNode::AttributeNode(vespalib::stringref name) :
    FunctionNode(),
    _scratchResult(new AttributeResult()),
    _hasMultiValue(false),
    _useEnumOptimization(false),
    _handler(),
    _attributeName(name)
{}
AttributeNode::AttributeNode(const IAttributeVector & attribute) :
    FunctionNode(),
    _scratchResult(createResult(&attribute)),
    _hasMultiValue(attribute.hasMultiValue()),
    _useEnumOptimization(false),
    _handler(),
    _attributeName(attribute.getName())
{}

AttributeNode::AttributeNode(const AttributeNode & attribute) :
    FunctionNode(attribute),
    _scratchResult(attribute._scratchResult->clone()),
    _hasMultiValue(attribute._hasMultiValue),
    _useEnumOptimization(attribute._useEnumOptimization),
    _handler(),
    _attributeName(attribute._attributeName)
{
    _scratchResult->setDocId(0);
}

AttributeNode & AttributeNode::operator = (const AttributeNode & attr)
{
    if (this != &attr) {
        FunctionNode::operator = (attr);
        _attributeName = attr._attributeName;
        _hasMultiValue = attr._hasMultiValue;
        _useEnumOptimization = attr._useEnumOptimization;
        _scratchResult.reset(attr._scratchResult->clone());
        _scratchResult->setDocId(0);
    }
    return *this;
}

void AttributeNode::onPrepare(bool preserveAccurateTypes)
{
    const IAttributeVector * attribute = _scratchResult->getAttribute();
    if (attribute != NULL) {
        BasicType::Type basicType = attribute->getBasicType();
        if (attribute->isIntegerType()) {
            if (_hasMultiValue) {
                if (preserveAccurateTypes) {
                    switch (basicType) {
                      case BasicType::INT8:
                        setResultType(std::make_unique<Int8ResultNodeVector>());
                        break;
                      case BasicType::INT16:
                        setResultType(std::make_unique<Int16ResultNodeVector>());
                        break;
                      case BasicType::INT32:
                        setResultType(std::make_unique<Int32ResultNodeVector>());
                        break;
                      case BasicType::INT64:
                        setResultType(std::make_unique<Int64ResultNodeVector>());
                        break;
                      default:
                        throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
                        break;
                    }
                } else {
                    setResultType(std::make_unique<IntegerResultNodeVector>());
                }
                _handler = std::make_unique<IntegerHandler>(updateResult());
            } else {
                if (preserveAccurateTypes) {
                    switch (basicType) {
                      case BasicType::INT8:
                        setResultType(std::make_unique<Int8ResultNode>());
                        break;
                      case BasicType::INT16:
                        setResultType(std::make_unique<Int16ResultNode>());
                        break;
                      case BasicType::INT32:
                        setResultType(std::make_unique<Int32ResultNode>());
                        break;
                      case BasicType::INT64:
                        setResultType(std::make_unique<Int64ResultNode>());
                        break;
                      default:
                        throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
                        break;
                    }
                } else {
                    setResultType(std::make_unique<Int64ResultNode>());
                }
            }
        } else if (attribute->isFloatingPointType()) {
            if (_hasMultiValue) {
                setResultType(std::make_unique<FloatResultNodeVector>());
                _handler = std::make_unique<FloatHandler>(updateResult());
            } else {
                setResultType(std::make_unique<FloatResultNode>());
            }
        } else if (attribute->isStringType()) {
            if (_hasMultiValue) {
                if (_useEnumOptimization) {
                    setResultType(std::make_unique<EnumResultNodeVector>());
                    _handler = std::make_unique<EnumHandler>(updateResult());
                } else {
                    setResultType(std::make_unique<StringResultNodeVector>());
                    _handler = std::make_unique<StringHandler>(updateResult());
                }
            } else {
                if (_useEnumOptimization) {
                    setResultType(std::make_unique<EnumResultNode>());
                } else {
                    setResultType(std::make_unique<StringResultNode>());
                }
            }
        } else {
            throw std::runtime_error(make_string("Can not deduce correct resultclass for attribute vector '%s'",
                                                 attribute->getName().c_str()));
        }
    }
}

void AttributeNode::IntegerHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

void AttributeNode::FloatHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

void AttributeNode::StringHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

void AttributeNode::EnumHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

bool AttributeNode::onExecute() const
{
    if (_hasMultiValue) {
        _handler->handle(*_scratchResult);
    } else {
        updateResult().set(*_scratchResult);
    }
    return true;
}

void AttributeNode::wireAttributes(const IAttributeContext & attrCtx)
{
    const IAttributeVector * attribute(_scratchResult ? _scratchResult->getAttribute() : nullptr);
    if (attribute == NULL) {
        if (_useEnumOptimization) {
            attribute = attrCtx.getAttributeStableEnum(_attributeName);
        } else {
            attribute = attrCtx.getAttribute(_attributeName);
        }
        if (attribute == NULL) {
            throw std::runtime_error(make_string("Failed locating attribute vector '%s'", _attributeName.c_str()));
        }
        _hasMultiValue = attribute->hasMultiValue();
        _scratchResult = createResult(attribute);
    }
}

void AttributeNode::cleanup()
{
    _scratchResult.reset();
}

Serializer & AttributeNode::onSerialize(Serializer & os) const
{
    FunctionNode::onSerialize(os);
    return os << _attributeName;
}

Deserializer & AttributeNode::onDeserialize(Deserializer & is)
{
    FunctionNode::onDeserialize(is);

    return is >> _attributeName;
}

void
AttributeNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
    visit(visitor, "attributeName", _attributeName);
}

}

// this function was added by ../../forcelink.sh
void forcelink_file_searchlib_expression_attributenode() {}
<commit_msg>Use Handler in AttributeNode when present to update values.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "attributenode.h"
#include <vespa/searchlib/attribute/singleenumattribute.h>

namespace search::expression {

using namespace vespalib;
using search::attribute::IAttributeContext;
using search::attribute::IAttributeVector;
using search::attribute::BasicType;

IMPLEMENT_EXPRESSIONNODE(AttributeNode, FunctionNode);
IMPLEMENT_RESULTNODE(AttributeResult, ResultNode);

namespace {

class EnumAttributeResult : public AttributeResult
{
public:
    DECLARE_RESULTNODE(EnumAttributeResult);
    EnumAttributeResult(const attribute::IAttributeVector * attribute, DocId docId) :
        AttributeResult(attribute, docId),
        _enumAttr(dynamic_cast<const SingleValueEnumAttributeBase *>(attribute))
    {
    }
private:
    EnumAttributeResult() :
        AttributeResult(),
        _enumAttr(NULL)
    { }
    int64_t onGetEnum(size_t index) const override { (void) index; return (static_cast<int64_t>(_enumAttr->getE(getDocId()))); }
    const SingleValueEnumAttributeBase * _enumAttr;
};

IMPLEMENT_RESULTNODE(EnumAttributeResult, AttributeResult);

std::unique_ptr<AttributeResult> createResult(const IAttributeVector * attribute)
{
    return (dynamic_cast<const SingleValueEnumAttributeBase *>(attribute) != NULL)
        ? std::make_unique<EnumAttributeResult>(attribute, 0)
        : std::make_unique<AttributeResult>(attribute, 0);
}

}

AttributeNode::AttributeNode() :
    FunctionNode(),
    _scratchResult(new AttributeResult()),
    _hasMultiValue(false),
    _useEnumOptimization(false),
    _handler(),
    _attributeName()
{}

AttributeNode::~AttributeNode() {}

AttributeNode::AttributeNode(vespalib::stringref name) :
    FunctionNode(),
    _scratchResult(new AttributeResult()),
    _hasMultiValue(false),
    _useEnumOptimization(false),
    _handler(),
    _attributeName(name)
{}
AttributeNode::AttributeNode(const IAttributeVector & attribute) :
    FunctionNode(),
    _scratchResult(createResult(&attribute)),
    _hasMultiValue(attribute.hasMultiValue()),
    _useEnumOptimization(false),
    _handler(),
    _attributeName(attribute.getName())
{}

AttributeNode::AttributeNode(const AttributeNode & attribute) :
    FunctionNode(attribute),
    _scratchResult(attribute._scratchResult->clone()),
    _hasMultiValue(attribute._hasMultiValue),
    _useEnumOptimization(attribute._useEnumOptimization),
    _handler(),
    _attributeName(attribute._attributeName)
{
    _scratchResult->setDocId(0);
}

AttributeNode & AttributeNode::operator = (const AttributeNode & attr)
{
    if (this != &attr) {
        FunctionNode::operator = (attr);
        _attributeName = attr._attributeName;
        _hasMultiValue = attr._hasMultiValue;
        _useEnumOptimization = attr._useEnumOptimization;
        _scratchResult.reset(attr._scratchResult->clone());
        _scratchResult->setDocId(0);
    }
    return *this;
}

void AttributeNode::onPrepare(bool preserveAccurateTypes)
{
    const IAttributeVector * attribute = _scratchResult->getAttribute();
    if (attribute != NULL) {
        BasicType::Type basicType = attribute->getBasicType();
        if (attribute->isIntegerType()) {
            if (_hasMultiValue) {
                if (preserveAccurateTypes) {
                    switch (basicType) {
                      case BasicType::INT8:
                        setResultType(std::make_unique<Int8ResultNodeVector>());
                        break;
                      case BasicType::INT16:
                        setResultType(std::make_unique<Int16ResultNodeVector>());
                        break;
                      case BasicType::INT32:
                        setResultType(std::make_unique<Int32ResultNodeVector>());
                        break;
                      case BasicType::INT64:
                        setResultType(std::make_unique<Int64ResultNodeVector>());
                        break;
                      default:
                        throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
                        break;
                    }
                } else {
                    setResultType(std::make_unique<IntegerResultNodeVector>());
                }
                _handler = std::make_unique<IntegerHandler>(updateResult());
            } else {
                if (preserveAccurateTypes) {
                    switch (basicType) {
                      case BasicType::INT8:
                        setResultType(std::make_unique<Int8ResultNode>());
                        break;
                      case BasicType::INT16:
                        setResultType(std::make_unique<Int16ResultNode>());
                        break;
                      case BasicType::INT32:
                        setResultType(std::make_unique<Int32ResultNode>());
                        break;
                      case BasicType::INT64:
                        setResultType(std::make_unique<Int64ResultNode>());
                        break;
                      default:
                        throw std::runtime_error("This is no valid integer attribute " + attribute->getName());
                        break;
                    }
                } else {
                    setResultType(std::make_unique<Int64ResultNode>());
                }
            }
        } else if (attribute->isFloatingPointType()) {
            if (_hasMultiValue) {
                setResultType(std::make_unique<FloatResultNodeVector>());
                _handler = std::make_unique<FloatHandler>(updateResult());
            } else {
                setResultType(std::make_unique<FloatResultNode>());
            }
        } else if (attribute->isStringType()) {
            if (_hasMultiValue) {
                if (_useEnumOptimization) {
                    setResultType(std::make_unique<EnumResultNodeVector>());
                    _handler = std::make_unique<EnumHandler>(updateResult());
                } else {
                    setResultType(std::make_unique<StringResultNodeVector>());
                    _handler = std::make_unique<StringHandler>(updateResult());
                }
            } else {
                if (_useEnumOptimization) {
                    setResultType(std::make_unique<EnumResultNode>());
                } else {
                    setResultType(std::make_unique<StringResultNode>());
                }
            }
        } else {
            throw std::runtime_error(make_string("Can not deduce correct resultclass for attribute vector '%s'",
                                                 attribute->getName().c_str()));
        }
    }
}

void AttributeNode::IntegerHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

void AttributeNode::FloatHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

void AttributeNode::StringHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

void AttributeNode::EnumHandler::handle(const AttributeResult & r)
{
    size_t numValues = r.getAttribute()->getValueCount(r.getDocId());
    _vector.resize(numValues);
    _wVector.resize(numValues);
    r.getAttribute()->get(r.getDocId(), &_wVector[0], _wVector.size());
    for(size_t i(0); i < numValues; i++) {
        _vector[i] = _wVector[i].getValue();
    }
}

bool AttributeNode::onExecute() const
{
    if (_handler) {
        _handler->handle(*_scratchResult);
    } else {
        updateResult().set(*_scratchResult);
    }
    return true;
}

void AttributeNode::wireAttributes(const IAttributeContext & attrCtx)
{
    const IAttributeVector * attribute(_scratchResult ? _scratchResult->getAttribute() : nullptr);
    if (attribute == NULL) {
        if (_useEnumOptimization) {
            attribute = attrCtx.getAttributeStableEnum(_attributeName);
        } else {
            attribute = attrCtx.getAttribute(_attributeName);
        }
        if (attribute == NULL) {
            throw std::runtime_error(make_string("Failed locating attribute vector '%s'", _attributeName.c_str()));
        }
        _hasMultiValue = attribute->hasMultiValue();
        _scratchResult = createResult(attribute);
    }
}

void AttributeNode::cleanup()
{
    _scratchResult.reset();
}

Serializer & AttributeNode::onSerialize(Serializer & os) const
{
    FunctionNode::onSerialize(os);
    return os << _attributeName;
}

Deserializer & AttributeNode::onDeserialize(Deserializer & is)
{
    FunctionNode::onDeserialize(is);

    return is >> _attributeName;
}

void
AttributeNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
    visit(visitor, "attributeName", _attributeName);
}

}

// this function was added by ../../forcelink.sh
void forcelink_file_searchlib_expression_attributenode() {}
<|endoftext|>


<commit_before>/// \file ROOT/TText.hxx
/// \ingroup Graf ROOT7
/// \author Olivier Couet <Olivier.Couet@cern.ch>
/// \date 2017-10-16
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT7_TText
#define ROOT7_TText

#include <ROOT/TDrawable.hxx>
#include <ROOT/TDrawingAttr.hxx>
#include <ROOT/TDrawingOptsBase.hxx>
#include <ROOT/TPad.hxx>
#include <ROOT/TVirtualCanvasPainter.hxx>

#include <initializer_list>
#include <memory>
#include <string>

namespace ROOT {
namespace Experimental {

/** \class ROOT::Experimental::TText
 A text.
 */

class TText {
private:
   std::string fText{};

   /// Text's X position
   double fX{0.};

   /// Text's Y position
   double fY{0.};

public:
   TText() = default;

   TText(const std::string &str) : fText(str) {}

   void SetText(const std::string &txt) { fText = txt; }

   std::string GetText() const { return fText; }

   void SetPosition(double x, double y)
   {
      fX = x;
      fY = y;
   }

   double GetX() const { return fX; }

   double GetY() const { return fY; }
};

class TextDrawingOpts: public TDrawingOptsBase {
   TDrawingAttr<int> fLineWidth{*this, "Text.Line.Width", 3}; ///< The line width.
   TDrawingAttr<TColor> fLineColor{*this, "Text.Line.Color", TColor::kBlack}; ///< The line color.
   TDrawingAttr<TColor> fFillColor{*this, "Text.Fill.Color", TColor::kInvisible}; ///< The fill color.

public:
   /// The color of the line.
   void SetLineColor(const TColor &col) { fLineColor = col; }
   TColor &GetLineColor() { return fLineColor.Get(); }
   const TColor &GetLineColor() const { return fLineColor.Get(); }

   /// The width of the line.
   void SetLineWidth(int width) { fLineWidth = width; }
   int GetLineWidth() { return (int)fLineWidth; }

   /// The fill color
   void SetFillColor(const TColor &col) { fFillColor = col; }
   TColor &GetFillColor() { return fFillColor.Get(); }
   const TColor &GetFillColor() const { return fFillColor.Get(); }
};

class TTextDrawable : public TDrawable {
private:
   /// Text string to be drawn

   Internal::TUniWeakPtr<ROOT::Experimental::TText> fText{};

   /// Text attributes
   TextDrawingOpts fOpts;

public:
   TTextDrawable() = default;

   TTextDrawable(const std::shared_ptr<ROOT::Experimental::TText> &txt)
      : TDrawable(), fText(txt)
   {
   }

   TextDrawingOpts &GetOptions() { return fOpts; }
   const TextDrawingOpts &GetOptions() const { return fOpts; }

   void Paint(Internal::TVirtualCanvasPainter &canv) final
   {
      canv.AddDisplayItem(new ROOT::Experimental::TOrdinaryDisplayItem<ROOT::Experimental::TTextDrawable>(this));
   }
};

inline std::unique_ptr<ROOT::Experimental::TTextDrawable>
GetDrawable(const std::shared_ptr<ROOT::Experimental::TText> &text)
{
   return std::make_unique<ROOT::Experimental::TTextDrawable>(text);
}

} // namespace Experimental
} // namespace ROOT

#endif
<commit_msg>Inject TDrawableBase.<commit_after>/// \file ROOT/TText.hxx
/// \ingroup Graf ROOT7
/// \author Olivier Couet <Olivier.Couet@cern.ch>
/// \date 2017-10-16
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT7_TText
#define ROOT7_TText

#include <ROOT/TDrawable.hxx>
#include <ROOT/TDrawingAttr.hxx>
#include <ROOT/TDrawingOptsBase.hxx>
#include <ROOT/TPad.hxx>
#include <ROOT/TVirtualCanvasPainter.hxx>

#include <initializer_list>
#include <memory>
#include <string>

namespace ROOT {
namespace Experimental {

/** \class ROOT::Experimental::TText
 A text.
 */

class TText {
private:
   std::string fText{};

   /// Text's X position
   double fX{0.};

   /// Text's Y position
   double fY{0.};

public:
   TText() = default;

   TText(const std::string &str) : fText(str) {}

   void SetText(const std::string &txt) { fText = txt; }

   std::string GetText() const { return fText; }

   void SetPosition(double x, double y)
   {
      fX = x;
      fY = y;
   }

   double GetX() const { return fX; }

   double GetY() const { return fY; }
};

class TextDrawingOpts: public TDrawingOptsBase {
   TDrawingAttr<int> fLineWidth{*this, "Text.Line.Width", 3}; ///< The line width.
   TDrawingAttr<TColor> fLineColor{*this, "Text.Line.Color", TColor::kBlack}; ///< The line color.
   TDrawingAttr<TColor> fFillColor{*this, "Text.Fill.Color", TColor::kInvisible}; ///< The fill color.

public:
   /// The color of the line.
   void SetLineColor(const TColor &col) { fLineColor = col; }
   TColor &GetLineColor() { return fLineColor.Get(); }
   const TColor &GetLineColor() const { return fLineColor.Get(); }

   /// The width of the line.
   void SetLineWidth(int width) { fLineWidth = width; }
   int GetLineWidth() { return (int)fLineWidth; }

   /// The fill color
   void SetFillColor(const TColor &col) { fFillColor = col; }
   TColor &GetFillColor() { return fFillColor.Get(); }
   const TColor &GetFillColor() const { return fFillColor.Get(); }
};

class TTextDrawable : public TDrawableBase<TTextDrawable> {
private:
   /// Text string to be drawn

   Internal::TUniWeakPtr<ROOT::Experimental::TText> fText{};

   /// Text attributes
   TextDrawingOpts fOpts;

public:
   TTextDrawable() = default;

   TTextDrawable(const std::shared_ptr<ROOT::Experimental::TText> &txt)
      : fText(txt)
   {
   }

   TextDrawingOpts &GetOptions() { return fOpts; }
   const TextDrawingOpts &GetOptions() const { return fOpts; }

   void Paint(Internal::TVirtualCanvasPainter &canv) final
   {
      canv.AddDisplayItem(new ROOT::Experimental::TOrdinaryDisplayItem<ROOT::Experimental::TTextDrawable>(this));
   }
};

inline std::unique_ptr<ROOT::Experimental::TTextDrawable>
GetDrawable(const std::shared_ptr<ROOT::Experimental::TText> &text)
{
   return std::make_unique<ROOT::Experimental::TTextDrawable>(text);
}

} // namespace Experimental
} // namespace ROOT

#endif
<|endoftext|>


<commit_before>#pragma once

#include <stdint.h>
#include <type_traits>

namespace faze
{
  // lets just use 64bits for this
  // we can reduce the size later if needed
  struct ResourceHandle
  {
    union
    {
      struct
      {
        uint64_t id : 20; // million is too much for id's
        uint64_t generation : 8; // generous generation id
        uint64_t type : 6; // ... I don't really want to write this much api types
        uint64_t gpuid : 16; // this should just be a bitfield, one bit for gpu, starting with modest 16 gpu's =D
        uint64_t unused : 14; // honestly could be more bits here, lets just see how things go on
      };
      uint64_t rawValue;
    };
    ResourceHandle(uint64_t id, uint64_t generation, uint64_t type, uint64_t gpuID)
      : id(id)
      , generation(generation)
      , type(type)
      , gpuid(gpuID)
    {
      static_assert(std::is_standard_layout<ResourceHandle>::value,  "ResourceHandle should be trivial to destroy.");
    }

    // returns positive value when single gpu
    // -1 when every gpu owns its own
    // -2 is mysterious error situation.
    int ownerGpuId() const
    {
      uint64_t c_gpuid = gpuid;
      uint64_t count = 0;
      if (c_gpuid == 65535)
      {
        return -1;
      }
      while(count < 16) // valid id's 0-15
      {
        if (c_gpuid & (1 << count))
        {
          return int(count);
        }
      }
      return -2;
    }

    // shared resource means it's a handle that can be opened on another api/gpu device
    // otherwise all gpu's have their own version of this resource.
    bool sharedResource() const
    {
      return ownerGpuId() >= 0; // false for now
    }
  };

  /*
  Problem is how we allocate these and ...
  There probably should be a manager that we can use for checks

  Ideally we want to check generation on each access of resource.
  So we could have something that gives out id's and offers functions to check if those id's are expired.
  So we would need
    - Allocate Handle
      - get id from pool
        - if no id in pool, make a new one
    - Delete Handle
      - mostly just, return to pool as usable
    - check if alive
      - array to check current status of the id and match generation for id check
  */
}<commit_msg>some more handle code Just making the utilities on using handles easier. Bit more so that I don't just spend tons of memory upfront for all id's like I do now.... 1 million uint32_t's upfront is kind of sizeful if assuming I use all the bits. Small steps baby steps...<commit_after>#pragma once

#include <core/datastructures/proxy.hpp>
#include <core/global_debug.hpp>

#include <stdint.h>
#include <type_traits>

namespace faze
{
  // lets just use 64bits for this
  // we can reduce the size later if needed
  struct ResourceHandle
  {
    static const uint64_t InvalidId = (1ull << 20ull) - 1;
    union
    {
      struct
      {
        uint64_t id : 20; // million is too much for id's
        uint64_t generation : 8; // generous generation id
        uint64_t type : 6; // ... I don't really want to write this much api types
        uint64_t gpuid : 16; // this should just be a bitfield, one bit for gpu, starting with modest 16 gpu's =D
        uint64_t unused : 14; // honestly could be more bits here, lets just see how things go on
      };
      uint64_t rawValue;
    };
    ResourceHandle(uint64_t id, uint64_t generation, uint64_t type, uint64_t gpuID)
      : id(id)
      , generation(generation)
      , type(type)
      , gpuid(gpuID)
    {
      static_assert(std::is_standard_layout<ResourceHandle>::value,  "ResourceHandle should be trivial to destroy.");
    }

    // returns positive value when single gpu
    // -1 when every gpu owns its own
    // -2 is mysterious error situation.
    int ownerGpuId() const
    {
      uint64_t c_gpuid = gpuid;
      uint64_t count = 0;
      if (c_gpuid == 65535)
      {
        return -1;
      }
      while(count < 16) // valid id's 0-15
      {
        if (c_gpuid & (1 << count))
        {
          return int(count);
        }
      }
      return -2;
    }

    // shared resource means it's a handle that can be opened on another api/gpu device
    // otherwise all gpu's have their own version of this resource.
    bool sharedResource() const
    {
      return ownerGpuId() >= 0; // false for now
    }
  };

  /*
  Problem is how we allocate these and ...
  There probably should be a manager that we can use for checks

  Ideally we want to check generation on each access of resource.
  So we could have something that gives out id's and offers functions to check if those id's are expired.
  So we would need
    - Allocate Handle
      - get id from pool
        - if no id in pool, make a new one
    - Delete Handle
      - mostly just, return to pool as usable
    - check if alive
      - array to check current status of the id and match generation for id check
  */

  // we need legopiece to generate id's which knows how to reuse them
  // we need "type" amount of these lego pieces, all ranges begin from 0 till something

  class HandlePool
  {
    vector<uint32_t> m_freelist;
    vector<uint8_t> m_generation;
    uint64_t m_type = 0;
    int m_size = 0;
  public:
    HandlePool(uint64_t type, int size)
      : m_type(type)
      , m_size(size)
    {
      for (int i = size; i >= 0; i--)
      {
        m_freelist.push_back(i);
      }
      m_generation.resize(m_size);
      for (int i = 0; i < m_size; ++i)
      {
        m_generation[i] = 0;
      }
    }

    ResourceHandle allocate()
    {
      if (m_freelist.empty())
      {
        F_ASSERT(false, "No handles left, what.");
        return ResourceHandle{ResourceHandle::InvalidId, 0, m_type, 0};
      }
      auto id = m_freelist.back();
      m_freelist.pop_back();
      auto generation = m_generation[id]; // take current generation
      return ResourceHandle{id, generation, m_type, 0};
    }

    void release(ResourceHandle val)
    {
      F_ASSERT(val.id != ResourceHandle::InvalidId
                && val.id < m_size
                && val.generation == m_generation[val.id]
                , "Invalid handle was released.");
      m_freelist.push_back(val.id);
      m_generation[val.id]++; // offset the generation to detect double free's
    }

    bool valid(ResourceHandle handle)
    {
      F_ASSERT(handle.id != ResourceHandle::InvalidId
                && handle.id < m_size
                , "Invalid handle was passed.");
      return handle.generation == m_generation[handle.id];
    }

    size_t size() const
    {
      return m_freelist.size();
    }
  };

}<|endoftext|>