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

#ifndef _XMLOFF_XMLEMBEDDEDOBJECTEXPORTFILTER_HXX
#define _XMLOFF_XMLEMBEDDEDOBJECTEXPORTFILTER_HXX

#ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

class XMLEmbeddedObjectExportFilter : public ::cppu::WeakImplHelper3<
             ::com::sun::star::xml::sax::XExtendedDocumentHandler,
             ::com::sun::star::lang::XServiceInfo,
             ::com::sun::star::lang::XInitialization>
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler > xHandler;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XExtendedDocumentHandler > xExtHandler;

public:
    XMLEmbeddedObjectExportFilter() throw();
    XMLEmbeddedObjectExportFilter( const ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler > & rHandler ) throw();
    virtual ~XMLEmbeddedObjectExportFilter () throw();

    // ::com::sun::star::xml::sax::XDocumentHandler
    virtual void SAL_CALL startDocument(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL endDocument(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL startElement(const ::rtl::OUString& aName,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL endElement(const ::rtl::OUString& aName)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL characters(const ::rtl::OUString& aChars)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL ignorableWhitespace(const ::rtl::OUString& aWhitespaces)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL processingInstruction(const ::rtl::OUString& aTarget,
                                       const ::rtl::OUString& aData)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL setDocumentLocator(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > & xLocator)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::xml::sax::XExtendedDocumentHandler
    virtual void SAL_CALL startCDATA(void) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL endCDATA(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL comment(const ::rtl::OUString& sComment)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL allowLineBreak(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL unknown(const ::rtl::OUString& sString)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );

    // XInitialization
    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);

};

#endif  //  _XMLOFF_XMLEMBEDDEDOBJECTEXPORTFILTER_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.640); FILE MERGED 2005/09/05 14:37:54 rt 1.1.640.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLEmbeddedObjectExportFilter.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:48:00 $
 *
 *  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 _XMLOFF_XMLEMBEDDEDOBJECTEXPORTFILTER_HXX
#define _XMLOFF_XMLEMBEDDEDOBJECTEXPORTFILTER_HXX

#ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

class XMLEmbeddedObjectExportFilter : public ::cppu::WeakImplHelper3<
             ::com::sun::star::xml::sax::XExtendedDocumentHandler,
             ::com::sun::star::lang::XServiceInfo,
             ::com::sun::star::lang::XInitialization>
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler > xHandler;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XExtendedDocumentHandler > xExtHandler;

public:
    XMLEmbeddedObjectExportFilter() throw();
    XMLEmbeddedObjectExportFilter( const ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XDocumentHandler > & rHandler ) throw();
    virtual ~XMLEmbeddedObjectExportFilter () throw();

    // ::com::sun::star::xml::sax::XDocumentHandler
    virtual void SAL_CALL startDocument(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL endDocument(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL startElement(const ::rtl::OUString& aName,
                              const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL endElement(const ::rtl::OUString& aName)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL characters(const ::rtl::OUString& aChars)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL ignorableWhitespace(const ::rtl::OUString& aWhitespaces)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL processingInstruction(const ::rtl::OUString& aTarget,
                                       const ::rtl::OUString& aData)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL setDocumentLocator(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > & xLocator)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::xml::sax::XExtendedDocumentHandler
    virtual void SAL_CALL startCDATA(void) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL endCDATA(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL comment(const ::rtl::OUString& sComment)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL allowLineBreak(void)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL unknown(const ::rtl::OUString& sString)
        throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException );

    // XInitialization
    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);

};

#endif  //  _XMLOFF_XMLEMBEDDEDOBJECTEXPORTFILTER_HXX
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#ifndef _LIBDNF_OPTION_HPP
#define _LIBDNF_OPTION_HPP

#ifdef LIBDNF_UNSTABLE_API

#include <stdexcept>
#include <string>

namespace libdnf {

class Option {
public:
    enum class Priority {
        EMPTY = 0,
        DEFAULT = 10,
        MAINCONFIG = 20,
        AUTOMATICCONFIG = 30,
        REPOCONFIG = 40,
        PLUGINDEFAULT = 50,
        PLUGINCONFIG = 60,
        COMMANDLINE = 70,
        RUNTIME = 80
    };

    struct Exception : public std::runtime_error {
        Exception(const std::string & msg) : runtime_error(msg) {}
        Exception(const char * msg) : runtime_error(msg) {}
    };
    struct InvalidValue : Exception {
        InvalidValue(const std::string & msg) : Exception(msg) {}
        InvalidValue(const char * msg) : Exception(msg) {}
    };
    struct ValueNotSet : Exception {
        ValueNotSet(const std::string & msg) : Exception(msg) {}
        ValueNotSet(const char * msg) : Exception(msg) {}
    };

    Option(Priority priority = Priority::EMPTY);
    virtual Option * clone() const = 0;
    virtual Priority getPriority() const;
    virtual void set(Priority priority, const std::string & value) = 0;
    virtual std::string getValueString() const = 0;
    virtual bool empty() const noexcept;
    virtual ~Option() = default;

protected:
    Priority priority;
};

inline Option::Option(Priority priority)
: priority(priority) {}

inline Option::Priority Option::getPriority() const
{
    return priority;
}

inline bool Option::empty() const noexcept
{
    return priority == Priority::EMPTY;
}

}

#endif

#endif
<commit_msg>set priority of dnf.conf.d drop-ins<commit_after>/*
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#ifndef _LIBDNF_OPTION_HPP
#define _LIBDNF_OPTION_HPP

#ifdef LIBDNF_UNSTABLE_API

#include <stdexcept>
#include <string>

namespace libdnf {

class Option {
public:
    enum class Priority {
        EMPTY = 0,
        DEFAULT = 10,
        MAINCONFIG = 20,
        AUTOMATICCONFIG = 30,
        REPOCONFIG = 40,
        PLUGINDEFAULT = 50,
        PLUGINCONFIG = 60,
        DROPINCONFIG = 65,
        COMMANDLINE = 70,
        RUNTIME = 80
    };

    struct Exception : public std::runtime_error {
        Exception(const std::string & msg) : runtime_error(msg) {}
        Exception(const char * msg) : runtime_error(msg) {}
    };
    struct InvalidValue : Exception {
        InvalidValue(const std::string & msg) : Exception(msg) {}
        InvalidValue(const char * msg) : Exception(msg) {}
    };
    struct ValueNotSet : Exception {
        ValueNotSet(const std::string & msg) : Exception(msg) {}
        ValueNotSet(const char * msg) : Exception(msg) {}
    };

    Option(Priority priority = Priority::EMPTY);
    virtual Option * clone() const = 0;
    virtual Priority getPriority() const;
    virtual void set(Priority priority, const std::string & value) = 0;
    virtual std::string getValueString() const = 0;
    virtual bool empty() const noexcept;
    virtual ~Option() = default;

protected:
    Priority priority;
};

inline Option::Option(Priority priority)
: priority(priority) {}

inline Option::Priority Option::getPriority() const
{
    return priority;
}

inline bool Option::empty() const noexcept
{
    return priority == Priority::EMPTY;
}

}

#endif

#endif
<|endoftext|>


<commit_before>#include "Arith256.h"
#include "Runtime.h"
#include "Type.h"

#include <llvm/IR/Function.h>

namespace dev
{
namespace eth
{
namespace jit
{

Arith256::Arith256(llvm::IRBuilder<>& _builder) :
	CompilerHelper(_builder)
{
	using namespace llvm;

	m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result");
	m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1");
	m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2");
	m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3");

	using Linkage = GlobalValue::LinkageTypes;

	llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr};
	llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr};

	m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule());
	m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule());
	m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule());
	m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule());
	m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule());
	m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule());
	m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule());
	m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule());
}

Arith256::~Arith256()
{}

llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2)
{
	m_builder.CreateStore(_arg1, m_arg1);
	m_builder.CreateStore(_arg2, m_arg2);
	m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result);
	return m_builder.CreateLoad(m_result);
}

llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
	m_builder.CreateStore(_arg1, m_arg1);
	m_builder.CreateStore(_arg2, m_arg2);
	m_builder.CreateStore(_arg3, m_arg3);
	m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result);
	return m_builder.CreateLoad(m_result);
}

llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_mul, _arg1, _arg2);
}

llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_div, _arg1, _arg2);
}

llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_mod, _arg1, _arg2);
}

llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_sdiv, _arg1, _arg2);
}

llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_smod, _arg1, _arg2);
}

llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_exp, _arg1, _arg2);
}

llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
	return ternaryOp(m_addmod, _arg1, _arg2, _arg3);
}

llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
	return ternaryOp(m_mulmod, _arg1, _arg2, _arg3);
}

}
}
}

extern "C"
{

	using namespace dev::eth::jit;
	using s256 = boost::multiprecision::int256_t;

	EXPORT void arith_mul(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg1 * arg2);
	}

	EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 / arg2);
	}

	EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2);
	}

	EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : (arg1.convert_to<s256>() / arg2.convert_to<s256>()).convert_to<u256>());
	}

	EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : (arg1.convert_to<s256>() % arg2.convert_to<s256>()).convert_to<u256>());
	}

	EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result)
	{
		bigint left = llvm2eth(*_arg1);
		bigint right = llvm2eth(*_arg2);
		auto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256));
		*o_result = eth2llvm(ret);
	}

	EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		auto arg3 = llvm2eth(*_arg3);
		*o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3));
	}

	EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		auto arg3 = llvm2eth(*_arg3);
		*o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3));
	}

}

<commit_msg>SDIV & SMOD fixed<commit_after>#include "Arith256.h"
#include "Runtime.h"
#include "Type.h"

#include <llvm/IR/Function.h>

namespace dev
{
namespace eth
{
namespace jit
{

Arith256::Arith256(llvm::IRBuilder<>& _builder) :
	CompilerHelper(_builder)
{
	using namespace llvm;

	m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result");
	m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1");
	m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2");
	m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3");

	using Linkage = GlobalValue::LinkageTypes;

	llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr};
	llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr};

	m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule());
	m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule());
	m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule());
	m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule());
	m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule());
	m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule());
	m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule());
	m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule());
}

Arith256::~Arith256()
{}

llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2)
{
	m_builder.CreateStore(_arg1, m_arg1);
	m_builder.CreateStore(_arg2, m_arg2);
	m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result);
	return m_builder.CreateLoad(m_result);
}

llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
	m_builder.CreateStore(_arg1, m_arg1);
	m_builder.CreateStore(_arg2, m_arg2);
	m_builder.CreateStore(_arg3, m_arg3);
	m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result);
	return m_builder.CreateLoad(m_result);
}

llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_mul, _arg1, _arg2);
}

llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_div, _arg1, _arg2);
}

llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_mod, _arg1, _arg2);
}

llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_sdiv, _arg1, _arg2);
}

llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_smod, _arg1, _arg2);
}

llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2)
{
	return binaryOp(m_exp, _arg1, _arg2);
}

llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
	return ternaryOp(m_addmod, _arg1, _arg2, _arg3);
}

llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)
{
	return ternaryOp(m_mulmod, _arg1, _arg2, _arg3);
}

namespace
{
	using s256 = boost::multiprecision::int256_t;

	inline s256 u2s(u256 _u)
	{
		static const bigint c_end = (bigint)1 << 256;
		static const u256 c_send = (u256)1 << 255;
		if (_u < c_send)
			return (s256)_u;
		else
			return (s256)-(c_end - _u);
	}

	inline u256 s2u(s256 _u)
	{
		static const bigint c_end = (bigint)1 << 256;
		if (_u >= 0)
			return (u256)_u;
		else
			return (u256)(c_end + _u);
	}
}

}
}
}

extern "C"
{

	using namespace dev::eth::jit;

	EXPORT void arith_mul(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg1 * arg2);
	}

	EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 / arg2);
	}

	EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2);
	}

	EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) / u2s(arg2)));
	}

	EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2)));
	}

	EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result)
	{
		bigint left = llvm2eth(*_arg1);
		bigint right = llvm2eth(*_arg2);
		auto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256));
		*o_result = eth2llvm(ret);
	}

	EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		auto arg3 = llvm2eth(*_arg3);
		*o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3));
	}

	EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)
	{
		auto arg1 = llvm2eth(*_arg1);
		auto arg2 = llvm2eth(*_arg2);
		auto arg3 = llvm2eth(*_arg3);
		*o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3));
	}

}

<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/quic/quic_flags.h"

// TODO(rtenneti): Remove this.
// Do not flip this flag until the flakiness of the
// net/tools/quic/end_to_end_test is fixed.
// If true, then QUIC connections will track the retransmission history of a
// packet so that an ack of a previous transmission will ack the data of all
// other transmissions.
bool FLAGS_track_retransmission_history = false;

// Do not remove this flag until the Finch-trials described in b/11706275
// are complete.
// If true, QUIC connections will support the use of a pacing algorithm when
// sending packets, in an attempt to reduce packet loss.  The client must also
// request pacing for the server to enable it.
bool FLAGS_enable_quic_pacing = true;

// Do not remove this flag until b/11792453 is marked as Fixed.
// If true, turns on stream flow control in QUIC.
// If this is disabled, all in flight QUIC connections talking QUIC_VERSION_17
// or higher will timeout. New connections will be fine.
// If disabling this flag, also disable enable_quic_connection_flow_control.
bool FLAGS_enable_quic_stream_flow_control_2 = true;

// Do not remove this flag until b/11792453 is marked as Fixed.
// If true, turns on connection level flow control in QUIC.
// If this is disabled, all in flight QUIC connections talking QUIC_VERSION_19
// or higher will timeout. New connections will be fine.
bool FLAGS_enable_quic_connection_flow_control = true;

bool FLAGS_quic_allow_oversized_packets_for_test = false;

// When true, the use time based loss detection instead of nack.
bool FLAGS_quic_use_time_loss_detection = false;

// If true, allow peer port migration of established QUIC connections.
bool FLAGS_quic_allow_port_migration = true;
<commit_msg>Rollback FLAGS_enable_quic_connection_flow_control due to bug in latest internal server.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/quic/quic_flags.h"

// TODO(rtenneti): Remove this.
// Do not flip this flag until the flakiness of the
// net/tools/quic/end_to_end_test is fixed.
// If true, then QUIC connections will track the retransmission history of a
// packet so that an ack of a previous transmission will ack the data of all
// other transmissions.
bool FLAGS_track_retransmission_history = false;

// Do not remove this flag until the Finch-trials described in b/11706275
// are complete.
// If true, QUIC connections will support the use of a pacing algorithm when
// sending packets, in an attempt to reduce packet loss.  The client must also
// request pacing for the server to enable it.
bool FLAGS_enable_quic_pacing = true;

// Do not remove this flag until b/11792453 is marked as Fixed.
// If true, turns on stream flow control in QUIC.
// If this is disabled, all in flight QUIC connections talking QUIC_VERSION_17
// or higher will timeout. New connections will be fine.
// If disabling this flag, also disable enable_quic_connection_flow_control.
bool FLAGS_enable_quic_stream_flow_control_2 = true;

// Do not remove this flag until b/11792453 is marked as Fixed.
// If true, turns on connection level flow control in QUIC.
// If this is disabled, all in flight QUIC connections talking QUIC_VERSION_19
// or higher will timeout. New connections will be fine.
// Disabled due to b/15084203.
bool FLAGS_enable_quic_connection_flow_control = false;

bool FLAGS_quic_allow_oversized_packets_for_test = false;

// When true, the use time based loss detection instead of nack.
bool FLAGS_quic_use_time_loss_detection = false;

// If true, allow peer port migration of established QUIC connections.
bool FLAGS_quic_allow_port_migration = true;
<|endoftext|>


<commit_before>#pragma once

#include <type_traits>
#include <tuple>
#include <agency/detail/tuple.hpp>
#include <agency/detail/shape_cast.hpp>
#include <agency/coordinate.hpp>
#include <agency/detail/tuple_utility.hpp>
#include <agency/detail/point_size.hpp>

namespace agency
{
namespace detail
{

template<class Index, class Size>
__AGENCY_ANNOTATION
auto project_index_helper(const Index& idx, Size size_of_second_to_last_dimension)
  -> typename std::decay<
       decltype(
         unwrap_single_element_tuple(__tu::tuple_drop_last(idx))
       )
     >::type
{
  auto result = detail::tuple_drop_last(idx);

  // multiply the index by the size of the second to last dimension and add
  // that to the second to last index
  __tu::tuple_last(result) += size_of_second_to_last_dimension * __tu::tuple_last(idx);

  return unwrap_single_element_tuple(result);
}

template<class Index, class Shape>
__AGENCY_ANNOTATION
auto project_index(const Index& idx, const Shape& shape)
  -> decltype(
       detail::make_tuple(
         project_index_helper(idx, __tu::tuple_last(shape)),
         project_shape(shape)
       )
     )
{
  // to project an index into the next lower dimension,
  // we combine the last two dimensions into one

  // for a 2D example, consider finding the 1D rank of element (2,2)
  // in a 5 x 4-shaped grid.
  // element (2,2)'s rank is 12 in this grid
  // given idx = (x,y) = (2,2) and shape = (width,height) = (5,4)
  // (2,2)'s 1D rank is computed as
  // y * width + x

  auto size_of_second_to_last_dimension = __tu::tuple_last(detail::tuple_drop_last(shape));

  auto projected_index = project_index_helper(idx, size_of_second_to_last_dimension);

  // project the shape
  // this creates a lower dimensional grid with
  // the same number of cells
  // for the shape = (5,4) example, this will compute
  // a 1D shape of 20
  auto projected_shape = project_shape(shape);

  return detail::make_tuple(projected_index, projected_shape);
}

template<class Tuple,
         class = typename std::enable_if<
           !std::is_integral<
              typename std::decay<Tuple>::type
            >::value
         >::type>
__AGENCY_ANNOTATION
auto wrap_scalar(Tuple&& t)
  -> decltype(std::forward<Tuple>(t))
{
  return std::forward<Tuple>(t);
}

template<class T,
         class = typename std::enable_if<
           std::is_integral<
             typename std::decay<T>::type
           >::value
         >::type>
__AGENCY_ANNOTATION
auto wrap_scalar(T&& x)
  -> decltype(
       rebind_point_size_t<
         typename std::decay<T>::type,
         1
       >{std::forward<T>(x)}
     )
{
  return rebind_point_size_t<
    typename std::decay<T>::type,
    1
  >{std::forward<T>(x)};
}

namespace index_cast_detail
{

// to lift a point-like type, add a dimension
template<class Index>
struct lift_t_impl
{
  using type = rebind_point_size_t<Index, point_size<Index>::value + 1>;
};

// to lift a heterogeneous Tuple-like type, repeat the type of the last element
template<template<class...> class tuple, class T, class... Types>
struct lift_t_impl<tuple<T,Types...>>
{
  using last_type = typename std::tuple_element<sizeof...(Types)-1, std::tuple<Types...>>::type;
  using type = tuple<T,Types...,last_type>;
};

template<class T>
struct make
{
  template<class... Args>
  __AGENCY_ANNOTATION
  T operator()(Args&&... args) const
  {
    return T{std::forward<Args>(args)...};
  }
};

} // end index_cast_detail

template<class Point>
using lift_t = typename index_cast_detail::lift_t_impl<Point>::type;

template<class Index, class FromShape, class ToShape>
__AGENCY_ANNOTATION
detail::tuple<lift_t<Index>, lift_t<FromShape>>
  lift_index(const Index& idx, const FromShape& from_shape, const ToShape& to_shape)
{
  // to lift idx into to_shape,
  // take the last element of idx and divide by the corresponding element of to_shape
  // replace the last element of idx with the remainder and append the quotient
  const auto i = index_size<Index>::value - 1;

  auto idx_tuple = wrap_scalar(idx);

  auto intermediate_result = idx_tuple;
  __tu::tuple_last(intermediate_result) %= detail::get<i>(to_shape);

  auto index_maker = index_cast_detail::make<lift_t<Index>>{};

  auto lifted_index = __tu::tuple_append_invoke(intermediate_result, __tu::tuple_last(idx_tuple) / detail::get<i>(to_shape), index_maker);

  // to lift from_shape, simply append the element of to_shape we just divided by
  auto shape_maker = index_cast_detail::make<lift_t<FromShape>>{};
  auto lifted_shape = __tu::tuple_append_invoke(wrap_scalar(from_shape), detail::get<i>(to_shape), shape_maker);

  return detail::make_tuple(lifted_index, lifted_shape);
}

// index_cast is recursive and has various overloads
// declare them here before their definitions

// scalar -> scalar (base case)
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value == 1),
  ToShape
>::type
  index_cast(const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape);

// recursive case for casting two indices of equal size
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value > 1),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape);

// upcast (recursive)
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value < index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape&   to_shape);

// downcast (recursive)
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value > index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape);

// definitions of index_cast follow

// terminal case for casting indices of size 1
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value == 1),
  ToShape
>::type
  index_cast(const FromIndex& from_idx, const FromShape&, const ToShape&)
{
  // from_idx might not be a tuple, but instead a scalar type
  // to ensure we can get the 0th value from from_idx in a uniform way, wrap it first
  return static_cast<ToIndex>(detail::get<0>(wrap_scalar(from_idx)));
}

struct index_cast_functor
{
  template<class ToIndex, class FromIndex, class FromShape, class ToShape>
  __AGENCY_ANNOTATION
  auto operator()(const ToIndex&, const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape)
    -> decltype(
          index_cast<ToIndex>(from_idx, from_shape, to_shape)
       )
  {
    return index_cast<ToIndex>(from_idx, from_shape, to_shape);
  }
};

// when both index types are the same size, index_cast recursively maps itself across the tuples
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value > 1),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape)
{
  return __tu::tuple_map_with_make(index_cast_functor{}, index_cast_detail::make<ToIndex>{}, ToIndex{}, from_idx, from_shape, to_shape);
}

// when FromIndex has fewer elements than ToIndex, we lift it and then cast
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value < index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape&   to_shape)
{
  auto lifted_idx_and_shape = lift_index(from_idx, from_shape, to_shape);
  return index_cast<ToIndex>(detail::get<0>(lifted_idx_and_shape), detail::get<1>(lifted_idx_and_shape), to_shape);
}

// when FromIndex has more elements than ToIndex, we project it and then cast
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value > index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape)
{
  auto projected_idx_and_shape = project_index(from_idx, from_shape);
  return index_cast<ToIndex>(detail::get<0>(projected_idx_and_shape), detail::get<1>(projected_idx_and_shape), to_shape);
}

} // end detail
} // end agency

<commit_msg>Diffentiate between project_index() & project_index_and_shape()<commit_after>#pragma once

#include <type_traits>
#include <tuple>
#include <agency/detail/tuple.hpp>
#include <agency/detail/shape_cast.hpp>
#include <agency/coordinate.hpp>
#include <agency/detail/tuple_utility.hpp>
#include <agency/detail/point_size.hpp>

namespace agency
{
namespace detail
{

template<class Tuple,
         class = typename std::enable_if<
           !std::is_integral<
              typename std::decay<Tuple>::type
            >::value
         >::type>
__AGENCY_ANNOTATION
auto wrap_scalar(Tuple&& t)
  -> decltype(std::forward<Tuple>(t))
{
  return std::forward<Tuple>(t);
}

template<class T,
         class = typename std::enable_if<
           std::is_integral<
             typename std::decay<T>::type
           >::value
         >::type>
__AGENCY_ANNOTATION
auto wrap_scalar(T&& x)
  -> decltype(
       rebind_point_size_t<
         typename std::decay<T>::type,
         1
       >{std::forward<T>(x)}
     )
{
  return rebind_point_size_t<
    typename std::decay<T>::type,
    1
  >{std::forward<T>(x)};
}

template<class IndexTuple, class Size>
__AGENCY_ANNOTATION
auto project_index_and_shape_helper(const IndexTuple& idx, Size size_of_second_to_last_dimension)
  -> typename std::decay<
       decltype(
         unwrap_single_element_tuple(__tu::tuple_drop_last(idx))
       )
     >::type
{
  auto result = detail::tuple_drop_last(idx);

  // multiply the index by the size of the second to last dimension and add
  // that to the second to last index
  __tu::tuple_last(result) += size_of_second_to_last_dimension * __tu::tuple_last(idx);

  return unwrap_single_element_tuple(result);
}

template<class IndexTuple, class ShapeTuple>
__AGENCY_ANNOTATION
auto project_index(const IndexTuple& idx, const ShapeTuple& shape)
  -> decltype(
       project_index_and_shape_helper(idx, __tu::tuple_last(detail::tuple_drop_last(shape)))
     )
{
  // to project an index into the next lower dimension,
  // we combine the last two dimensions into one

  // for a 2D example, consider finding the 1D rank of element (2,2)
  // in a 5 x 4-shaped grid.
  // element (2,2)'s rank is 12 in this grid
  // given idx = (x,y) = (2,2) and shape = (width,height) = (5,4)
  // (2,2)'s 1D rank is computed as
  // y * width + x

  auto size_of_second_to_last_dimension = __tu::tuple_last(detail::tuple_drop_last(shape));

  return project_index_and_shape_helper(idx, size_of_second_to_last_dimension);
}

template<class IndexTuple, class ShapeTuple>
__AGENCY_ANNOTATION
auto project_index_and_shape(const IndexTuple& idx, const ShapeTuple& shape)
  -> decltype(
       detail::make_tuple(
         project_index(idx, shape),
         project_shape(shape)
       )
     )
{
  // to project an index into the next lower dimension,
  // we combine the last two dimensions into one

  // for a 2D example, consider finding the 1D rank of element (2,2)
  // in a 5 x 4-shaped grid.
  // element (2,2)'s rank is 12 in this grid
  // given idx = (x,y) = (2,2) and shape = (width,height) = (5,4)
  // (2,2)'s 1D rank is computed as
  // y * width + x
  auto projected_index = project_index(idx, shape);

  // project the shape
  // this creates a lower dimensional grid with
  // the same number of cells
  // for the shape = (5,4) example, this will compute
  // a 1D shape of 20
  auto projected_shape = project_shape(shape);

  return detail::make_tuple(projected_index, projected_shape);
}

namespace index_cast_detail
{

// to lift a point-like type, add a dimension
template<class Index>
struct lift_t_impl
{
  using type = rebind_point_size_t<Index, point_size<Index>::value + 1>;
};

// to lift a heterogeneous Tuple-like type, repeat the type of the last element
template<template<class...> class tuple, class T, class... Types>
struct lift_t_impl<tuple<T,Types...>>
{
  using last_type = typename std::tuple_element<sizeof...(Types)-1, std::tuple<Types...>>::type;
  using type = tuple<T,Types...,last_type>;
};

template<class T>
struct make
{
  template<class... Args>
  __AGENCY_ANNOTATION
  T operator()(Args&&... args) const
  {
    return T{std::forward<Args>(args)...};
  }
};

} // end index_cast_detail

template<class Point>
using lift_t = typename index_cast_detail::lift_t_impl<Point>::type;

template<class Index, class FromShape, class ToShape>
__AGENCY_ANNOTATION
detail::tuple<lift_t<Index>, lift_t<FromShape>>
  lift_index(const Index& idx, const FromShape& from_shape, const ToShape& to_shape)
{
  // to lift idx into to_shape,
  // take the last element of idx and divide by the corresponding element of to_shape
  // replace the last element of idx with the remainder and append the quotient
  const auto i = index_size<Index>::value - 1;

  auto idx_tuple = wrap_scalar(idx);

  auto intermediate_result = idx_tuple;
  __tu::tuple_last(intermediate_result) %= detail::get<i>(to_shape);

  auto index_maker = index_cast_detail::make<lift_t<Index>>{};

  auto lifted_index = __tu::tuple_append_invoke(intermediate_result, __tu::tuple_last(idx_tuple) / detail::get<i>(to_shape), index_maker);

  // to lift from_shape, simply append the element of to_shape we just divided by
  auto shape_maker = index_cast_detail::make<lift_t<FromShape>>{};
  auto lifted_shape = __tu::tuple_append_invoke(wrap_scalar(from_shape), detail::get<i>(to_shape), shape_maker);

  return detail::make_tuple(lifted_index, lifted_shape);
}

// index_cast is recursive and has various overloads
// declare them here before their definitions

// scalar -> scalar (base case)
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value == 1),
  ToShape
>::type
  index_cast(const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape);

// recursive case for casting two indices of equal size
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value > 1),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape);

// upcast (recursive)
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value < index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape&   to_shape);

// downcast (recursive)
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value > index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape);

// definitions of index_cast follow

// terminal case for casting indices of size 1
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value == 1),
  ToShape
>::type
  index_cast(const FromIndex& from_idx, const FromShape&, const ToShape&)
{
  // from_idx might not be a tuple, but instead a scalar type
  // to ensure we can get the 0th value from from_idx in a uniform way, wrap it first
  return static_cast<ToIndex>(detail::get<0>(wrap_scalar(from_idx)));
}

struct index_cast_functor
{
  template<class ToIndex, class FromIndex, class FromShape, class ToShape>
  __AGENCY_ANNOTATION
  auto operator()(const ToIndex&, const FromIndex& from_idx, const FromShape& from_shape, const ToShape& to_shape)
    -> decltype(
          index_cast<ToIndex>(from_idx, from_shape, to_shape)
       )
  {
    return index_cast<ToIndex>(from_idx, from_shape, to_shape);
  }
};

// when both index types are the same size, index_cast recursively maps itself across the tuples
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value == index_size<ToIndex>::value) &&
  (index_size<FromIndex>::value > 1),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape)
{
  return __tu::tuple_map_with_make(index_cast_functor{}, index_cast_detail::make<ToIndex>{}, ToIndex{}, from_idx, from_shape, to_shape);
}

// when FromIndex has fewer elements than ToIndex, we lift it and then cast
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value < index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape&   to_shape)
{
  auto lifted_idx_and_shape = lift_index(from_idx, from_shape, to_shape);
  return index_cast<ToIndex>(detail::get<0>(lifted_idx_and_shape), detail::get<1>(lifted_idx_and_shape), to_shape);
}

// when FromIndex has more elements than ToIndex, we project it and then cast
template<class ToIndex, class FromIndex, class FromShape, class ToShape>
__AGENCY_ANNOTATION
typename std::enable_if<
  (index_size<FromIndex>::value > index_size<ToIndex>::value),
  ToIndex
>::type
  index_cast(const FromIndex& from_idx,
             const FromShape& from_shape,
             const ToShape& to_shape)
{
  auto projected_idx_and_shape = project_index_and_shape(from_idx, from_shape);
  return index_cast<ToIndex>(detail::get<0>(projected_idx_and_shape), detail::get<1>(projected_idx_and_shape), to_shape);
}

} // end detail
} // end agency

<|endoftext|>


<commit_before><commit_msg>loplugin:simplifybool<commit_after><|endoftext|>


<commit_before>/* *****************************************************************
 *
 * Copyright 2015 Samsung Electronics All Rights Reserved.
 *
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * *****************************************************************/

#include <ocstack.h>
#include <oic_malloc.h>
#include <OCApi.h>
#include <OCPlatform_impl.h>
#include <oxmjustworks.h>
#include <oxmrandompin.h>
#include <srmutility.h>
#include <OCProvisioningManager.hpp>
#include <gtest/gtest.h>

#define TIMEOUT 5

namespace OCProvisioningTest
{
    using namespace OC;

    void resultCallback(PMResultList_t *result, int hasError)
    {
        (void)result;
        (void)hasError;
    }

    TEST(ProvisionInitTest, TestWithEmptyPath)
    {
        std::string dbPath("");
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
    }

    TEST(ProvisionInitTest, TestValidPath)
    {
        std::string dbPath("./dbPath.tmp");
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
    }

    TEST(DiscoveryTest, SecureResource)
    {
        std::shared_ptr< OC::OCSecureResource > secureResource;
        OicUuid_t uuid;
        ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);

        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverSingleDevice(TIMEOUT, &uuid, secureResource));
    }

    TEST(DiscoveryTest, SecureResourceZeroTimeout)
    {
        std::shared_ptr< OC::OCSecureResource > secureResource;
        OicUuid_t uuid;
        ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);

        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverSingleDevice(0, &uuid, secureResource));
    }

    TEST(DiscoveryTest, UnownedDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverUnownedDevices(TIMEOUT, list));
    }

    TEST(DiscoveryTest, UnownedDevicesZeroTimeout)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverUnownedDevices(0, list));
    }

#ifdef MULTIPLE_OWNER
    TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnerEnabledDevices(TIMEOUT, list));
    }

    TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevicesZeroTimeOut)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnerEnabledDevices(0, list));
    }

    TEST(MOTDiscoveryTest, MultipleOwnedDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnedDevices(TIMEOUT, list));
    }

    TEST(MOTDiscoveryTest, MultipleOwnedDevicesZeroTimeOut)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnedDevices(0, list));
    }
#endif

    TEST(DiscoveryTest, OwnedDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverOwnedDevices(TIMEOUT, list));
    }

    TEST(DiscoveryTest, OwnedDevicesZeroTimeout)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverOwnedDevices(0, list));
    }

    TEST(OwnershipTest, OwnershipTransferNullCallback)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doOwnershipTransfer(nullptr));
    }

#ifdef MULTIPLE_OWNER
    TEST(MOTOwnershipTest, MOTOwnershipTransferNullCallback)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doMultipleOwnershipTransfer(nullptr));
    }

    TEST(selectMOTMethodTest, selectMOTMethodNullCallback)
    {
        OCSecureResource device;
        const OicSecOxm_t stsecOxm = OIC_PRECONFIG_PIN;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.selectMOTMethod(stsecOxm, nullptr));
    }

    TEST(changeMOTModeTest, changeMOTModeNullCallback)
    {
        OCSecureResource device;
        const OicSecMomType_t momType = OIC_MULTIPLE_OWNER_ENABLE;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.changeMOTMode(momType, nullptr));
    }

    TEST(addPreconfigPINTest, addPreconfigPINNullPin)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.addPreconfigPIN(nullptr, 0));
    }

    TEST(provisionPreconfPinTest, provisionPreconfPinNullCallback)
    {
        OCSecureResource device;
        const char *pin = "test";
        size_t PinLength = 4;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPreconfPin(pin, PinLength, nullptr));
    }

    TEST(isMOTEnabledTest, isMOTEnabledWithoutDeviceInst)
    {
        OCSecureResource device;
        EXPECT_FALSE(device.isMOTEnabled());
    }

    TEST(isMOTSupportedTest, isMOTSupportedWithoutDeviceInst)
    {
        OCSecureResource device;
        EXPECT_FALSE(device.isMOTSupported());
    }

    TEST(getMOTMethodTest, getMOTMethodNullOxM)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.getMOTMethod(nullptr));
    }
#endif

    TEST(DeviceInfoTest, DevInfoFromNetwork)
    {
        std::string dbPath("./dbPath");
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
        DeviceList_t owned, unowned;
        EXPECT_EQ(OC_STACK_OK, OCSecure::getDevInfoFromNetwork(TIMEOUT,
                    owned, unowned));
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
    }

    TEST(SetDisplayPinCBTest, SetDisplayPinCBTestNullCB)
    {
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDisplayPinCB(nullptr));
    }

    TEST(ProvisionAclTest, ProvisionAclTestNullAcl)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, resultCallback));
    }

    TEST(ProvisionAclTest, ProvisionAclTestNullCallback)
    {
        OCSecureResource device;
        OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionACL(acl, nullptr));
        OICFree(acl);
    }

    TEST(ProvisionAclTest, ProvisionAclTestNullCallbackNUllAcl)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, nullptr));
    }

    TEST(ProvisionCredTest, ProvisionCredTestNullCallback)
    {
        OCSecureResource device, dev2;
        Credential cred;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionCredentials(cred, dev2, nullptr));
    }

    TEST(ProvisionPairwiseTest, ProvisionPairwiseTestNullCallback)
    {
        OCSecureResource device, dev2;
        Credential cred;
        OicSecAcl_t *acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
        OicSecAcl_t *acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPairwiseDevices(cred, acl1,
                    dev2, acl2, nullptr));
        OICFree(acl1);
        OICFree(acl2);
    }

#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
    TEST(setDeviceIdSeed, NullParam)
    {
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(NULL, 0));
    }

    TEST(setDeviceIdSeed, InvalidParam)
    {
        uint8_t seed[1024] = {0};

        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, 0));
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
    }

    TEST(setDeviceIdSeed, ValidValue)
    {
        uint8_t seed[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                            0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
        EXPECT_EQ(OC_STACK_OK, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
    }
#endif // __WITH_DTLS__ || __WITH_TLS__
}
<commit_msg>IOT-2848 Fix for intermitent read error<commit_after>/* *****************************************************************
 *
 * Copyright 2015 Samsung Electronics All Rights Reserved.
 *
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * *****************************************************************/

#include <ocstack.h>
#include <oic_malloc.h>
#include <OCApi.h>
#include <OCPlatform_impl.h>
#include <oxmjustworks.h>
#include <oxmrandompin.h>
#include <srmutility.h>
#include <OCProvisioningManager.hpp>
#include <gtest/gtest.h>

#define TIMEOUT 5
#define DB_FILE "./dbPath.tmp"

namespace OCProvisioningTest
{
    using namespace OC;

    void resultCallback(PMResultList_t *result, int hasError)
    {
        (void)result;
        (void)hasError;
    }

    TEST(ProvisionInitTest, TestWithEmptyPath)
    {
        std::string dbPath("");
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
    }

    TEST(ProvisionInitTest, TestValidPath)
    {
        std::string dbPath(DB_FILE);
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
    }

    TEST(DiscoveryTest, SecureResource)
    {
        std::shared_ptr< OC::OCSecureResource > secureResource;
        OicUuid_t uuid;
        ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);

        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverSingleDevice(TIMEOUT, &uuid, secureResource));
    }

    TEST(DiscoveryTest, SecureResourceZeroTimeout)
    {
        std::shared_ptr< OC::OCSecureResource > secureResource;
        OicUuid_t uuid;
        ConvertStrToUuid("11111111-1111-1111-1111-111111111111", &uuid);

        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverSingleDevice(0, &uuid, secureResource));
    }

    TEST(DiscoveryTest, UnownedDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverUnownedDevices(TIMEOUT, list));
    }

    TEST(DiscoveryTest, UnownedDevicesZeroTimeout)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverUnownedDevices(0, list));
    }

#ifdef MULTIPLE_OWNER
    TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnerEnabledDevices(TIMEOUT, list));
    }

    TEST(MOTDiscoveryTest, MultipleOwnerEnabledDevicesZeroTimeOut)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnerEnabledDevices(0, list));
    }

    TEST(MOTDiscoveryTest, MultipleOwnedDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverMultipleOwnedDevices(TIMEOUT, list));
    }

    TEST(MOTDiscoveryTest, MultipleOwnedDevicesZeroTimeOut)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverMultipleOwnedDevices(0, list));
    }
#endif

    TEST(DiscoveryTest, OwnedDevices)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_OK, OCSecure::discoverOwnedDevices(TIMEOUT, list));
    }

    TEST(DiscoveryTest, OwnedDevicesZeroTimeout)
    {
        DeviceList_t list;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::discoverOwnedDevices(0, list));
    }

    TEST(OwnershipTest, OwnershipTransferNullCallback)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doOwnershipTransfer(nullptr));
    }

#ifdef MULTIPLE_OWNER
    TEST(MOTOwnershipTest, MOTOwnershipTransferNullCallback)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.doMultipleOwnershipTransfer(nullptr));
    }

    TEST(selectMOTMethodTest, selectMOTMethodNullCallback)
    {
        OCSecureResource device;
        const OicSecOxm_t stsecOxm = OIC_PRECONFIG_PIN;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.selectMOTMethod(stsecOxm, nullptr));
    }

    TEST(changeMOTModeTest, changeMOTModeNullCallback)
    {
        OCSecureResource device;
        const OicSecMomType_t momType = OIC_MULTIPLE_OWNER_ENABLE;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.changeMOTMode(momType, nullptr));
    }

    TEST(addPreconfigPINTest, addPreconfigPINNullPin)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.addPreconfigPIN(nullptr, 0));
    }

    TEST(provisionPreconfPinTest, provisionPreconfPinNullCallback)
    {
        OCSecureResource device;
        const char *pin = "test";
        size_t PinLength = 4;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPreconfPin(pin, PinLength, nullptr));
    }

    TEST(isMOTEnabledTest, isMOTEnabledWithoutDeviceInst)
    {
        OCSecureResource device;
        EXPECT_FALSE(device.isMOTEnabled());
    }

    TEST(isMOTSupportedTest, isMOTSupportedWithoutDeviceInst)
    {
        OCSecureResource device;
        EXPECT_FALSE(device.isMOTSupported());
    }

    TEST(getMOTMethodTest, getMOTMethodNullOxM)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.getMOTMethod(nullptr));
    }
#endif

    TEST(DeviceInfoTest, DevInfoFromNetwork)
    {
        std::string dbPath(DB_FILE);
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
        DeviceList_t owned, unowned;
        EXPECT_EQ(OC_STACK_OK, OCSecure::getDevInfoFromNetwork(TIMEOUT,
                    owned, unowned));
        EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
    }

    TEST(SetDisplayPinCBTest, SetDisplayPinCBTestNullCB)
    {
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDisplayPinCB(nullptr));
    }

    TEST(ProvisionAclTest, ProvisionAclTestNullAcl)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, resultCallback));
    }

    TEST(ProvisionAclTest, ProvisionAclTestNullCallback)
    {
        OCSecureResource device;
        OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionACL(acl, nullptr));
        OICFree(acl);
    }

    TEST(ProvisionAclTest, ProvisionAclTestNullCallbackNUllAcl)
    {
        OCSecureResource device;
        EXPECT_EQ(OC_STACK_INVALID_PARAM, device.provisionACL(nullptr, nullptr));
    }

    TEST(ProvisionCredTest, ProvisionCredTestNullCallback)
    {
        OCSecureResource device, dev2;
        Credential cred;
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionCredentials(cred, dev2, nullptr));
    }

    TEST(ProvisionPairwiseTest, ProvisionPairwiseTestNullCallback)
    {
        OCSecureResource device, dev2;
        Credential cred;
        OicSecAcl_t *acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
        OicSecAcl_t *acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
        EXPECT_EQ(OC_STACK_INVALID_CALLBACK, device.provisionPairwiseDevices(cred, acl1,
                    dev2, acl2, nullptr));
        OICFree(acl1);
        OICFree(acl2);
    }

#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
    TEST(setDeviceIdSeed, NullParam)
    {
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(NULL, 0));
    }

    TEST(setDeviceIdSeed, InvalidParam)
    {
        uint8_t seed[1024] = {0};

        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, 0));
        EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
    }

    TEST(setDeviceIdSeed, ValidValue)
    {
        uint8_t seed[16] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                            0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10};
        EXPECT_EQ(OC_STACK_OK, OCSecure::setDeviceIdSeed(seed, sizeof(seed)));
    }
#endif // __WITH_DTLS__ || __WITH_TLS__
}
<|endoftext|>


<commit_before>#undef _FORTIFY_SOURCE

#include "reader.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#include <sys/time.h>

reader::reader(const char *fname)
{
  char msg[4096];
  sprintf(msg, "Open %s", fname);
  int fd = open(fname, O_RDONLY);
  if(fd<0) {
    perror(msg);
    exit(2);
  }

  int size = lseek(fd, 0, SEEK_END);
  lseek(fd, 0, SEEK_SET);

  data = (char *)malloc(size+1);
  read(fd, data, size);
  data[size] = 0;
  close(fd);

  pos = data;
  has_nl = false;
}

reader::~reader()
{
  free((void *)data);
}

const char *reader::gw()
{
  assert(!has_nl);
  while(*pos == ' ')
    pos++;
  const char *r = pos;
  while(*pos != ' ' && *pos != '\n')
    pos++;
  assert(pos != r);
  has_nl = *pos == '\n';
  *pos++ = 0;
  return r;
}

const char *reader::gwnl()
{
  assert(!has_nl);
  while(*pos == ' ')
    pos++;
  const char *r = pos;
  while(*pos && *pos != '\n')
    pos++;
  if(*pos) {
    has_nl = true;
    *pos++ = 0;
  } else
    has_nl = false;
  return r;
}

void reader::nl()
{
  if(!has_nl) {
    while(*pos && *pos != '\n')
      pos++;
    if(*pos)
      pos++;
  }
  has_nl = false;
}

int reader::gi()
{
  return strtol(gw(), 0, 10);
}

double reader::gd()
{
  return strtod(gw(), 0);
}

bool reader::eof()
{
  return !*pos;
}

bool reader::eol()
{
  return has_nl;
}

char reader::peek()
{
  return *pos;
}
<commit_msg>lseek is an upper bound on Windows- fix to get number of chars.<commit_after>#undef _FORTIFY_SOURCE

#include "reader.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#include <sys/time.h>

reader::reader(const char *fname)
{
  char msg[4096];
  sprintf(msg, "Open %s", fname);
  int fd = open(fname, O_RDONLY);
  if(fd<0) {
    perror(msg);
    exit(2);
  }

  // On Windows, lseek is upper bound for text files, thanks to
  // CLRF translation.
  int size = lseek(fd, 0, SEEK_END);
  lseek(fd, 0, SEEK_SET);

  data = (char *)malloc(size+1);
  #ifdef _WIN32
    // Full read of file will get number of characters. If not buffering
    // full file, getc in for loop might be better.
    int char_size = read(fd, data, size);
    assert(char_size <= size);
    data[char_size] = 0;
  #else
    read(fd, data, size);
    data[size] = 0;
  #endif
  close(fd);

  pos = data;
  has_nl = false;
}

reader::~reader()
{
  free((void *)data);
}

const char *reader::gw()
{
  assert(!has_nl);
  while(*pos == ' ')
    pos++;
  const char *r = pos;
  while(*pos != ' ' && *pos != '\n')
    pos++;
  assert(pos != r);
  has_nl = *pos == '\n';
  *pos++ = 0;
  return r;
}

const char *reader::gwnl()
{
  assert(!has_nl);
  while(*pos == ' ')
    pos++;
  const char *r = pos;
  while(*pos && *pos != '\n')
    pos++;
  if(*pos) {
    has_nl = true;
    *pos++ = 0;
  } else
    has_nl = false;
  return r;
}

void reader::nl()
{
  if(!has_nl) {
    while(*pos && *pos != '\n')
      pos++;
    if(*pos)
      pos++;
  }
  has_nl = false;
}

int reader::gi()
{
  return strtol(gw(), 0, 10);
}

double reader::gd()
{
  return strtod(gw(), 0);
}

bool reader::eof()
{
  return !*pos;
}

bool reader::eol()
{
  return has_nl;
}

char reader::peek()
{
  return *pos;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 ARM Limited
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Lisa Hsu
 */

/**
 * @file
 * Declaration of an associative set
 */

#ifndef __CACHESET_HH__
#define __CACHESET_HH__

#include <cassert>

#include "mem/cache/blk.hh" // base class

/**
 * An associative set of cache blocks.
 */
template <class Blktype>
class CacheSet
{
  public:
    /** The associativity of this set. */
    int assoc;

    /** Cache blocks in this set, maintained in LRU order 0 = MRU. */
    Blktype **blks;

    /**
     * Find a block matching the tag in this set.
     * @param way_id The id of the way that matches the tag.
     * @param tag The Tag to find.
     * @param is_secure True if the target memory space is secure.
     * @return Pointer to the block if found. Set way_id to assoc if none found
     */
    Blktype* findBlk(Addr tag, bool is_secure, int& way_id) const ;
    Blktype* findBlk(Addr tag, bool is_secure) const ;

    /**
     * Move the given block to the head of the list.
     * @param blk The block to move.
     */
    void moveToHead(Blktype *blk);

    /**
     * Move the given block to the tail of the list.
     * @param blk The block to move
     */
    void moveToTail(Blktype *blk);

};

template <class Blktype>
Blktype*
CacheSet<Blktype>::findBlk(Addr tag, bool is_secure, int& way_id) const
{
    /**
     * Way_id returns the id of the way that matches the block
     * If no block is found way_id is set to assoc.
     */
    way_id = assoc;
    for (int i = 0; i < assoc; ++i) {
        if (blks[i]->tag == tag && blks[i]->isValid() &&
            blks[i]->isSecure() == is_secure) {
            way_id = i;
            return blks[i];
        }
    }
    return NULL;
}

template <class Blktype>
Blktype*
CacheSet<Blktype>::findBlk(Addr tag, bool is_secure) const
{
    int ignored_way_id;
    return findBlk(tag, is_secure, ignored_way_id);
}

template <class Blktype>
void
CacheSet<Blktype>::moveToHead(Blktype *blk)
{
    // nothing to do if blk is already head
    if (blks[0] == blk)
        return;

    // write 'next' block into blks[i], moving up from MRU toward LRU
    // until we overwrite the block we moved to head.

    // start by setting up to write 'blk' into blks[0]
    int i = 0;
    Blktype *next = blk;

    do {
        assert(i < assoc);
        // swap blks[i] and next
        Blktype *tmp = blks[i];
        blks[i] = next;
        next = tmp;
        ++i;
    } while (next != blk);
}

template <class Blktype>
void
CacheSet<Blktype>::moveToTail(Blktype *blk)
{
    // nothing to do if blk is already tail
    if (blks[assoc - 1] == blk)
        return;

    // write 'next' block into blks[i], moving from LRU to MRU
    // until we overwrite the block we moved to tail.

    // start by setting up to write 'blk' into tail
    int i = assoc - 1;
    Blktype *next = blk;

    do {
        assert(i >= 0);
        // swap blks[i] and next
        Blktype *tmp = blks[i];
        blks[i] = next;
        next = tmp;
        --i;
    } while (next != blk);
}

#endif
<commit_msg>mem: Tidy up CacheSet<commit_after>/*
 * Copyright (c) 2013 ARM Limited
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Lisa Hsu
 */

/**
 * @file
 * Declaration of an associative set
 */

#ifndef __MEM_CACHE_TAGS_CACHESET_HH__
#define __MEM_CACHE_TAGS_CACHESET_HH__

#include <cassert>

/**
 * An associative set of cache blocks.
 */
template <class Blktype>
class CacheSet
{
  public:
    /** The associativity of this set. */
    int assoc;

    /** Cache blocks in this set, maintained in LRU order 0 = MRU. */
    Blktype **blks;

    /**
     * Find a block matching the tag in this set.
     * @param way_id The id of the way that matches the tag.
     * @param tag The Tag to find.
     * @param is_secure True if the target memory space is secure.
     * @return Pointer to the block if found. Set way_id to assoc if none found
     */
    Blktype* findBlk(Addr tag, bool is_secure, int& way_id) const ;
    Blktype* findBlk(Addr tag, bool is_secure) const ;

    /**
     * Move the given block to the head of the list.
     * @param blk The block to move.
     */
    void moveToHead(Blktype *blk);

    /**
     * Move the given block to the tail of the list.
     * @param blk The block to move
     */
    void moveToTail(Blktype *blk);

};

template <class Blktype>
Blktype*
CacheSet<Blktype>::findBlk(Addr tag, bool is_secure, int& way_id) const
{
    /**
     * Way_id returns the id of the way that matches the block
     * If no block is found way_id is set to assoc.
     */
    way_id = assoc;
    for (int i = 0; i < assoc; ++i) {
        if (blks[i]->tag == tag && blks[i]->isValid() &&
            blks[i]->isSecure() == is_secure) {
            way_id = i;
            return blks[i];
        }
    }
    return NULL;
}

template <class Blktype>
Blktype*
CacheSet<Blktype>::findBlk(Addr tag, bool is_secure) const
{
    int ignored_way_id;
    return findBlk(tag, is_secure, ignored_way_id);
}

template <class Blktype>
void
CacheSet<Blktype>::moveToHead(Blktype *blk)
{
    // nothing to do if blk is already head
    if (blks[0] == blk)
        return;

    // write 'next' block into blks[i], moving up from MRU toward LRU
    // until we overwrite the block we moved to head.

    // start by setting up to write 'blk' into blks[0]
    int i = 0;
    Blktype *next = blk;

    do {
        assert(i < assoc);
        std::swap(blks[i], next);
        ++i;
    } while (next != blk);
}

template <class Blktype>
void
CacheSet<Blktype>::moveToTail(Blktype *blk)
{
    // nothing to do if blk is already tail
    if (blks[assoc - 1] == blk)
        return;

    // write 'next' block into blks[i], moving from LRU to MRU
    // until we overwrite the block we moved to tail.

    // start by setting up to write 'blk' into tail
    int i = assoc - 1;
    Blktype *next = blk;

    do {
        assert(i >= 0);
        std::swap(blks[i], next);
        --i;
    } while (next != blk);
}

#endif
<|endoftext|>


<commit_before>#include "ortools/base/commandlineflags.h"
#include "ortools/base/logging.h"
#include "ortools/linear_solver/linear_solver.h"

namespace operations_research {
void SolveLP() {
  MPSolver solver("test", MPSolver::CBC_MIXED_INTEGER_PROGRAMMING);
  const double kInfinity = solver.infinity();
  MPVariable* const x = solver.MakeNumVar(-kInfinity, kInfinity, "x");

  MPObjective* const objective = solver.MutableObjective();
  objective->SetMaximization();
  objective->SetCoefficient(x, 1);

  MPConstraint* const constraint = solver.MakeRowConstraint(0, 5);
  constraint->SetCoefficient(x, 1);

  solver.Solve();
}

void BreakLoop() {
  for (int i = 0; i < 500; i++) {
    SolveLP();
  }
}
}  // namespace operations_research

int main(int argc, char** argv) {
  absl::ParseCommandLine(argc, argv);
  operations_research::BreakLoop();
  return 0;
}
<commit_msg>cpp(test): Fix tests when SCIP and COINOR are disabled (#3261)<commit_after>#include "ortools/base/commandlineflags.h"
#include "ortools/base/logging.h"
#include "ortools/linear_solver/linear_solver.h"

namespace operations_research {
void SolveLP() {
  // Create the linear solver with the GLOP backend.
  std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("CBC"));
  if (!solver) {
    return;
  }
  const double kInfinity = solver->infinity();
  MPVariable* const x = solver->MakeNumVar(-kInfinity, kInfinity, "x");

  MPObjective* const objective = solver->MutableObjective();
  objective->SetMaximization();
  objective->SetCoefficient(x, 1);

  MPConstraint* const constraint = solver->MakeRowConstraint(0, 5);
  constraint->SetCoefficient(x, 1);

  solver->Solve();
}

void BreakLoop() {
  for (int i = 0; i < 500; i++) {
    SolveLP();
  }
}
}  // namespace operations_research

int main(int argc, char** argv) {
  absl::ParseCommandLine(argc, argv);
  operations_research::BreakLoop();
  return 0;
}
<|endoftext|>


<commit_before>//
// Created by martin on 11/02/19.
//
#include <iostream>
#include <gtest/gtest.h>
#include <ros/package.h>
#include "ros/ros.h"
#include "std_msgs/String.h"

#include "rosplan_planning_system/PlannerInterface/POPFPlannerInterface.h"
#include "rosplan_planning_system/PlannerInterface/PlannerInterface.h"
#include "rosplan_dispatch_msgs/PlanningService.h"
#include <cstdlib>

    bool plan_received;
    std::string last_plan;

    void testCallback(const std_msgs::String::ConstPtr &plan) {
        ROS_INFO("I heard: [%s]", plan->data.c_str());
        last_plan = plan->data;
        plan_received = true;
    }

    GTEST_TEST(PlannerInterfaceTests, Test1_plan_found) {

        ros::NodeHandle n("~");

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        ASSERT_EQ(1, client1.call(srv));
        ASSERT_EQ(1, srv.response.plan_found);

    }

    GTEST_TEST(PlannerInterfaceTests, Test2_planner_output_against_known_plan) {

        ros::NodeHandle n("~");

        ros::Subscriber sub = n.subscribe<std_msgs::String>("/rosplan_planner_interface/planner_output", 1000, &testCallback);
        ros::Publisher pub = n.advertise<std_msgs::String>("/rosplan_problem_interface/problem_instance", 1000);

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        std::ifstream t(rosplan_demos_path + "/common/test_problem.pddl");
        std::stringstream ss;
        ss << t.rdbuf();

        std_msgs::String msg;
        msg.data = ss.str();
        pub.publish(msg);

        ros::spinOnce();

        // call service to generate plan
        client1.call(srv);

        // wait to receive the planner output
        ros::Rate loop_rate = 10;
        plan_received = false;
        while (!plan_received && ros::ok()) {
            loop_rate.sleep();
            ros::spinOnce();

        }
        std::string known_plan = "0.000: (movetob ball)  [0.001]\n";

        // checking the plan
        ASSERT_EQ(1, srv.response.plan_found);
        ASSERT_EQ(last_plan, known_plan);

    }

    GTEST_TEST(PlannerInterfaceTests, Test3_problem_without_solution) {
        ros::NodeHandle n("~");

        ros::Subscriber sub = n.subscribe<std_msgs::String>("/rosplan_planner_interface/planner_output", 1000, &testCallback);
        ros::Publisher pub = n.advertise<std_msgs::String>("/rosplan_problem_interface/problem_instance", 1000);

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem_no_solution.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        std::ifstream t(rosplan_demos_path + "/common/test_problem_no_solution.pddl");
        std::stringstream ss;
        ss << t.rdbuf();

        std_msgs::String msg;
        msg.data = ss.str();
        pub.publish(msg);

        ros::spinOnce();

        // call service to generate plan
        bool call_answer = client1.call(srv);

        ASSERT_EQ(1, call_answer);
        ASSERT_EQ(0, srv.response.plan_found);

    }

    GTEST_TEST(PlannerInterfaceTests, Test4_invalid_pddl_syntax) {

        ros::NodeHandle n("~");

        ros::Subscriber sub = n.subscribe<std_msgs::String>("/rosplan_planner_interface/planner_output", 1000, &testCallback);
        ros::Publisher pub = n.advertise<std_msgs::String>("/rosplan_problem_interface/problem_instance", 1000);

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem_invalid_syntax.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        std::ifstream t(rosplan_demos_path + "/common/test_problem_invalid_syntax.pddl");
        std::stringstream ss;
        ss << t.rdbuf();

        std_msgs::String msg;
        msg.data = ss.str();
        pub.publish(msg);

        ros::spinOnce();

        // call service to generate plan
        bool call_answer = client1.call(srv);

        ASSERT_EQ(1, call_answer);
        ASSERT_EQ(0, srv.response.plan_found);

    }

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

            ::testing::InitGoogleTest(&argc, argv);
            ros::init(argc, argv, "PlannerInterfaceTests");

            ros::NodeHandle n("~");

            return RUN_ALL_TESTS();
    }<commit_msg>First commit in unit-tests branch<commit_after>//
// Created by martin on 11/02/19.
//
#include <iostream>
#include <gtest/gtest.h>
#include <ros/package.h>
#include "ros/ros.h"
#include "std_msgs/String.h"

#include "rosplan_planning_system/PlannerInterface/POPFPlannerInterface.h"
#include "rosplan_planning_system/PlannerInterface/PlannerInterface.h"
#include "rosplan_dispatch_msgs/PlanningService.h"
#include <cstdlib>

    bool plan_received;
    std::string last_plan;

    void testCallback(const std_msgs::String::ConstPtr &plan) {
        ROS_INFO("I heard: [%s]", plan->data.c_str());
        last_plan = plan->data;
        plan_received = true;
    }

    GTEST_TEST(PlannerInterfaceTests, Test1_plan_found) {

        ros::NodeHandle n("~");

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        ASSERT_EQ(1, client1.call(srv));
        ASSERT_EQ(1, srv.response.plan_found);

    }

    GTEST_TEST(PlannerInterfaceTests, Test2_planner_output_against_known_plan) {

        ros::NodeHandle n("~");

        ros::Subscriber sub = n.subscribe<std_msgs::String>("/rosplan_planner_interface/planner_output", 1000, &testCallback);
        ros::Publisher pub = n.advertise<std_msgs::String>("/rosplan_problem_interface/problem_instance", 1000);

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        std::ifstream t(rosplan_demos_path + "/common/test_problem.pddl");
        std::stringstream ss;
        ss << t.rdbuf();

        std_msgs::String msg;
        msg.data = ss.str();
        pub.publish(msg);

        ros::spinOnce();

        // call service to generate plan
        client1.call(srv);

        // wait to receive the planner output
        ros::Rate loop_rate = 10;
        plan_received = false;
        while (!plan_received && ros::ok()) {
            loop_rate.sleep();
            ros::spinOnce();

        }
        std::string known_plan = "0.000: (movetob ball)  [0.001]\n";

        // checking the plan
        ASSERT_EQ(1, srv.response.plan_found);
        ASSERT_EQ(last_plan, known_plan);

    }

    GTEST_TEST(PlannerInterfaceTests, Test3_problem_without_solution) {
        ros::NodeHandle n("~");

        ros::Subscriber sub = n.subscribe<std_msgs::String>("/rosplan_planner_interface/planner_output", 1000, &testCallback);
        ros::Publisher pub = n.advertise<std_msgs::String>("/rosplan_problem_interface/problem_instance", 1000);

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem_no_solution.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        std::ifstream t(rosplan_demos_path + "/common/test_problem_no_solution.pddl");
        std::stringstream ss;
        ss << t.rdbuf();

        std_msgs::String msg;
        msg.data = ss.str();
        pub.publish(msg);

        ros::spinOnce();

        // call service to generate plan
        bool call_answer = client1.call(srv);

        ASSERT_EQ(1, call_answer);
        ASSERT_EQ(0, srv.response.plan_found);

    }

    GTEST_TEST(PlannerInterfaceTests, Test4_invalid_pddl_syntax) {

        ros::NodeHandle n("~");

        ros::Subscriber sub = n.subscribe<std_msgs::String>("/rosplan_planner_interface/planner_output", 1000, &testCallback);
        ros::Publisher pub = n.advertise<std_msgs::String>("/rosplan_problem_interface/problem_instance", 1000);

        ros::ServiceClient client1 = n.serviceClient<rosplan_dispatch_msgs::PlanningService>("/rosplan_planner_interface/planning_server_params");
        rosplan_dispatch_msgs::PlanningService srv;

        std::string rosplan_demos_path = ros::package::getPath("rosplan_demos");
        std::string rosplan_planning_system_path = ros::package::getPath("rosplan_planning_system");

        srv.request.use_problem_topic = false;
        srv.request.data_path = rosplan_demos_path + "/common/";
        srv.request.domain_path = rosplan_demos_path + "/common/test_domain.pddl";
        srv.request.problem_path = rosplan_demos_path + "/common/test_problem_invalid_syntax.pddl";
        srv.request.planner_command = "timeout 10 " + rosplan_planning_system_path + "/common/bin/popf -n DOMAIN PROBLEM";

        std::ifstream t(rosplan_demos_path + "/common/test_problem_invalid_syntax.pddl");
        std::stringstream ss;
        ss << t.rdbuf();

        std_msgs::String msg;
        msg.data = ss.str();
        pub.publish(msg);

        ros::spinOnce();

        // call service to generate plan
        bool call_answer = client1.call(srv);

        ASSERT_EQ(1, call_answer);
        ASSERT_EQ(0, srv.response.plan_found);

    }

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

            ::testing::InitGoogleTest(&argc, argv);
            ros::init(argc, argv, "PlannerInterfaceTests");

            ros::NodeHandle n("~");

            return RUN_ALL_TESTS();
    }<|endoftext|>