<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: astinterface.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#include <idlc/astinterface.hxx>
#include <idlc/astattribute.hxx>
#include <idlc/astoperation.hxx>
#include "idlc/idlc.hxx"

#include "registry/version.h"
#include "registry/writer.hxx"

using namespace ::rtl;

AstInterface::AstInterface(const ::rtl::OString& name,
                           AstInterface const * pInherits,
                           AstScope* pScope)
    : AstType(NT_interface, name, pScope)
    , AstScope(NT_interface)
    , m_mandatoryInterfaces(0)
    , m_bIsDefined(false)
    , m_bForwarded(sal_False)
    , m_bForwardedInSameFile(sal_False)
    , m_bSingleInheritance(pInherits != 0)
{
    if (pInherits != 0) {
        addInheritedInterface(pInherits, false, rtl::OUString());
    }
}

AstInterface::~AstInterface()
{
}

AstInterface::DoubleDeclarations AstInterface::checkInheritedInterfaceClashes(
    AstInterface const * ifc, bool optional) const
{
    DoubleDeclarations doubleDecls;
    std::set< rtl::OString > seen;
    checkInheritedInterfaceClashes(
        doubleDecls, seen, ifc, true, optional, optional);
    return doubleDecls;
}

void AstInterface::addInheritedInterface(
    AstType const * ifc, bool optional, rtl::OUString const & documentation)
{
    m_inheritedInterfaces.push_back(
        InheritedInterface(ifc, optional, documentation));
    if (!optional) {
        ++m_mandatoryInterfaces;
    }
    AstInterface const * resolved = resolveInterfaceTypedefs(ifc);
    addVisibleInterface(resolved, true, optional);
    if (optional) {
        addOptionalVisibleMembers(resolved);
    }
}

AstInterface::DoubleMemberDeclarations AstInterface::checkMemberClashes(
    AstDeclaration const * member) const
{
    DoubleMemberDeclarations doubleMembers;
    checkMemberClashes(doubleMembers, member, true);
    return doubleMembers;
}

void AstInterface::addMember(AstDeclaration /*TODO: const*/ * member) {
    addDeclaration(member);
    m_visibleMembers.insert(
        VisibleMembers::value_type(
            member->getLocalName(), VisibleMember(member)));
}

void AstInterface::forwardDefined(AstInterface const & def)
{
    setImported(def.isImported());
    setInMainfile(def.isInMainfile());
    setLineNumber(def.getLineNumber());
    setFileName(def.getFileName());
    setDocumentation(def.getDocumentation());
    m_inheritedInterfaces = def.m_inheritedInterfaces;
    m_mandatoryInterfaces = def.m_mandatoryInterfaces;
    m_bIsDefined = true;
}

sal_Bool AstInterface::dump(RegistryKey& rKey)
{
    if ( !isDefined() )
        return sal_True;

    RegistryKey localKey;
    if (rKey.createKey( OStringToOUString(getFullName(), RTL_TEXTENCODING_UTF8 ), localKey))
    {
        fprintf(stderr, "%s: warning, could not create key '%s' in '%s'\n",
                idlc()->getOptions()->getProgramName().getStr(),
                getFullName().getStr(), OUStringToOString(rKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
        return sal_False;
    }

    if (m_mandatoryInterfaces > SAL_MAX_UINT16
        || m_inheritedInterfaces.size() - m_mandatoryInterfaces
            > SAL_MAX_UINT16)
    {
        fprintf(
            stderr, "%s: interface %s has too many direct base interfaces\n",
            idlc()->getOptions()->getProgramName().getStr(),
            getScopedName().getStr());
        return false;
    }
    sal_uInt16 nBaseTypes = static_cast< sal_uInt16 >(m_mandatoryInterfaces);
    sal_uInt16 nAttributes = 0;
    sal_uInt16 nMethods = 0;
    sal_uInt16 nReferences = static_cast< sal_uInt16 >(
        m_inheritedInterfaces.size() - m_mandatoryInterfaces);
    typereg_Version version
        = (nBaseTypes <= 1 && nReferences == 0 && !m_bPublished
           ? TYPEREG_VERSION_0 : TYPEREG_VERSION_1);
    {for (DeclList::const_iterator i(getIteratorBegin()); i != getIteratorEnd();
          ++i)
    {
        switch ((*i)->getNodeType()) {
        case NT_attribute:
            {
                if (!increment(&nAttributes, "attributes")) {
                    return false;
                }
//                AstAttribute * attr = static_cast< AstAttribute * >(*i);
                AstAttribute * attr = (AstAttribute *)(*i);
                if (attr->isBound()) {
                    version = TYPEREG_VERSION_1;
                }
                DeclList::size_type getCount = attr->getGetExceptionCount();
                if (getCount > SAL_MAX_UINT16) {
                    fprintf(
                        stderr,
                        ("%s: raises clause of getter for attribute %s of"
                         " interface %s is too long\n"),
                        idlc()->getOptions()->getProgramName().getStr(),
                        (*i)->getLocalName().getStr(),
                        getScopedName().getStr());
                    return false;
                }
                if (getCount > 0) {
                    version = TYPEREG_VERSION_1;
                    if (!increment(&nMethods, "attributes")) {
                        return false;
                    }
                }
                DeclList::size_type setCount = attr->getSetExceptionCount();
                if (setCount > SAL_MAX_UINT16) {
                    fprintf(
                        stderr,
                        ("%s: raises clause of setter for attribute %s of"
                         " interface %s is too long\n"),
                        idlc()->getOptions()->getProgramName().getStr(),
                        (*i)->getLocalName().getStr(),
                        getScopedName().getStr());
                    return false;
                }
                if (setCount > 0) {
                    version = TYPEREG_VERSION_1;
                    if (!increment(&nMethods, "attributes")) {
                        return false;
                    }
                }
                break;
            }

        case NT_operation:
            if (!increment(&nMethods, "methods")) {
                return false;
            }
            break;

        default:
            OSL_ASSERT(false);
            break;
        }
    }}

    OUString emptyStr;
    typereg::Writer aBlob(
        version, getDocumentation(), emptyStr, RT_TYPE_INTERFACE, m_bPublished,
        OStringToOUString(getRelativName(), RTL_TEXTENCODING_UTF8), nBaseTypes,
        nAttributes, nMethods, nReferences);

    sal_uInt16 superTypeIndex = 0;
    sal_uInt16 referenceIndex = 0;
    {for (InheritedInterfaces::iterator i = m_inheritedInterfaces.begin();
          i != m_inheritedInterfaces.end(); ++i)
    {
        if (i->isOptional()) {
            aBlob.setReferenceData(
                referenceIndex++, i->getDocumentation(), RT_REF_SUPPORTS,
                RT_ACCESS_OPTIONAL,
                OStringToOUString(
                    i->getInterface()->getRelativName(),
                    RTL_TEXTENCODING_UTF8));
        } else {
            aBlob.setSuperTypeName(
                superTypeIndex++,
                OStringToOUString(
                    i->getInterface()->getRelativName(),
                    RTL_TEXTENCODING_UTF8));
        }
    }}

    sal_uInt16 attributeIndex = 0;
    sal_uInt16 methodIndex = 0;
    {for (DeclList::const_iterator i(getIteratorBegin()); i != getIteratorEnd();
          ++i)
    {
        switch ((*i)->getNodeType()) {
        case NT_attribute:
//           static_cast< AstAttribute * >(*i)->dumpBlob(

            ((AstAttribute *)(*i))->dumpBlob(
                aBlob, attributeIndex++, &methodIndex);
            break;

        case NT_operation:
//            static_cast< AstOperation * >(*i)->dumpBlob(aBlob, methodIndex++);
            ((AstOperation *)(*i))->dumpBlob(aBlob, methodIndex++);
            break;

        default:
            OSL_ASSERT(false);
            break;
        }
    }}

    sal_uInt32 aBlobSize;
    void const * pBlob = aBlob.getBlob(&aBlobSize);

    if (localKey.setValue(emptyStr, RG_VALUETYPE_BINARY, (RegValue)pBlob, aBlobSize))
    {
        fprintf(stderr, "%s: warning, could not set value of key \"%s\" in %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                getFullName().getStr(), OUStringToOString(localKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
        return sal_False;
    }

    return true;
}

void AstInterface::checkInheritedInterfaceClashes(
    DoubleDeclarations & doubleDeclarations,
    std::set< rtl::OString > & seenInterfaces, AstInterface const * ifc,
    bool direct, bool optional, bool mainOptional) const
{
    if (direct || optional
        || seenInterfaces.insert(ifc->getScopedName()).second)
    {
        VisibleInterfaces::const_iterator visible(
            m_visibleInterfaces.find(ifc->getScopedName()));
        if (visible != m_visibleInterfaces.end()) {
            switch (visible->second) {
            case INTERFACE_INDIRECT_OPTIONAL:
                if (direct && optional) {
                    doubleDeclarations.interfaces.push_back(ifc);
                    return;
                }
                break;

            case INTERFACE_DIRECT_OPTIONAL:
                if (direct || !mainOptional) {
                    doubleDeclarations.interfaces.push_back(ifc);
                }
                return;

            case INTERFACE_INDIRECT_MANDATORY:
                if (direct) {
                    doubleDeclarations.interfaces.push_back(ifc);
                }
                return;

            case INTERFACE_DIRECT_MANDATORY:
                if (direct || !optional && !mainOptional) {
                    doubleDeclarations.interfaces.push_back(ifc);
                }
                return;
            }
        }
        if (direct || !optional) {
            {for (DeclList::const_iterator i(ifc->getIteratorBegin());
                  i != ifc->getIteratorEnd(); ++i)
            {
                checkMemberClashes(
                    doubleDeclarations.members, *i, !mainOptional);
            }}
            {for (InheritedInterfaces::const_iterator i(
                      ifc->m_inheritedInterfaces.begin());
                  i != ifc->m_inheritedInterfaces.end(); ++i)
            {
                checkInheritedInterfaceClashes(
                    doubleDeclarations, seenInterfaces, i->getResolved(),
                    false, i->isOptional(), mainOptional);
            }}
        }
    }
}

void AstInterface::checkMemberClashes(
    DoubleMemberDeclarations & doubleMembers, AstDeclaration const * member,
    bool checkOptional) const
{
    VisibleMembers::const_iterator i(
        m_visibleMembers.find(member->getLocalName()));
    if (i != m_visibleMembers.end()) {
        if (i->second.mandatory != 0) {
            if (i->second.mandatory->getScopedName() != member->getScopedName())
            {
                DoubleMemberDeclaration d;
                d.first = i->second.mandatory;
                d.second = member;
                doubleMembers.push_back(d);
            }
        } else if (checkOptional) {
            for (VisibleMember::Optionals::const_iterator j(
                     i->second.optionals.begin());
                 j != i->second.optionals.end(); ++j)
            {
                if (j->second->getScopedName() != member->getScopedName()) {
                    DoubleMemberDeclaration d;
                    d.first = j->second;
                    d.second = member;
                    doubleMembers.push_back(d);
                }
            }
        }
    }
}

void AstInterface::addVisibleInterface(
    AstInterface const * ifc, bool direct, bool optional)
{
    InterfaceKind kind = optional
        ? direct ? INTERFACE_DIRECT_OPTIONAL : INTERFACE_INDIRECT_OPTIONAL
        : direct ? INTERFACE_DIRECT_MANDATORY : INTERFACE_INDIRECT_MANDATORY;
    std::pair< VisibleInterfaces::iterator, bool > result(
        m_visibleInterfaces.insert(
            VisibleInterfaces::value_type(ifc->getScopedName(), kind)));
    bool seen = !result.second
        && result.first->second >= INTERFACE_INDIRECT_MANDATORY;
    if (!result.second && kind > result.first->second) {
        result.first->second = kind;
    }
    if (!optional && !seen) {
        {for (DeclList::const_iterator i(ifc->getIteratorBegin());
              i != ifc->getIteratorEnd(); ++i)
        {
            m_visibleMembers.insert(
                VisibleMembers::value_type(
                    (*i)->getLocalName(), VisibleMember(*i)));
        }}
        {for (InheritedInterfaces::const_iterator i(
                  ifc->m_inheritedInterfaces.begin());
              i != ifc->m_inheritedInterfaces.end(); ++i)
        {
            addVisibleInterface(i->getResolved(), false, i->isOptional());
        }}
    }
}

void AstInterface::addOptionalVisibleMembers(AstInterface const * ifc) {
    {for (DeclList::const_iterator i(ifc->getIteratorBegin());
          i != ifc->getIteratorEnd(); ++i)
    {
        VisibleMembers::iterator visible(
            m_visibleMembers.find((*i)->getLocalName()));
        if (visible == m_visibleMembers.end()) {
            visible = m_visibleMembers.insert(
                VisibleMembers::value_type(
                    (*i)->getLocalName(), VisibleMember())).first;
        }
        if (visible->second.mandatory == 0) {
            visible->second.optionals.insert(
                VisibleMember::Optionals::value_type(ifc->getScopedName(), *i));
        }
    }}
    {for (InheritedInterfaces::const_iterator i(
              ifc->m_inheritedInterfaces.begin());
          i != ifc->m_inheritedInterfaces.end(); ++i)
    {
        if (!i->isOptional()) {
            addOptionalVisibleMembers(i->getResolved());
        }
    }}
}

bool AstInterface::increment(sal_uInt16 * counter, char const * sort) const {
    if (*counter == SAL_MAX_UINT16) {
        fprintf(
            stderr, "%s: interface %s has too many direct %s\n",
            idlc()->getOptions()->getProgramName().getStr(),
            getScopedName().getStr(), sort);
        return false;
    }
    ++*counter;
    return true;
}
<commit_msg>CWS-TOOLING: integrate CWS cmcfixes50 2008-11-10 13:31:50 +0100 cmc  r263517 : gio doesn't do anything useful for remote stuff wrt info 2008-11-06 00:11:47 +0100 cmc  r263359 : #i93436# pile of other 64bit new gcc warnings 2008-11-05 00:39:03 +0100 cmc  r263340 : i95856 let a ppc64 vanilla build succeed 2008-11-04 14:00:25 +0100 cmc  r263320 : #i93436# useless const 2008-11-04 11:53:10 +0100 cmc  r263314 : #i93436# ambiguous 2008-11-04 11:48:05 +0100 cmc  r263313 : #i93436# add some braces 2008-11-04 11:29:24 +0100 cmc  r263312 : #i93436# ambiguous 2008-11-04 10:53:46 +0100 cmc  r263311 : <commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: astinterface.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"
#include <idlc/astinterface.hxx>
#include <idlc/astattribute.hxx>
#include <idlc/astoperation.hxx>
#include "idlc/idlc.hxx"

#include "registry/version.h"
#include "registry/writer.hxx"

using namespace ::rtl;

AstInterface::AstInterface(const ::rtl::OString& name,
                           AstInterface const * pInherits,
                           AstScope* pScope)
    : AstType(NT_interface, name, pScope)
    , AstScope(NT_interface)
    , m_mandatoryInterfaces(0)
    , m_bIsDefined(false)
    , m_bForwarded(sal_False)
    , m_bForwardedInSameFile(sal_False)
    , m_bSingleInheritance(pInherits != 0)
{
    if (pInherits != 0) {
        addInheritedInterface(pInherits, false, rtl::OUString());
    }
}

AstInterface::~AstInterface()
{
}

AstInterface::DoubleDeclarations AstInterface::checkInheritedInterfaceClashes(
    AstInterface const * ifc, bool optional) const
{
    DoubleDeclarations doubleDecls;
    std::set< rtl::OString > seen;
    checkInheritedInterfaceClashes(
        doubleDecls, seen, ifc, true, optional, optional);
    return doubleDecls;
}

void AstInterface::addInheritedInterface(
    AstType const * ifc, bool optional, rtl::OUString const & documentation)
{
    m_inheritedInterfaces.push_back(
        InheritedInterface(ifc, optional, documentation));
    if (!optional) {
        ++m_mandatoryInterfaces;
    }
    AstInterface const * resolved = resolveInterfaceTypedefs(ifc);
    addVisibleInterface(resolved, true, optional);
    if (optional) {
        addOptionalVisibleMembers(resolved);
    }
}

AstInterface::DoubleMemberDeclarations AstInterface::checkMemberClashes(
    AstDeclaration const * member) const
{
    DoubleMemberDeclarations doubleMembers;
    checkMemberClashes(doubleMembers, member, true);
    return doubleMembers;
}

void AstInterface::addMember(AstDeclaration /*TODO: const*/ * member) {
    addDeclaration(member);
    m_visibleMembers.insert(
        VisibleMembers::value_type(
            member->getLocalName(), VisibleMember(member)));
}

void AstInterface::forwardDefined(AstInterface const & def)
{
    setImported(def.isImported());
    setInMainfile(def.isInMainfile());
    setLineNumber(def.getLineNumber());
    setFileName(def.getFileName());
    setDocumentation(def.getDocumentation());
    m_inheritedInterfaces = def.m_inheritedInterfaces;
    m_mandatoryInterfaces = def.m_mandatoryInterfaces;
    m_bIsDefined = true;
}

sal_Bool AstInterface::dump(RegistryKey& rKey)
{
    if ( !isDefined() )
        return sal_True;

    RegistryKey localKey;
    if (rKey.createKey( OStringToOUString(getFullName(), RTL_TEXTENCODING_UTF8 ), localKey))
    {
        fprintf(stderr, "%s: warning, could not create key '%s' in '%s'\n",
                idlc()->getOptions()->getProgramName().getStr(),
                getFullName().getStr(), OUStringToOString(rKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
        return sal_False;
    }

    if (m_mandatoryInterfaces > SAL_MAX_UINT16
        || m_inheritedInterfaces.size() - m_mandatoryInterfaces
            > SAL_MAX_UINT16)
    {
        fprintf(
            stderr, "%s: interface %s has too many direct base interfaces\n",
            idlc()->getOptions()->getProgramName().getStr(),
            getScopedName().getStr());
        return false;
    }
    sal_uInt16 nBaseTypes = static_cast< sal_uInt16 >(m_mandatoryInterfaces);
    sal_uInt16 nAttributes = 0;
    sal_uInt16 nMethods = 0;
    sal_uInt16 nReferences = static_cast< sal_uInt16 >(
        m_inheritedInterfaces.size() - m_mandatoryInterfaces);
    typereg_Version version
        = (nBaseTypes <= 1 && nReferences == 0 && !m_bPublished
           ? TYPEREG_VERSION_0 : TYPEREG_VERSION_1);
    {for (DeclList::const_iterator i(getIteratorBegin()); i != getIteratorEnd();
          ++i)
    {
        switch ((*i)->getNodeType()) {
        case NT_attribute:
            {
                if (!increment(&nAttributes, "attributes")) {
                    return false;
                }
//                AstAttribute * attr = static_cast< AstAttribute * >(*i);
                AstAttribute * attr = (AstAttribute *)(*i);
                if (attr->isBound()) {
                    version = TYPEREG_VERSION_1;
                }
                DeclList::size_type getCount = attr->getGetExceptionCount();
                if (getCount > SAL_MAX_UINT16) {
                    fprintf(
                        stderr,
                        ("%s: raises clause of getter for attribute %s of"
                         " interface %s is too long\n"),
                        idlc()->getOptions()->getProgramName().getStr(),
                        (*i)->getLocalName().getStr(),
                        getScopedName().getStr());
                    return false;
                }
                if (getCount > 0) {
                    version = TYPEREG_VERSION_1;
                    if (!increment(&nMethods, "attributes")) {
                        return false;
                    }
                }
                DeclList::size_type setCount = attr->getSetExceptionCount();
                if (setCount > SAL_MAX_UINT16) {
                    fprintf(
                        stderr,
                        ("%s: raises clause of setter for attribute %s of"
                         " interface %s is too long\n"),
                        idlc()->getOptions()->getProgramName().getStr(),
                        (*i)->getLocalName().getStr(),
                        getScopedName().getStr());
                    return false;
                }
                if (setCount > 0) {
                    version = TYPEREG_VERSION_1;
                    if (!increment(&nMethods, "attributes")) {
                        return false;
                    }
                }
                break;
            }

        case NT_operation:
            if (!increment(&nMethods, "methods")) {
                return false;
            }
            break;

        default:
            OSL_ASSERT(false);
            break;
        }
    }}

    OUString emptyStr;
    typereg::Writer aBlob(
        version, getDocumentation(), emptyStr, RT_TYPE_INTERFACE, m_bPublished,
        OStringToOUString(getRelativName(), RTL_TEXTENCODING_UTF8), nBaseTypes,
        nAttributes, nMethods, nReferences);

    sal_uInt16 superTypeIndex = 0;
    sal_uInt16 referenceIndex = 0;
    {for (InheritedInterfaces::iterator i = m_inheritedInterfaces.begin();
          i != m_inheritedInterfaces.end(); ++i)
    {
        if (i->isOptional()) {
            aBlob.setReferenceData(
                referenceIndex++, i->getDocumentation(), RT_REF_SUPPORTS,
                RT_ACCESS_OPTIONAL,
                OStringToOUString(
                    i->getInterface()->getRelativName(),
                    RTL_TEXTENCODING_UTF8));
        } else {
            aBlob.setSuperTypeName(
                superTypeIndex++,
                OStringToOUString(
                    i->getInterface()->getRelativName(),
                    RTL_TEXTENCODING_UTF8));
        }
    }}

    sal_uInt16 attributeIndex = 0;
    sal_uInt16 methodIndex = 0;
    {for (DeclList::const_iterator i(getIteratorBegin()); i != getIteratorEnd();
          ++i)
    {
        switch ((*i)->getNodeType()) {
        case NT_attribute:
//           static_cast< AstAttribute * >(*i)->dumpBlob(

            ((AstAttribute *)(*i))->dumpBlob(
                aBlob, attributeIndex++, &methodIndex);
            break;

        case NT_operation:
//            static_cast< AstOperation * >(*i)->dumpBlob(aBlob, methodIndex++);
            ((AstOperation *)(*i))->dumpBlob(aBlob, methodIndex++);
            break;

        default:
            OSL_ASSERT(false);
            break;
        }
    }}

    sal_uInt32 aBlobSize;
    void const * pBlob = aBlob.getBlob(&aBlobSize);

    if (localKey.setValue(emptyStr, RG_VALUETYPE_BINARY, (RegValue)pBlob, aBlobSize))
    {
        fprintf(stderr, "%s: warning, could not set value of key \"%s\" in %s\n",
                idlc()->getOptions()->getProgramName().getStr(),
                getFullName().getStr(), OUStringToOString(localKey.getRegistryName(), RTL_TEXTENCODING_UTF8).getStr());
        return sal_False;
    }

    return true;
}

void AstInterface::checkInheritedInterfaceClashes(
    DoubleDeclarations & doubleDeclarations,
    std::set< rtl::OString > & seenInterfaces, AstInterface const * ifc,
    bool direct, bool optional, bool mainOptional) const
{
    if (direct || optional
        || seenInterfaces.insert(ifc->getScopedName()).second)
    {
        VisibleInterfaces::const_iterator visible(
            m_visibleInterfaces.find(ifc->getScopedName()));
        if (visible != m_visibleInterfaces.end()) {
            switch (visible->second) {
            case INTERFACE_INDIRECT_OPTIONAL:
                if (direct && optional) {
                    doubleDeclarations.interfaces.push_back(ifc);
                    return;
                }
                break;

            case INTERFACE_DIRECT_OPTIONAL:
                if (direct || !mainOptional) {
                    doubleDeclarations.interfaces.push_back(ifc);
                }
                return;

            case INTERFACE_INDIRECT_MANDATORY:
                if (direct) {
                    doubleDeclarations.interfaces.push_back(ifc);
                }
                return;

            case INTERFACE_DIRECT_MANDATORY:
                if (direct || (!optional && !mainOptional)) {
                    doubleDeclarations.interfaces.push_back(ifc);
                }
                return;
            }
        }
        if (direct || !optional) {
            {for (DeclList::const_iterator i(ifc->getIteratorBegin());
                  i != ifc->getIteratorEnd(); ++i)
            {
                checkMemberClashes(
                    doubleDeclarations.members, *i, !mainOptional);
            }}
            {for (InheritedInterfaces::const_iterator i(
                      ifc->m_inheritedInterfaces.begin());
                  i != ifc->m_inheritedInterfaces.end(); ++i)
            {
                checkInheritedInterfaceClashes(
                    doubleDeclarations, seenInterfaces, i->getResolved(),
                    false, i->isOptional(), mainOptional);
            }}
        }
    }
}

void AstInterface::checkMemberClashes(
    DoubleMemberDeclarations & doubleMembers, AstDeclaration const * member,
    bool checkOptional) const
{
    VisibleMembers::const_iterator i(
        m_visibleMembers.find(member->getLocalName()));
    if (i != m_visibleMembers.end()) {
        if (i->second.mandatory != 0) {
            if (i->second.mandatory->getScopedName() != member->getScopedName())
            {
                DoubleMemberDeclaration d;
                d.first = i->second.mandatory;
                d.second = member;
                doubleMembers.push_back(d);
            }
        } else if (checkOptional) {
            for (VisibleMember::Optionals::const_iterator j(
                     i->second.optionals.begin());
                 j != i->second.optionals.end(); ++j)
            {
                if (j->second->getScopedName() != member->getScopedName()) {
                    DoubleMemberDeclaration d;
                    d.first = j->second;
                    d.second = member;
                    doubleMembers.push_back(d);
                }
            }
        }
    }
}

void AstInterface::addVisibleInterface(
    AstInterface const * ifc, bool direct, bool optional)
{
    InterfaceKind kind = optional
        ? direct ? INTERFACE_DIRECT_OPTIONAL : INTERFACE_INDIRECT_OPTIONAL
        : direct ? INTERFACE_DIRECT_MANDATORY : INTERFACE_INDIRECT_MANDATORY;
    std::pair< VisibleInterfaces::iterator, bool > result(
        m_visibleInterfaces.insert(
            VisibleInterfaces::value_type(ifc->getScopedName(), kind)));
    bool seen = !result.second
        && result.first->second >= INTERFACE_INDIRECT_MANDATORY;
    if (!result.second && kind > result.first->second) {
        result.first->second = kind;
    }
    if (!optional && !seen) {
        {for (DeclList::const_iterator i(ifc->getIteratorBegin());
              i != ifc->getIteratorEnd(); ++i)
        {
            m_visibleMembers.insert(
                VisibleMembers::value_type(
                    (*i)->getLocalName(), VisibleMember(*i)));
        }}
        {for (InheritedInterfaces::const_iterator i(
                  ifc->m_inheritedInterfaces.begin());
              i != ifc->m_inheritedInterfaces.end(); ++i)
        {
            addVisibleInterface(i->getResolved(), false, i->isOptional());
        }}
    }
}

void AstInterface::addOptionalVisibleMembers(AstInterface const * ifc) {
    {for (DeclList::const_iterator i(ifc->getIteratorBegin());
          i != ifc->getIteratorEnd(); ++i)
    {
        VisibleMembers::iterator visible(
            m_visibleMembers.find((*i)->getLocalName()));
        if (visible == m_visibleMembers.end()) {
            visible = m_visibleMembers.insert(
                VisibleMembers::value_type(
                    (*i)->getLocalName(), VisibleMember())).first;
        }
        if (visible->second.mandatory == 0) {
            visible->second.optionals.insert(
                VisibleMember::Optionals::value_type(ifc->getScopedName(), *i));
        }
    }}
    {for (InheritedInterfaces::const_iterator i(
              ifc->m_inheritedInterfaces.begin());
          i != ifc->m_inheritedInterfaces.end(); ++i)
    {
        if (!i->isOptional()) {
            addOptionalVisibleMembers(i->getResolved());
        }
    }}
}

bool AstInterface::increment(sal_uInt16 * counter, char const * sort) const {
    if (*counter == SAL_MAX_UINT16) {
        fprintf(
            stderr, "%s: interface %s has too many direct %s\n",
            idlc()->getOptions()->getProgramName().getStr(),
            getScopedName().getStr(), sort);
        return false;
    }
    ++*counter;
    return true;
}
<|endoftext|>


<commit_before>#include <algorithm>
#include "servicelayer.h"
#include "sortings.h"

ServiceLayer::ServiceLayer()
{
    sortByName(1); //Defaults to sorting the list by name.
}

vector<Persons> ServiceLayer::list()
{
   return dl.getVector();
}

void ServiceLayer::sorting(int type, int order)
{
    switch (type)
    {
    case 1:
    {
        sortByName(order);
        break;
    }
    case 2:
    {
        sortByBirthYear(order);
        break;
    }
    case 3:
    {
        sortByDeathYear(order);
        break;
    }
    case 4:
    {
        sortByGender(order);
        break;
    }

    default:
    {
        break;
    }
    }
}

//regular sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool sortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() < rhs.getName(); }
bool sortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() < rhs.getGender(); }
bool sortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() < rhs.getBirthYear(); }
bool sortByDeathYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getDeathYear() < rhs.getDeathYear(); }

//reverse sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool rSortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() > rhs.getName(); }
bool rSortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() > rhs.getGender(); }
bool rSortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() > rhs.getBirthYear(); }
bool rSortByDeathYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getDeathYear() > rhs.getDeathYear(); }

void ServiceLayer::sortByName(int order)
{
    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByName);
        stable_sort(people.begin(), people.end(), sortByName2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByName);
        stable_sort(people.begin(), people.end(), rSortByName2);
    }
    dl.setVector(people);
}

void ServiceLayer::sortByGender(int order)
{
    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByGender);
        stable_sort(people.begin(), people.end(), sortByGender2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByGender);
        stable_sort(people.begin(), people.end(), rSortByGender2);
    }
    dl.setVector(people);
}

void ServiceLayer::sortByBirthYear(int order)
{

    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByBirthYear);
        stable_sort(people.begin(), people.end(), sortByBirthYear2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByBirthYear);
        stable_sort(people.begin(), people.end(), rSortByBirthYear2);
    }
    dl.setVector(people);
}

void ServiceLayer::sortByDeathYear(int order)
{
    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByDeathYear);
        stable_sort(people.begin(), people.end(), sortByDeathYear2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByDeathYear);
        stable_sort(people.begin(), people.end(), rSortByDeathYear2);
    }
    dl.setVector(people);
}

void ServiceLayer::add(const Persons& p)
{
    dl.addPerson(p);
}

bool ServiceLayer::addFromFile(string input)
{
    return dl.loadFromOtherFile(input);

}

vector<int> ServiceLayer::searchByName(const string name)
{
    vector<int> v;
    for (unsigned int i = 0; i < list().size(); i++)
    {
        if (name.length() <= list()[i].getName().length())
        {
            if (list()[i].getName() == name)
            {
                v.push_back(i);
                break;
            }
            else
            {
                for (unsigned int p = 0; p <=(list()[i].getName().length() - name.length()); p++)
                {
                    if(name == list()[i].getName().substr(p, name.length()))
                    {
                        v.push_back(i);
                        break;
                    }
                }
            }
        }
    }
    return v;
}

vector<int> ServiceLayer::searchByGender(const char gender)
{
    vector<int> v;

    for(unsigned int i = 0; i < list().size(); i++)
    {
        if(list()[i].getGender() == gender)
        {
            v.push_back(i);
        }
    }
    return v;
}

vector<int> ServiceLayer::searchByYear(const int year)
{
    vector<int> v;
    for (unsigned int i = 0; i < list().size(); i++)
    {
        if (list()[i].getBirthYear() == year)
        {
            v.push_back(i);
        }
    }
    return v;
}

vector<int> ServiceLayer::searchByRange(const int f, const int l)
{
    vector<int> v;

    for(unsigned int i = 0; i < list().size(); i++)
    {
        if(list()[i].getBirthYear() >= f && list()[i].getBirthYear() <= l)
        {
            v.push_back(i);
        }
    }
    return v;
}

void ServiceLayer::deletePerson(int n)
{
    dl.deletePerson(n);
}
<commit_msg>lagaði sort by DeathYear<commit_after>#include <algorithm>
#include "servicelayer.h"
#include "sortings.h"

ServiceLayer::ServiceLayer()
{
    sortByName(1); //Defaults to sorting the list by name.
}

vector<Persons> ServiceLayer::list()
{
   return dl.getVector();
}

void ServiceLayer::sorting(int type, int order)
{
    switch (type)
    {
    case 1:
    {
        sortByName(order);
        break;
    }
    case 2:
    {
        sortByBirthYear(order);
        break;
    }
    case 3:
    {
        sortByDeathYear(order);
        break;
    }
    case 4:
    {
        sortByGender(order);
        break;
    }

    default:
    {
        break;
    }
    }
}

//regular sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool sortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() < rhs.getName(); }
bool sortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() < rhs.getGender(); }
bool sortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() < rhs.getBirthYear(); }
bool sortByDeathYear2(const Persons &lhs, const Persons &rhs)
{
    if (lhs.getDeathYear() == 0 && rhs.getDeathYear() == 0)
    {
        return lhs.getDeathYear() < rhs.getDeathYear();
    }
    else if (lhs.getDeathYear() == 0)
    {
        return lhs.getDeathYear() > rhs.getDeathYear();
    }
    else if (rhs.getDeathYear() == 0)
    {
        return lhs.getDeathYear() > rhs.getDeathYear();
    }
    else
    {
        return lhs.getDeathYear() < rhs.getDeathYear();
    }
}

//reverse sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool rSortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() > rhs.getName(); }
bool rSortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() > rhs.getGender(); }
bool rSortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() > rhs.getBirthYear(); }
bool rSortByDeathYear2(const Persons &lhs, const Persons &rhs)
{
    if (lhs.getDeathYear() == 0 && rhs.getDeathYear() == 0)
    {
        return lhs.getDeathYear() > rhs.getDeathYear();
    }
    else if (lhs.getDeathYear() == 0)
    {
        return lhs.getDeathYear() < rhs.getDeathYear();
    }
    else if (rhs.getDeathYear() == 0)
    {
        return lhs.getDeathYear() < rhs.getDeathYear();
    }
    else
    {
        return lhs.getDeathYear() > rhs.getDeathYear();
    }
}

void ServiceLayer::sortByName(int order)
{
    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByName);
        stable_sort(people.begin(), people.end(), sortByName2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByName);
        stable_sort(people.begin(), people.end(), rSortByName2);
    }
    dl.setVector(people);
}

void ServiceLayer::sortByGender(int order)
{
    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByGender);
        stable_sort(people.begin(), people.end(), sortByGender2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByGender);
        stable_sort(people.begin(), people.end(), rSortByGender2);
    }
    dl.setVector(people);
}

void ServiceLayer::sortByBirthYear(int order)
{

    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByBirthYear);
        stable_sort(people.begin(), people.end(), sortByBirthYear2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByBirthYear);
        stable_sort(people.begin(), people.end(), rSortByBirthYear2);
    }
    dl.setVector(people);
}

void ServiceLayer::sortByDeathYear(int order)
{
    vector <Persons> people = dl.getVector();
    if (order == 1)
    {
        //stable_sort(people.begin(), people.end(), sorter.sortByDeathYear);
        stable_sort(people.begin(), people.end(), sortByDeathYear2);
    }
    else //order == 2
    {
        //stable_sort(people.begin(), people.end(), sorter.rSortByDeathYear);
        stable_sort(people.begin(), people.end(), rSortByDeathYear2);
    }
    dl.setVector(people);
}

void ServiceLayer::add(const Persons& p)
{
    dl.addPerson(p);
}

bool ServiceLayer::addFromFile(string input)
{
    return dl.loadFromOtherFile(input);

}

vector<int> ServiceLayer::searchByName(const string name)
{
    vector<int> v;
    for (unsigned int i = 0; i < list().size(); i++)
    {
        if (name.length() <= list()[i].getName().length())
        {
            if (list()[i].getName() == name)
            {
                v.push_back(i);
                break;
            }
            else
            {
                for (unsigned int p = 0; p <=(list()[i].getName().length() - name.length()); p++)
                {
                    if(name == list()[i].getName().substr(p, name.length()))
                    {
                        v.push_back(i);
                        break;
                    }
                }
            }
        }
    }
    return v;
}

vector<int> ServiceLayer::searchByGender(const char gender)
{
    vector<int> v;

    for(unsigned int i = 0; i < list().size(); i++)
    {
        if(list()[i].getGender() == gender)
        {
            v.push_back(i);
        }
    }
    return v;
}

vector<int> ServiceLayer::searchByYear(const int year)
{
    vector<int> v;
    for (unsigned int i = 0; i < list().size(); i++)
    {
        if (list()[i].getBirthYear() == year)
        {
            v.push_back(i);
        }
    }
    return v;
}

vector<int> ServiceLayer::searchByRange(const int f, const int l)
{
    vector<int> v;

    for(unsigned int i = 0; i < list().size(); i++)
    {
        if(list()[i].getBirthYear() >= f && list()[i].getBirthYear() <= l)
        {
            v.push_back(i);
        }
    }
    return v;
}

void ServiceLayer::deletePerson(int n)
{
    dl.deletePerson(n);
}
<|endoftext|>


<commit_before>#include "Player.hpp"
#include "Patron.hpp"

#include "../Application.hpp"
#include "../Inputs.hpp"

#include <SFML/Graphics/RectangleShape.hpp>

using namespace Game;

void Player::update(float dt)
{
	auto& inp = Application::getApplication()->getInputManager();

	auto pos = getPosition();
	auto& size = getRoom().getSize();

	if (inp[Input_Left].pressed() && pos.x > 0)
		--pos.x;
	if (inp[Input_Right].pressed() && pos.x + 1 < size.x)
		++pos.x;
	if (inp[Input_Up].pressed() && pos.y > 0)
		--pos.y;
	if (inp[Input_Down].pressed() && pos.y + 1 < size.y)
		++pos.y;

	auto tile = getRoom().getTile({ uint32_t(pos.x), uint32_t(pos.y) });
	if (tile == Room::Tile_Floor)
		setPosition(pos);
	else if (!mCarried)
	{
		if (tile == Room::Tile_Bottles)
			mCarried = std::make_unique<Drink>(Drink_Cocktail);
		else if (tile == Room::Tile_Taps)
			mCarried = std::make_unique<Drink>(Drink_Beer);
		else if (tile == Room::Tile_Sink)
			mCarried = std::make_unique<Drink>(Drink_Water);
	}
	else
	{
		if (tile == Room::Tile_Sink)
			mCarried.reset(nullptr);
		else if (tile == Room::Tile_Seat || tile == Room::Tile_Stool)
		{
			auto* target = dynamic_cast<Patron*>(getRoom().getObject(sf::Vector2u(pos)));

			if (target && target->getOrder().getType() == mCarried->getType())
				mCarried.reset(nullptr);
		}
		else if (tile == Room::Tile_Bar || tile == Room::Tile_Table)
		{
			// TODO: Delta * 2
		}
	}
}
void Player::draw(sf::RenderTarget& rt, sf::RenderStates states) const
{
	states.transform *= getTransform();

	auto rect = sf::RectangleShape({ 1, 1 });
	rect.setFillColor(sf::Color::Blue);

	rt.draw(rect, states);

	if (mCarried)
	{
		auto& drink = *mCarried;

		rt.draw(drink, states);
	}
}

<commit_msg>Handing over the bar<commit_after>#include "Player.hpp"
#include "Patron.hpp"

#include "../Application.hpp"
#include "../Inputs.hpp"

#include <SFML/Graphics/RectangleShape.hpp>

using namespace Game;

void Player::update(float dt)
{
	auto& inp = Application::getApplication()->getInputManager();

	auto& size = getRoom().getSize();
	sf::Vector2u pos = sf::Vector2u(getPosition());
	sf::Vector2u delta;

	if (inp[Input_Left].pressed() && pos.x > 0)
		--delta.x;
	if (inp[Input_Right].pressed() && pos.x + 1 < size.x)
		++delta.x;
	if (inp[Input_Up].pressed() && pos.y > 0)
		--delta.y;
	if (inp[Input_Down].pressed() && pos.y + 1 < size.y)
		++delta.y;

	auto newPos = pos + delta;
	auto tile = getRoom().getTile({ newPos.x, newPos.y });
	if (tile == Room::Tile_Floor)
		setPosition(sf::Vector2f(newPos));
	else if (!mCarried)
	{
		if (tile == Room::Tile_Bottles)
			mCarried = std::make_unique<Drink>(Drink_Cocktail);
		else if (tile == Room::Tile_Taps)
			mCarried = std::make_unique<Drink>(Drink_Beer);
		else if (tile == Room::Tile_Sink)
			mCarried = std::make_unique<Drink>(Drink_Water);
	}
	else
	{
		if (tile == Room::Tile_Sink)
			mCarried.reset(nullptr);
		else if (tile == Room::Tile_Seat || tile == Room::Tile_Stool)
		{
			auto* target = dynamic_cast<Patron*>(getRoom().getObject(newPos));

			if (target && target->getOrder().getType() == mCarried->getType())
				mCarried.reset(nullptr);
		}
		else if (tile == Room::Tile_Bar || tile == Room::Tile_Table)
		{
			auto* target = dynamic_cast<Patron*>(getRoom().getObject(pos + delta * 2u));

			if (target && target->getOrder().getType() == mCarried->getType())
				mCarried.reset(nullptr);
		}
	}
}
void Player::draw(sf::RenderTarget& rt, sf::RenderStates states) const
{
	states.transform *= getTransform();

	auto rect = sf::RectangleShape({ 1, 1 });
	rect.setFillColor(sf::Color::Blue);

	rt.draw(rect, states);

	if (mCarried)
	{
		auto& drink = *mCarried;

		rt.draw(drink, states);
	}
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved
 *
 * This source code is subject to the terms of the BSD 2 Clause License and
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
 * was not distributed with this source code in the LICENSE file, you can
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
 * Media Patent License 1.0 was not distributed with this source code in the
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
 */

#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <ctime>
#include <utility>
#include <vector>

#include "third_party/googletest/src/include/gtest/gtest.h"

#include "test/acm_random.h"
#include "aom_dsp/ansreader.h"
#include "aom_dsp/answriter.h"

namespace {
typedef std::vector<std::pair<uint8_t, bool> > PvVec;

const int kPrintStats = 0;

PvVec abs_encode_build_vals(int iters) {
  PvVec ret;
  libaom_test::ACMRandom gen(0x30317076);
  double entropy = 0;
  for (int i = 0; i < iters; ++i) {
    uint8_t p;
    do {
      p = gen.Rand8();
    } while (p == 0);  // zero is not a valid coding probability
    bool b = gen.Rand8() < p;
    ret.push_back(std::make_pair(static_cast<uint8_t>(p), b));
    if (kPrintStats) {
      double d = p / 256.;
      entropy += -d * log2(d) - (1 - d) * log2(1 - d);
    }
  }
  if (kPrintStats) printf("entropy %f\n", entropy);
  return ret;
}

bool check_uabs(const PvVec &pv_vec, uint8_t *buf) {
  AnsCoder a;
  ans_write_init(&a, buf);

  std::clock_t start = std::clock();
  for (PvVec::const_reverse_iterator it = pv_vec.rbegin(); it != pv_vec.rend();
       ++it) {
    uabs_write(&a, it->second, 256 - it->first);
  }
  std::clock_t enc_time = std::clock() - start;
  int offset = ans_write_end(&a);
  bool okay = true;
  AnsDecoder d;
  if (ans_read_init(&d, buf, offset)) return false;
  start = std::clock();
  for (PvVec::const_iterator it = pv_vec.begin(); it != pv_vec.end(); ++it) {
    okay &= uabs_read(&d, 256 - it->first) == it->second;
  }
  std::clock_t dec_time = std::clock() - start;
  if (!okay) return false;
  if (kPrintStats)
    printf("uABS size %d enc_time %f dec_time %f\n", offset,
           static_cast<float>(enc_time) / CLOCKS_PER_SEC,
           static_cast<float>(dec_time) / CLOCKS_PER_SEC);
  return ans_read_end(&d);
}

// TODO(aconverse@google.com): replace this with a more representative
// distribution from the codec.
const rans_sym rans_sym_tab[] = {
  { 67, 0 }, { 99, 67 }, { 575, 166 }, { 283, 741 },
};
const int kRansSymbols =
    static_cast<int>(sizeof(rans_sym_tab) / sizeof(rans_sym));

std::vector<int> ans_encode_build_vals(const rans_sym *tab, int iters) {
  std::vector<int> p_to_sym;
  for (int i = 0; i < kRansSymbols; ++i) {
    p_to_sym.insert(p_to_sym.end(), tab[i].prob, i);
  }
  assert(p_to_sym.size() == RANS_PRECISION);
  std::vector<int> ret;
  libaom_test::ACMRandom gen(18543637);
  for (int i = 0; i < iters; ++i) {
    int sym = p_to_sym[gen.Rand8() * 4];
    ret.push_back(sym);
  }
  return ret;
}

void rans_build_dec_tab(const struct rans_sym sym_tab[],
                        aom_cdf_prob *dec_tab) {
  unsigned int sum = 0;
  for (int i = 0; sum < RANS_PRECISION; ++i) {
    dec_tab[i] = sum += sym_tab[i].prob;
  }
}

bool check_rans(const std::vector<int> &sym_vec, const rans_sym *const tab,
                uint8_t *buf) {
  AnsCoder a;
  ans_write_init(&a, buf);
  aom_cdf_prob dec_tab[kRansSymbols];
  rans_build_dec_tab(tab, dec_tab);

  std::clock_t start = std::clock();
  for (std::vector<int>::const_reverse_iterator it = sym_vec.rbegin();
       it != sym_vec.rend(); ++it) {
    rans_write(&a, &tab[*it]);
  }
  std::clock_t enc_time = std::clock() - start;
  int offset = ans_write_end(&a);
  bool okay = true;
  AnsDecoder d;
  if (ans_read_init(&d, buf, offset)) return false;
  start = std::clock();
  for (std::vector<int>::const_iterator it = sym_vec.begin();
       it != sym_vec.end(); ++it) {
    okay &= rans_read(&d, dec_tab) == *it;
  }
  std::clock_t dec_time = std::clock() - start;
  if (!okay) return false;
  if (kPrintStats)
    printf("rANS size %d enc_time %f dec_time %f\n", offset,
           static_cast<float>(enc_time) / CLOCKS_PER_SEC,
           static_cast<float>(dec_time) / CLOCKS_PER_SEC);
  return ans_read_end(&d);
}

class AbsTest : public ::testing::Test {
 protected:
  static void SetUpTestCase() { pv_vec_ = abs_encode_build_vals(kNumBools); }
  virtual void SetUp() { buf_ = new uint8_t[kNumBools / 8]; }
  virtual void TearDown() { delete[] buf_; }
  static const int kNumBools = 100000000;
  static PvVec pv_vec_;
  uint8_t *buf_;
};
PvVec AbsTest::pv_vec_;

class AnsTest : public ::testing::Test {
 protected:
  static void SetUpTestCase() {
    sym_vec_ = ans_encode_build_vals(rans_sym_tab, kNumSyms);
  }
  virtual void SetUp() { buf_ = new uint8_t[kNumSyms / 2]; }
  virtual void TearDown() { delete[] buf_; }
  static const int kNumSyms = 25000000;
  static std::vector<int> sym_vec_;
  uint8_t *buf_;
};
std::vector<int> AnsTest::sym_vec_;

TEST_F(AbsTest, Uabs) { EXPECT_TRUE(check_uabs(pv_vec_, buf_)); }
TEST_F(AnsTest, Rans) { EXPECT_TRUE(check_rans(sym_vec_, rans_sym_tab, buf_)); }
}  // namespace
<commit_msg>AnsTest: Replace the dummy distribution<commit_after>/*
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved
 *
 * This source code is subject to the terms of the BSD 2 Clause License and
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
 * was not distributed with this source code in the LICENSE file, you can
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
 * Media Patent License 1.0 was not distributed with this source code in the
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
 */

#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <ctime>
#include <utility>
#include <vector>

#include "third_party/googletest/src/include/gtest/gtest.h"

#include "test/acm_random.h"
#include "aom_dsp/ansreader.h"
#include "aom_dsp/answriter.h"

namespace {
typedef std::vector<std::pair<uint8_t, bool> > PvVec;

const int kPrintStats = 0;

PvVec abs_encode_build_vals(int iters) {
  PvVec ret;
  libaom_test::ACMRandom gen(0x30317076);
  double entropy = 0;
  for (int i = 0; i < iters; ++i) {
    uint8_t p;
    do {
      p = gen.Rand8();
    } while (p == 0);  // zero is not a valid coding probability
    bool b = gen.Rand8() < p;
    ret.push_back(std::make_pair(static_cast<uint8_t>(p), b));
    if (kPrintStats) {
      double d = p / 256.;
      entropy += -d * log2(d) - (1 - d) * log2(1 - d);
    }
  }
  if (kPrintStats) printf("entropy %f\n", entropy);
  return ret;
}

bool check_uabs(const PvVec &pv_vec, uint8_t *buf) {
  AnsCoder a;
  ans_write_init(&a, buf);

  std::clock_t start = std::clock();
  for (PvVec::const_reverse_iterator it = pv_vec.rbegin(); it != pv_vec.rend();
       ++it) {
    uabs_write(&a, it->second, 256 - it->first);
  }
  std::clock_t enc_time = std::clock() - start;
  int offset = ans_write_end(&a);
  bool okay = true;
  AnsDecoder d;
  if (ans_read_init(&d, buf, offset)) return false;
  start = std::clock();
  for (PvVec::const_iterator it = pv_vec.begin(); it != pv_vec.end(); ++it) {
    okay &= uabs_read(&d, 256 - it->first) == it->second;
  }
  std::clock_t dec_time = std::clock() - start;
  if (!okay) return false;
  if (kPrintStats)
    printf("uABS size %d enc_time %f dec_time %f\n", offset,
           static_cast<float>(enc_time) / CLOCKS_PER_SEC,
           static_cast<float>(dec_time) / CLOCKS_PER_SEC);
  return ans_read_end(&d);
}

const aom_cdf_prob spareto65[] = { 260, 188, 138, 102, 133, 122, 64, 15, 1, 1 };

const int kRansSymbols =
    static_cast<int>(sizeof(spareto65) / sizeof(spareto65[0]));

std::vector<int> ans_encode_build_vals(rans_sym *const tab, int iters) {
  aom_cdf_prob sum = 0;
  for (int i = 0; i < kRansSymbols; ++i) {
    tab[i].cum_prob = sum;
    tab[i].prob = spareto65[i];
    sum += spareto65[i];
  }
  std::vector<int> p_to_sym;
  for (int i = 0; i < kRansSymbols; ++i) {
    p_to_sym.insert(p_to_sym.end(), tab[i].prob, i);
  }
  assert(p_to_sym.size() == RANS_PRECISION);
  std::vector<int> ret;
  libaom_test::ACMRandom gen(18543637);
  for (int i = 0; i < iters; ++i) {
    int sym = p_to_sym[gen.Rand8() * 4];
    ret.push_back(sym);
  }
  return ret;
}

void rans_build_dec_tab(const struct rans_sym sym_tab[],
                        aom_cdf_prob *dec_tab) {
  unsigned int sum = 0;
  for (int i = 0; sum < RANS_PRECISION; ++i) {
    dec_tab[i] = sum += sym_tab[i].prob;
  }
}

bool check_rans(const std::vector<int> &sym_vec, const rans_sym *const tab,
                uint8_t *buf) {
  AnsCoder a;
  ans_write_init(&a, buf);
  aom_cdf_prob dec_tab[kRansSymbols];
  rans_build_dec_tab(tab, dec_tab);

  std::clock_t start = std::clock();
  for (std::vector<int>::const_reverse_iterator it = sym_vec.rbegin();
       it != sym_vec.rend(); ++it) {
    rans_write(&a, &tab[*it]);
  }
  std::clock_t enc_time = std::clock() - start;
  int offset = ans_write_end(&a);
  bool okay = true;
  AnsDecoder d;
  if (ans_read_init(&d, buf, offset)) return false;
  start = std::clock();
  for (std::vector<int>::const_iterator it = sym_vec.begin();
       it != sym_vec.end(); ++it) {
    okay &= rans_read(&d, dec_tab) == *it;
  }
  std::clock_t dec_time = std::clock() - start;
  if (!okay) return false;
  if (kPrintStats)
    printf("rANS size %d enc_time %f dec_time %f\n", offset,
           static_cast<float>(enc_time) / CLOCKS_PER_SEC,
           static_cast<float>(dec_time) / CLOCKS_PER_SEC);
  return ans_read_end(&d);
}

class AbsTest : public ::testing::Test {
 protected:
  static void SetUpTestCase() { pv_vec_ = abs_encode_build_vals(kNumBools); }
  virtual void SetUp() { buf_ = new uint8_t[kNumBools / 8]; }
  virtual void TearDown() { delete[] buf_; }
  static const int kNumBools = 100000000;
  static PvVec pv_vec_;
  uint8_t *buf_;
};
PvVec AbsTest::pv_vec_;

class AnsTest : public ::testing::Test {
 protected:
  static void SetUpTestCase() {
    sym_vec_ = ans_encode_build_vals(rans_sym_tab_, kNumSyms);
  }
  virtual void SetUp() { buf_ = new uint8_t[kNumSyms / 2]; }
  virtual void TearDown() { delete[] buf_; }
  static const int kNumSyms = 25000000;
  static std::vector<int> sym_vec_;
  static rans_sym rans_sym_tab_[kRansSymbols];
  uint8_t *buf_;
};
std::vector<int> AnsTest::sym_vec_;
rans_sym AnsTest::rans_sym_tab_[kRansSymbols];

TEST_F(AbsTest, Uabs) { EXPECT_TRUE(check_uabs(pv_vec_, buf_)); }
TEST_F(AnsTest, Rans) {
  EXPECT_TRUE(check_rans(sym_vec_, rans_sym_tab_, buf_));
}
}  // namespace
<|endoftext|>


<commit_before>/*
 * console.hpp
 *
 *  Created on: Oct 04, 2013
 *      Author: philip
 */
/*
#include "irrlight/dev/console.hpp"
*/

#ifndef _IRRLIGHT_DEV_CONSOLE_HPP_
#define _IRRLIGHT_DEV_CONSOLE_HPP_

#include <string>
#include <vector>
#include "irrlicht.h"

#include "kul/hash.hpp"
#include "kul/string.hpp"

namespace irrlight{namespace dev{

enum ConsoleUI{
	COMMAND_BOX,
	COMMAND__HISTORY_BOX,
};

class AConsoleCmd{
	public:
		virtual ~AConsoleCmd(){}
		virtual void 			perform() 	{};
		virtual void 			perform(const std::vector<std::wstring>& args){};
		virtual std::wstring 	getOutput() { return L"";};
};

class ConsoleCmdHistory{
	private:
		static int MINUS_ONE;
		int it;
		std::vector<std::wstring> history;
	public:
		ConsoleCmdHistory() : it(-1){}
		~ConsoleCmdHistory(){}

		const wchar_t*	getPrevious ()  ;
		const wchar_t*	getNext 	()  ;
		ConsoleCmdHistory* addNew(std::wstring currentCommand) ; // andDeleteOldestIfApplicable
		ConsoleCmdHistory* reset() { it = history.size(); return this;}
};

class Console{
	private:
		bool shown;
		std::vector<std::string> output;
		ConsoleCmdHistory commandHistory;
		kul::hash::map::S2T<AConsoleCmd> cmds;
	protected:
		void rollDown	(irr::IrrlichtDevice * device);
		void rollUp		(irr::IrrlichtDevice * device);
	public:
		Console() : shown(false){}
		void draw(irr::IrrlichtDevice * device);
		void show(irr::IrrlichtDevice * device) { shown = true; 	history().reset(); rollDown(device); }
		void hide(irr::IrrlichtDevice * device) { shown = false;	rollUp(device);}
		const wchar_t * getText(irr::IrrlichtDevice *device) const;
		void setText(irr::IrrlichtDevice *device, const wchar_t* text);

		bool isShown() const { return shown; }
		const void addCommand(const std::string& s, const AConsoleCmd& cmd){ cmds.insert(s, cmd); }
		kul::hash::map::S2T<AConsoleCmd>& commands() { return cmds;}
		ConsoleCmdHistory& history() { return commandHistory; }
};

class AConsoleKeyHandler{
	protected:
		irr::IrrlichtDevice& 	device;
	public:
		AConsoleKeyHandler(irr::IrrlichtDevice& device) : device(device) {}
		virtual ~AConsoleKeyHandler(){}
		virtual bool handle() = 0;
};

class ConsoleStringHandler{
	public:
		static std::wstring getWStringFromWChar_TP(const wchar_t* cText, char upperLower = ' ', bool trim = false, bool replaceDoubleSpace = false){
			irr::core::stringw text(cText);
			if		(upperLower == 'U' || upperLower == 'u')
				text.make_upper();
			else if	(upperLower == 'L' || upperLower == 'l')
				text.make_lower();
			std::wstring textString(text.c_str());
			std::string tS = kul::WString::toString(textString);
			kul::String::trim(tS);
			if(trim)
				kul::WString::trim(textString);
			if(replaceDoubleSpace){
				const wchar_t* ds{L"  "};
				const wchar_t* ss{L" "};
				kul::WString::replaceAll(textString, std::wstring(ds), std::wstring(ss));
			}
			return textString;
		}
};

class ConsoleEnterKeyHandler : public AConsoleKeyHandler{
	private:
		Console& console;
	public:
		ConsoleEnterKeyHandler(Console& console, irr::IrrlichtDevice* device) : AConsoleKeyHandler(*device), console(console) {}
		~ConsoleEnterKeyHandler(){}
		bool handle(){
			std::wstring textString(ConsoleStringHandler::getWStringFromWChar_TP(console.getText(&device), 'L', true, true));
			if(textString.size() == 0) return false;

			console.setText(&device, L"");
			std::vector<std::wstring> bits = kul::WString::split(textString, ' ');
			//boost::split(bits, textString, boost::is_any_of(" ") );
			const std::string call = kul::WString::toString(bits[0]);

			if(console.commands().count(call)){
				AConsoleCmd& cmd = console.commands()[call];
				if(bits.size() > 1){
					bits.erase(bits.begin(), bits.begin() + 1);
					cmd.perform(bits);
				}else cmd.perform();
			}
			console.history().addNew(textString);
			return true;
		}
};

class ConsoleKeyEntryHandler{
	public:
		static bool keyUp(irr::IrrlichtDevice *device, Console& console, irr::EKEY_CODE keyCode){
			bool k = false;
			if(keyCode == irr::KEY_RETURN)
				k = ConsoleEnterKeyHandler(console, device).handle();
			else
			if(keyCode == irr::KEY_UP)		{
				const wchar_t* txt = console.history().getPrevious();
				if(txt) console.setText(device, txt);
				k = true;
			}
			else
			if(keyCode == irr::KEY_DOWN)	{
				const wchar_t* txt = console.history().getNext();
				if(!txt) txt = L"";
				console.setText(device, txt);
				k = true;
			}
			return k;
		}
		static bool keyDown	(irr::IrrlichtDevice *device, Console& console, irr::EKEY_CODE keyCode){
			return false;
		}
};

};};
#endif /* _IRRLIGHT_DEV_CONSOLE_HPP_ */
<commit_msg>console command handling<commit_after>/*
 * console.hpp
 *
 *  Created on: Oct 04, 2013
 *      Author: philip
 */
/*
#include "irrlight/dev/console.hpp"
*/

#ifndef _IRRLIGHT_DEV_CONSOLE_HPP_
#define _IRRLIGHT_DEV_CONSOLE_HPP_

#include <string>
#include <vector>
#include "irrlicht.h"

#include "kul/hash.hpp"
#include "kul/string.hpp"

namespace irrlight{namespace dev{

enum ConsoleUI{
	COMMAND_BOX,
	COMMAND__HISTORY_BOX,
};

class AConsoleCmd{
	public:
		virtual ~AConsoleCmd(){}
		virtual void 			perform() 	{};
		virtual void 			perform(const std::vector<std::wstring>& args){};
		virtual std::wstring 	getOutput() { return L"";};
};

class ConsoleCmdHistory{
	private:
		static int MINUS_ONE;
		int it;
		std::vector<std::wstring> history;
	public:
		ConsoleCmdHistory() : it(-1){}
		~ConsoleCmdHistory(){}

		const wchar_t*	getPrevious ()  ;
		const wchar_t*	getNext 	()  ;
		ConsoleCmdHistory* addNew(std::wstring currentCommand) ; // andDeleteOldestIfApplicable
		ConsoleCmdHistory* reset() { it = history.size(); return this;}
};

class Console{
	private:
		bool shown;
		std::vector<std::string> output;
		ConsoleCmdHistory commandHistory;
		kul::hash::map::S2T<AConsoleCmd> cmds;
	protected:
		void rollDown	(irr::IrrlichtDevice * device);
		void rollUp		(irr::IrrlichtDevice * device);
	public:
		Console() : shown(false){}
		void draw(irr::IrrlichtDevice * device);
		void show(irr::IrrlichtDevice * device) { shown = true; 	history().reset(); rollDown(device); }
		void hide(irr::IrrlichtDevice * device) { shown = false;	rollUp(device);}
		const wchar_t * getText(irr::IrrlichtDevice *device) const;
		void setText(irr::IrrlichtDevice *device, const wchar_t* text);

		bool isShown() const { return shown; }
		const void addCommand(const std::string& s, const AConsoleCmd& cmd){ cmds.insert(s, cmd); }
		kul::hash::map::S2T<AConsoleCmd>& commands() { return cmds;}
		ConsoleCmdHistory& history() { return commandHistory; }
};

class ConsoleStringHandler{
	public:
		static std::wstring getWStringFromWChar_TP(const wchar_t* cText, char upperLower = ' ', bool trim = false, bool replaceDoubleSpace = false){
			irr::core::stringw text(cText);
			if		(upperLower == 'U' || upperLower == 'u')
				text.make_upper();
			else if	(upperLower == 'L' || upperLower == 'l')
				text.make_lower();
			std::wstring textString(text.c_str());
			std::string tS = kul::WString::toString(textString);
			kul::String::trim(tS);
			if(trim)
				kul::WString::trim(textString);
			if(replaceDoubleSpace){
				const wchar_t* ds{L"  "};
				const wchar_t* ss{L" "};
				kul::WString::replaceAll(textString, std::wstring(ds), std::wstring(ss));
			}
			return textString;
		}
};

class ConsoleEnterKeyHandler{
	public:
		static std::string handle(Console& console, irr::IrrlichtDevice* device){
			std::wstring textString(ConsoleStringHandler::getWStringFromWChar_TP(console.getText(device), 'L', true, true));
			if(textString.size() == 0) return "";
			console.setText(device, L"");
			console.history().addNew(textString);
			return kul::WString::toString(textString);
		}
};

class ConsoleKeyEntryHandler{
	public:
		static bool keyUp(irr::IrrlichtDevice *device, Console& console, irr::EKEY_CODE keyCode){
			bool k = false;
			//if(keyCode == irr::KEY_RETURN) k = ConsoleEnterKeyHandler(console, device).handle();
			if(keyCode == irr::KEY_UP){
				const wchar_t* txt = console.history().getPrevious();
				if(txt) console.setText(device, txt);
				k = true;
			}else if(keyCode == irr::KEY_DOWN){
				const wchar_t* txt = console.history().getNext();
				if(!txt) txt = L"";
				console.setText(device, txt);
				k = true;
			}
			return k;
		}
		static bool keyDown	(irr::IrrlichtDevice *device, Console& console, irr::EKEY_CODE keyCode){
			return false;
		}
};

};};
#endif /* _IRRLIGHT_DEV_CONSOLE_HPP_ */
<|endoftext|>


<commit_before>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include "common.hpp"

using namespace std;

void hexdump(const void *data, int dataLen) {
	const char *const start = static_cast<const char *>(data);

	int it = 0;

	stringstream all;

	cout << "Hexdump of: " << data << endl;
	while (dataLen > 0) {
		unsigned int lineLength = min((int)16, dataLen);
		const char *line = start + it;

		stringstream ascii;
		stringstream hexDump;

		ascii << setfill('0') << setw(2) << hex << it << " : ";

		for (unsigned int i = 0; i < lineLength; i++) {
			char c = static_cast<char>(line[i]);
			unsigned int varInt = 0;
			varInt |= static_cast<uint8_t>(c);

			if (isprint(varInt) != 0) {
				ascii << static_cast<char>(line[i]);
			} else {
				ascii << '.';
			}

			hexDump << " " << setfill('0') << setw(2) << hex << uppercase << varInt;
		}

		for (int i = lineLength; i < 16; i++) {
			ascii << " ";
		}

		all << ascii.str();
		all << hexDump.str();
		all << endl;

		dataLen -= 16;
		it += lineLength;
	}

	cout << all.str();
}

void hexdumpHexOnly(const void *data, int dataLen) {
	const char *const start = static_cast<const char *>(data);

	int it = 0;

	stringstream all;

	cout << "Hexdump of: " << data << endl;
	while (dataLen > 0) {
		unsigned int lineLength = min((int)16, dataLen);
		const char *line = start + it;

		for (unsigned int i = 0; i < lineLength; i++) {
			char c = static_cast<char>(line[i]);
			unsigned int varInt = 0;
			varInt |= static_cast<uint8_t>(c);

			all << " " << setfill('0') << setw(2) << hex << uppercase << varInt;
		}

		all << endl;

		dataLen -= 16;
		it += lineLength;
	}

	cout << all.str();
}
<commit_msg>hexdump design<commit_after>#include <cassert>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include "common.hpp"

using namespace std;

void hexdump(const void *data, int dataLen) {
	const char *const start = static_cast<const char *>(data);

	int it = 0;

	stringstream all;

	cout << "Hexdump of: " << data << endl;
	while (dataLen > 0) {
		unsigned int lineLength = min((int)16, dataLen);
		const char *line = start + it;

		stringstream ascii;
		stringstream hexDump;

		ascii << "0x" << setfill('0') << setw(4) << hex << it << " : ";

		for (unsigned int i = 0; i < lineLength; i++) {
			char c = static_cast<char>(line[i]);
			unsigned int varInt = 0;
			varInt |= static_cast<uint8_t>(c);

			if (isprint(varInt) != 0) {
				ascii << static_cast<char>(line[i]);
			} else {
				ascii << '.';
			}

			hexDump << " " << setfill('0') << setw(2) << hex << uppercase << varInt;
		}

		for (int i = lineLength; i < 16; i++) {
			ascii << " ";
		}

		all << ascii.str();
		all << hexDump.str();
		all << endl;

		dataLen -= 16;
		it += lineLength;
	}

	cout << all.str();
}

void hexdumpHexOnly(const void *data, int dataLen) {
	const char *const start = static_cast<const char *>(data);

	int it = 0;

	stringstream all;

	cout << "Hexdump of: " << data << endl;
	while (dataLen > 0) {
		unsigned int lineLength = min((int)16, dataLen);
		const char *line = start + it;

		for (unsigned int i = 0; i < lineLength; i++) {
			char c = static_cast<char>(line[i]);
			unsigned int varInt = 0;
			varInt |= static_cast<uint8_t>(c);

			all << " " << setfill('0') << setw(2) << hex << uppercase << varInt;
		}

		all << endl;

		dataLen -= 16;
		it += lineLength;
	}

	cout << all.str();
}
<|endoftext|>


<commit_before>/*
 * vnicppcodegen.cpp
 *
 *  Created on: Jul 8, 2016
 *      Author: mad
 */

#include "VNIParser.h"
#include "Compiler.h"

#include "cpp/Generator.h"

using namespace vni::codegen;

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

	if(argc < 2) {
		cout << "Usage: vnicppcodegen interface-dir ..." << endl;
	}

	Compiler<VNIParser> compiler;
	compiler.root_dirs.push_back(argv[1]);

	compiler.compile();

	cpp::Generator gen;
	gen.generate_all();

}
<commit_msg>small fix<commit_after>/*
 * vnicppcodegen.cpp
 *
 *  Created on: Jul 8, 2016
 *      Author: mad
 */

#include "VNIParser.h"
#include "Compiler.h"

#include "cpp/Generator.h"

using namespace vni::codegen;

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

	if(argc < 2) {
		cout << "Usage: vnicppcodegen interface-dir ..." << endl;
	}

	Compiler<VNIParser> compiler;
	for(int i = 1; i < argc; ++i) {
		compiler.root_dirs.push_back(argv[i]);
	}

	compiler.compile();

	cpp::Generator gen;
	gen.generate_all();

}
<|endoftext|>


<commit_before>#pragma once

#include <cstdint>
#include <vector>
#include <initializer_list>
#include <ostream>
#include <istream>

// Bitstream_Generic[0] is the least significant bit (LSB)
// Bitsream[Bitstream_Generic.size()-1] is the most significant bit (MSB)
template <typename BlockType>
class Bitstream_Generic
{
public:
    friend class BitView;
    static const auto block_size = sizeof(BlockType) * 8;

    typedef std::vector<BlockType> ContainerType;

    class BitView
    {

        friend class Bitstream_Generic<BlockType>;
        BitView(ContainerType& bstream, unsigned int block_idx, uint8_t bit_idx)
            : bits(bstream),
            block_index(block_idx),
            bit_index(bit_idx)
        {}

        ContainerType& bits;
        const unsigned int block_index;
        const uint8_t bit_index;

    public:
        operator bool() const
        {
            return (bits[block_index] & ((BlockType) 1 << bit_index)) != 0;
        }

        void operator=(bool val)
        {
            auto& block = bits[block_index];
            if (val) {
                // set bit at bit_idx
                auto mask = (BlockType) 1 << bit_index;
                block |= mask;
            }
            else {
                // unset bit at bit_idx
                auto mask = ~((BlockType) 1 << bit_index);
                block &= mask;
            }
        }
    };

private:
    ContainerType bits;
    uint8_t bit_idx;
    size_t sz;

private:
    // appending Blocks, don't let the user see this as it needs proper alignment,
    // only used for reading in a file
    Bitstream_Generic& operator<<(BlockType val);

public:
    // ctors
    Bitstream_Generic();
    Bitstream_Generic(std::initializer_list<bool> args);

    // appending bits
    Bitstream_Generic& operator<<(bool val);
    Bitstream_Generic& operator<<(std::initializer_list<bool> args);
    Bitstream_Generic& push_back(bool val);

    // streaming
    template<typename BlockType>
    friend std::ostream& operator<<(std::ostream& out, const Bitstream_Generic<BlockType>& bitstream);
    template<typename BlockType>
    friend std::istream& operator>>(std::istream& in, Bitstream_Generic<BlockType>& bitstream);

    // accessing
    BitView operator[](unsigned int pos);

    // others
    size_t size() const;
    void fill(); // fill remaining bits in the last block with 1s
};

//
// Implementation
//
template<typename BlockType>
Bitstream_Generic<BlockType>::Bitstream_Generic()
: bit_idx(block_size),
bits(),
sz(0)
{}

template<typename BlockType>
Bitstream_Generic<BlockType>::Bitstream_Generic(std::initializer_list<bool> args)
: Bitstream_Generic()
{
    *this << args;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::operator<<(bool val)
{
    // make bit stream longer if we run out of space
    if (bit_idx >= block_size) {
        bits.push_back(0);
        bit_idx = block_size - 1;
    }

    auto& block = bits.back();
    if (val) {
        // set bit at bit_idx
        auto mask = (BlockType) 1 << bit_idx;
        block |= mask;
    }
    --bit_idx;
    ++sz;

    return *this;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::operator<<(BlockType val)
{
    bits.push_back(val);
    sz += block_size;
    return *this;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::operator<<(std::initializer_list<bool> args)
{
    // todo: perf improve: use operator<<(bool) as long as the block is not aligned
    //          then use operator<<(BlockType) if enough bits are available
    for (auto& bit : args)
        *this << bit;
    return *this;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::push_back(bool val)
{
    *this << val;
    return *this;
}

template<typename BlockType>
std::ostream& operator<<(std::ostream& out, const Bitstream_Generic<BlockType>& bitstream)
{
    for (const auto& bit : bitstream.bits)
        out.write((const char*)&bit, sizeof(bit));
    return out;
}

template<typename BlockType>
std::istream& operator>>(std::istream& in, Bitstream_Generic<BlockType>& bitstream)
{
    BlockType b = 0;
    while (in.read((char*) &b, sizeof(b)))
        bitstream << b;
    return in;
}

template<typename BlockType>
size_t Bitstream_Generic<BlockType>::size() const
{
    return sz;
}

template<typename BlockType>
void Bitstream_Generic<BlockType>::fill()
{
    // set all remaining bits in the last block to 1
    while (bit_idx <= block_size)
        *this << true;
}

template<typename BlockType>
typename Bitstream_Generic<BlockType>::BitView Bitstream_Generic<BlockType>::operator[](unsigned int pos) {
    auto block_idx = static_cast<unsigned int>(pos / block_size);
    auto bit_idx = static_cast<uint8_t>(block_size - (pos - block_idx * block_size) - 1);

    return BitView(bits, block_idx, bit_idx);
}

// Convenience definitions (new type alias format)
using Bitstream8 = Bitstream_Generic<uint8_t>;
using Bitstream16 = Bitstream_Generic<uint16_t>;
using Bitstream32 = Bitstream_Generic<uint32_t>;
using Bitstream64 = Bitstream_Generic<uint64_t>;
using Bitstream = Bitstream64;

typedef std::initializer_list<bool> Bits;<commit_msg>Range checking in Bitstream_Generic::operator[] and some comments.<commit_after>#pragma once

#include <cstdint>
#include <vector>
#include <initializer_list>
#include <ostream>
#include <istream>

// Bitstream_Generic[0] is the least significant bit (LSB)
// Bitsream[Bitstream_Generic.size()-1] is the most significant bit (MSB)
template <typename BlockType>
class Bitstream_Generic
{
public:
    friend class BitView;
    static const auto block_size = sizeof(BlockType) * 8;

    typedef std::vector<BlockType> ContainerType;

    class BitView
    {

        friend class Bitstream_Generic<BlockType>;
        BitView(ContainerType& bstream, unsigned int block_idx, uint8_t bit_idx)
            : bits(bstream),
            block_index(block_idx),
            bit_index(bit_idx)
        {}

        ContainerType& bits;
        const unsigned int block_index;
        const uint8_t bit_index;

    public:
        operator bool() const
        {
            return (bits[block_index] & ((BlockType) 1 << bit_index)) != 0;
        }

        void operator=(bool val)
        {
            auto& block = bits[block_index];
            if (val) {
                // set bit at bit_idx
                auto mask = (BlockType) 1 << bit_index;
                block |= mask;
            }
            else {
                // unset bit at bit_idx
                auto mask = ~((BlockType) 1 << bit_index);
                block &= mask;
            }
        }
    };

private:
    ContainerType bits;
    uint8_t bit_idx;
    size_t sz;

private:
    // appending Blocks, don't let the user see this as it needs proper alignment,
    // only used for reading in a file
    Bitstream_Generic& operator<<(BlockType val);

public:
    // ctors
    Bitstream_Generic();
    Bitstream_Generic(std::initializer_list<bool> args);

    // appending bits
    Bitstream_Generic& operator<<(bool val);
    Bitstream_Generic& operator<<(std::initializer_list<bool> args);
    Bitstream_Generic& push_back(bool val);

    // streaming
    template<typename BlockType>
    friend std::ostream& operator<<(std::ostream& out, const Bitstream_Generic<BlockType>& bitstream);
    template<typename BlockType>
    friend std::istream& operator>>(std::istream& in, Bitstream_Generic<BlockType>& bitstream);

    // accessing
    BitView operator[](unsigned int pos);

    // others
    size_t size() const;
    void fill(); // fill remaining bits in the last block with 1s
};

//
// Implementation
//
template<typename BlockType>
Bitstream_Generic<BlockType>::Bitstream_Generic()
: bit_idx(block_size),
bits(),
sz(0)
{}

template<typename BlockType>
Bitstream_Generic<BlockType>::Bitstream_Generic(std::initializer_list<bool> args)
: Bitstream_Generic()
{
    *this << args;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::operator<<(bool val)
{
    // make bit stream longer if we run out of space
    if (bit_idx >= block_size) {
        bits.push_back(0);
        bit_idx = block_size - 1;
    }

    auto& block = bits.back();
    if (val) {
        // set bit at bit_idx
        auto mask = (BlockType) 1 << bit_idx;
        block |= mask;
    }

    --bit_idx; // wraps around to 255 if it was 0
    ++sz;

    return *this;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::operator<<(BlockType val)
{
    bits.push_back(val);
    sz += block_size;
    return *this;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::operator<<(std::initializer_list<bool> args)
{
    // todo: perf improve: use operator<<(bool) as long as the block is not aligned
    //          then use operator<<(BlockType) if enough bits are available
    for (auto& bit : args)
        *this << bit;
    return *this;
}

template<typename BlockType>
Bitstream_Generic<BlockType>& Bitstream_Generic<BlockType>::push_back(bool val)
{
    *this << val;
    return *this;
}

template<typename BlockType>
std::ostream& operator<<(std::ostream& out, const Bitstream_Generic<BlockType>& bitstream)
{
    for (const auto& bit : bitstream.bits)
        out.write((const char*)&bit, sizeof(bit));
    return out;
}

template<typename BlockType>
std::istream& operator>>(std::istream& in, Bitstream_Generic<BlockType>& bitstream)
{
    BlockType b = 0;
    // only reads sizeof(b) bytes, if the istream was not aligned to that, the rest is ignored
    while (in.read((char*) &b, sizeof(b)))
        bitstream << b;
    return in;
}

template<typename BlockType>
size_t Bitstream_Generic<BlockType>::size() const
{
    return sz;
}

template<typename BlockType>
void Bitstream_Generic<BlockType>::fill()
{
    // set all remaining bits in the last block to 1
    while (bit_idx <= block_size)
        *this << true;
}

template<typename BlockType>
typename Bitstream_Generic<BlockType>::BitView Bitstream_Generic<BlockType>::operator[](unsigned int pos) {
    assert(pos < size());
    auto block_idx = static_cast<unsigned int>(pos / block_size);
    auto bit_idx = static_cast<uint8_t>(block_size - (pos - block_idx * block_size) - 1);

    return BitView(bits, block_idx, bit_idx);
}

// Convenience definitions (new type alias format)
using Bitstream8 = Bitstream_Generic<uint8_t>;
using Bitstream16 = Bitstream_Generic<uint16_t>;
using Bitstream32 = Bitstream_Generic<uint32_t>;
using Bitstream64 = Bitstream_Generic<uint64_t>;
using Bitstream = Bitstream64;

typedef std::initializer_list<bool> Bits;<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//	     other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#ifndef IE_CORE_FASTFLOAT_INL
#define IE_CORE_FASTFLOAT_INL

namespace IECore
{
#define IECORE_DOUBLEMAGICROUNDEPS	(.5-1.4e-11)

#if (defined(__linux__) && defined(__i386__)) || defined(WIN32)
	#define IECORE_DOUBLEMAGIC			double (6755399441055744.0)

	inline int fastFloat2Int( double v )
	{
		 return ( v < 0.0 ) ? fastFloatRound( v + IECORE_DOUBLEMAGICROUNDEPS ) : fastFloatRound(v-IECORE_DOUBLEMAGICROUNDEPS );
	}

	union FastFloatDoubleLong
	{
		double d;
		long l;
	};

	inline int fastFloatRound( double v )
	{
		FastFloatDoubleLong vv;
		vv.d = v + IECORE_DOUBLEMAGIC;
		return vv.l;
	}

	inline int fastFloatFloor( double v )
	{
		return fastFloatRound( v - IECORE_DOUBLEMAGICROUNDEPS );
	}

	inline int fastFloatCeil( double v )
	{
		return fastFloatRound( v + IECORE_DOUBLEMAGICROUNDEPS );
	}

	union FastFloatFloatInt
	{
		float f;
		int i;
	};

	// From: http://www.beyond3d.com/articles/fastinvsqrt/
	inline float fastFloatInvSqrt( float x )
	{
		float xhalf = 0.5f * x;
		FastFloatFloatInt u;
		u.f = x;
		u.i = 0x5f3759df - (u.i >> 1 );
		x = u.f;
		x = x*(1.5f - xhalf*x*x);
		return x;
	}

#else

	inline int fastFloat2Int( double v )
	{
		 return (int)v;
	}

	inline int fastFloatRound( double v )
	{
		return int( v+IECORE_DOUBLEMAGICROUNDEPS );
	}

	inline int fastFloatFloor( double v )
	{
		return (int)floorf( v );
	}

	inline int fastFloatCeil( double v )
	{
		return (int)ceilf( v );
	}

	inline float fastFloatInvSqrt( float x )
	{
		return 1.0f / sqrtf(x);
	}

#endif

} // namespace IECore

#endif // IE_CORE_FASTFLOAT_INL
<commit_msg>Enabling fast float flooring on 64 bit architectures.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//	     other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////

#ifndef IE_CORE_FASTFLOAT_INL
#define IE_CORE_FASTFLOAT_INL

namespace IECore
{
#define IECORE_DOUBLEMAGICROUNDEPS	(.5-1.4e-11)

#if (defined(__linux__) && ( defined(__i386__) || defined(__x86_64__) ) ) || defined(WIN32)
	#define IECORE_DOUBLEMAGIC			double (6755399441055744.0)

	inline int fastFloat2Int( double v )
	{
		 return ( v < 0.0 ) ? fastFloatRound( v + IECORE_DOUBLEMAGICROUNDEPS ) : fastFloatRound(v-IECORE_DOUBLEMAGICROUNDEPS );
	}

	union FastFloatDoubleLong
	{
		double d;
		long l;
	};

	inline int fastFloatRound( double v )
	{
		FastFloatDoubleLong vv;
		vv.d = v + IECORE_DOUBLEMAGIC;
		return vv.l;
	}

	inline int fastFloatFloor( double v )
	{
		return fastFloatRound( v - IECORE_DOUBLEMAGICROUNDEPS );
	}

	inline int fastFloatCeil( double v )
	{
		return fastFloatRound( v + IECORE_DOUBLEMAGICROUNDEPS );
	}

	union FastFloatFloatInt
	{
		float f;
		int i;
	};

	// From: http://www.beyond3d.com/articles/fastinvsqrt/
	inline float fastFloatInvSqrt( float x )
	{
		float xhalf = 0.5f * x;
		FastFloatFloatInt u;
		u.f = x;
		u.i = 0x5f3759df - (u.i >> 1 );
		x = u.f;
		x = x*(1.5f - xhalf*x*x);
		return x;
	}

#else

	inline int fastFloat2Int( double v )
	{
		 return (int)v;
	}

	inline int fastFloatRound( double v )
	{
		return int( v+IECORE_DOUBLEMAGICROUNDEPS );
	}

	inline int fastFloatFloor( double v )
	{
		return (int)floorf( v );
	}

	inline int fastFloatCeil( double v )
	{
		return (int)ceilf( v );
	}

	inline float fastFloatInvSqrt( float x )
	{
		return 1.0f / sqrtf(x);
	}

#endif

} // namespace IECore

#endif // IE_CORE_FASTFLOAT_INL
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>

#include <Poco\Stopwatch.h>
#include <Poco\Stopwatch.h>

#include "StreamLatencyMeasurementTest.h"

using std::cerr;
using std::cout;
using std::endl;
using Poco::Stopwatch;
using Poco::Exception;

string boundary = "--VIDEOSTREAM\r\n";
string contentLength = "Content-Length: ";
string length = "Length";
string jpeg = "jpeg\r\n";
string lineend = "\r\n";

#if defined(_MSC_VER) || defined(WIN32)  || defined(_WIN32) || defined(__WIN32__) \
	|| defined(WIN64) || defined(_WIN64) || defined(__WIN64__)

#include <windows.h>
bool _qpcInited = false;
double PCFreq = 0.0;
__int64 CounterStart = 0;
void InitCounter()
{
	LARGE_INTEGER li;
	if (!QueryPerformanceFrequency(&li))
	{
		std::cout << "QueryPerformanceFrequency failed!\n";
	}
	PCFreq = double(li.QuadPart) / 1000.0f;
	_qpcInited = true;
}
double CLOCK()
{
	if (!_qpcInited) InitCounter();
	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);
	return double(li.QuadPart) / PCFreq;
}

#endif

double _avgdur = 0;
double _fpsstart = 0;
double _avgfps = 0;
double _fps1sec = 0;

double avgdur(double newdur)
{
	_avgdur = 0.98*_avgdur + 0.02*newdur;
	return _avgdur;
}

StreamLatencyMeasurementTest::StreamLatencyMeasurementTest(URI uri)
	: uri(uri), Task("StreamLatencyMeasurementTest"), socketAddr(uri.getHost(), uri.getPort()), socket(), stream(socket)
{
}

void StreamLatencyMeasurementTest::runTask()
{
	try {
		socket.connect(socketAddr);

		string request = "GET /videostream HTTP/1.1\r\nHost: 192.168.0.15:4711\r\nConnection: keep - alive\r\nAccept : image / webp, */*;q=0.8\r\n\r\n";

		SendFrame(request);

		double start = 0.0;
		double end = 0.0;
		long frameno = 0;
		long data = 0;
		Stopwatch sw;

		sw.start();
		while (sw.elapsedSeconds() <= 10) {
			double start = CLOCK();

			int size = FindLength();
			if (size == -1) {
				cerr << endl << "could not find length" << endl;
				break;
			}

			MoveToStreamStart();

			GetBytes(size);
			data += size;

			double dur = CLOCK() - start;
			printf("frame: %f ms; avg per frame %f ms; frameno: %u; data: %u\r", dur, avgdur(dur), frameno++, data);
		}

		socket.close();
	}
	catch (Exception& e) {
		cerr << endl;
		cerr << "Exception: " << e.what() << endl;
		cerr << "Message: " << e.message() << endl;
		cerr << e.displayText() << endl;
	}
}

void StreamLatencyMeasurementTest::MoveToStreamStart() {
	while (1) {
		string response;

		GetFrame(response, '\n');
		std::size_t start = response.find(jpeg);

		if (start != 0 && start != string::npos) {
			return;
		}
	}
}

int StreamLatencyMeasurementTest::FindLength() {
	bool foundLength = false;
	int size = -1;

	while (!foundLength) {
		string response;

		GetFrame(response, '\n');
		std::size_t start = response.find(length);

		if (start != 0 && start != string::npos) {
			std::size_t end = response.find_last_of(lineend);

			string strSize = response.substr(contentLength.length(), 5);
			size = stoi(strSize);
			foundLength = true;
		}
	}

	return size;
}

bool StreamLatencyMeasurementTest::GetBytes(int bytesToRead) {
	char* buff = new char[bytesToRead];
	int receivedBytes = 0;
	int temp;
	try {
		while (bytesToRead > receivedBytes) {
			temp = socket.receiveBytes(buff + receivedBytes, bytesToRead - receivedBytes);
			if (temp == 0) std::cout << "empty frame!" << std::endl;
			receivedBytes += temp;
		}
	}
	catch (Exception error) {
		std::cout << "recv failed (Error: " << error.displayText() << ')' << std::endl;
		return false;
	}
	return true;
}

bool StreamLatencyMeasurementTest::GetFrame(std::string& frame, char delimiter) {
	char c;
	try {
		do {
			socket.receiveBytes(&c, 1);
			frame.append(1, c);
		} while (delimiter != c);
	}
	catch (Exception e) {
		cerr << e.displayText() << endl;
		return false;
	}
	return true;
}

bool StreamLatencyMeasurementTest::SendFrame(const std::string& frame) {
	int tmp = 0;
	int bytesToWrite = frame.length();
	const char* bytes = frame.c_str();

	try {
		while (bytesToWrite > tmp) {
			tmp += socket.sendBytes(bytes + tmp, bytesToWrite - tmp);
		}
	}
	catch (Exception e) {
		cerr << e.displayText() << endl;
		return false;
	}

	return true;
}<commit_msg>update performance measurement test<commit_after>#include <iostream>
#include <iomanip>

#include <Poco\Stopwatch.h>
#include <Poco\Stopwatch.h>

#include "StreamLatencyMeasurementTest.h"

using std::cerr;
using std::cout;
using std::endl;
using Poco::Stopwatch;
using Poco::Exception;

string boundary = "--VIDEOSTREAM\r\n";
string contentLength = "Content-Length: ";
string length = "Length";
string jpeg = "jpeg\r\n";
string lineend = "\r\n";

#if defined(_MSC_VER) || defined(WIN32)  || defined(_WIN32) || defined(__WIN32__) \
	|| defined(WIN64) || defined(_WIN64) || defined(__WIN64__)

#include <windows.h>
bool _qpcInited = false;
double PCFreq = 0.0;
__int64 CounterStart = 0;
void InitCounter()
{
	LARGE_INTEGER li;
	if (!QueryPerformanceFrequency(&li))
	{
		std::cout << "QueryPerformanceFrequency failed!\n";
	}
	PCFreq = double(li.QuadPart) / 1000.0f;
	_qpcInited = true;
}
double CLOCK()
{
	if (!_qpcInited) InitCounter();
	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);
	return double(li.QuadPart) / PCFreq;
}

#endif

double _avgdur = 0;
double _fpsstart = 0;
double _avgfps = 0;
double _fps1sec = 0;

double avgdur(double newdur)
{
	_avgdur = 0.98*_avgdur + 0.02*newdur;
	return _avgdur;
}

StreamLatencyMeasurementTest::StreamLatencyMeasurementTest(URI uri)
	: uri(uri), Task("StreamLatencyMeasurementTest"), socketAddr(uri.getHost(), uri.getPort()), socket(), stream(socket)
{
}

void StreamLatencyMeasurementTest::runTask()
{
	try {
		socket.connect(socketAddr);

		string request = "GET /videostream HTTP/1.1\r\nHost: 192.168.0.15:4711\r\nConnection: keep - alive\r\nAccept : image / webp, */*;q=0.8\r\n\r\n";

		SendFrame(request);

		double start = 0.0;
		double end = 0.0;
		int frameno = 0;
		long data = 0;
		Stopwatch sw;

		sw.start();
		while (sw.elapsedSeconds() < 60) {
			double start = CLOCK();

			int size = FindLength();
			if (size == -1) {
				cerr << endl << "could not find length" << endl;
				break;
			}

			MoveToStreamStart();

			GetBytes(size);
			data += size;

			double dur = CLOCK() - start;
			printf("frame: %04.2f ms; avg/frame %04.2f ms; frame#: %04u; bytes: %08u\r", dur, avgdur(dur), frameno++, data);
		}

		printf("\n\r##################################\n\r");
		printf("time: %u sec; avg/frame %.2f ms; frames: %4u; data: %.2f mb\r", sw.elapsedSeconds(), _avgdur, --frameno, ((double)data / 1024 / 1014));

		socket.close();
	}
	catch (Exception& e) {
		cerr << endl;
		cerr << "Exception: " << e.what() << endl;
		cerr << "Message: " << e.message() << endl;
		cerr << e.displayText() << endl;
	}
}

void StreamLatencyMeasurementTest::MoveToStreamStart() {
	while (1) {
		string response;

		GetFrame(response, '\n');
		std::size_t start = response.find(jpeg);

		if (start != 0 && start != string::npos) {
			return;
		}
	}
}

int StreamLatencyMeasurementTest::FindLength() {
	bool foundLength = false;
	int size = -1;

	while (!foundLength) {
		string response;

		GetFrame(response, '\n');
		std::size_t start = response.find(length);

		if (start != 0 && start != string::npos) {
			std::size_t end = response.find_last_of(lineend);

			string strSize = response.substr(contentLength.length(), 5);
			size = stoi(strSize);
			foundLength = true;
		}
	}

	return size;
}

bool StreamLatencyMeasurementTest::GetBytes(int bytesToRead) {
	char* buff = new char[bytesToRead];
	int receivedBytes = 0;
	int temp;
	try {
		while (bytesToRead > receivedBytes) {
			temp = socket.receiveBytes(buff + receivedBytes, bytesToRead - receivedBytes);
			if (temp == 0) std::cout << "empty frame!" << std::endl;
			receivedBytes += temp;
		}
	}
	catch (Exception error) {
		std::cout << "recv failed (Error: " << error.displayText() << ')' << std::endl;
		return false;
	}
	return true;
}

bool StreamLatencyMeasurementTest::GetFrame(std::string& frame, char delimiter) {
	char c;
	try {
		do {
			socket.receiveBytes(&c, 1);
			frame.append(1, c);
		} while (delimiter != c);
	}
	catch (Exception e) {
		cerr << e.displayText() << endl;
		return false;
	}
	return true;
}

bool StreamLatencyMeasurementTest::SendFrame(const std::string& frame) {
	int tmp = 0;
	int bytesToWrite = frame.length();
	const char* bytes = frame.c_str();

	try {
		while (bytesToWrite > tmp) {
			tmp += socket.sendBytes(bytes + tmp, bytesToWrite - tmp);
		}
	}
	catch (Exception e) {
		cerr << e.displayText() << endl;
		return false;
	}

	return true;
}<|endoftext|>