<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "common.h"
#include "CommonTypes.h"
#include "CommonMacros.h"
#include "daccess.h"
#include "PalRedhawkCommon.h"
#include "PalRedhawk.h"
#include "rhassert.h"
#include "slist.h"
#include "holder.h"
#include "Crst.h"
#include "rhbinder.h"
#include "RWLock.h"
#include "RuntimeInstance.h"
#include "GenericUnification.h"
#include "EEType.h"

bool GenericUnificationHashtable::GrowTable(UInt32 minSize)
{
    // immediately give up for ridiculously large sizes
    if (minSize >= 1024 * 1024 * 1024 / sizeof(Entry *))
        return false;

    UInt32 newSize = max(1024, m_tableSize);
    while (newSize < minSize)
        newSize *= 2;

    // newSize should be a power of 2 as we always double the size of the table
    // we rely on this property, otherwise masking off bits to index wouldn't work
    ASSERT((newSize & (newSize - 1)) == 0);

    Entry ** newTable = new (nothrow) Entry*[newSize];
    if (newTable == nullptr)
        return false;

    memset(newTable, 0, sizeof(newTable[0])*newSize);
    UInt32 newHashMask = newSize - 1;

    for (UInt32 i = 0; i < m_tableSize; i++)
    {
        Entry * pNextEntry;
        for (Entry *pEntry = m_table[i]; pEntry != nullptr; pEntry = pNextEntry)
        {
            pNextEntry = pEntry->m_nextInHash;

            GenericUnificationDesc * pDesc = pEntry->m_desc;
            UInt32 hashCode = pDesc->m_hashCode & newHashMask;

            pEntry->m_nextInHash = newTable[hashCode];
            newTable[hashCode] = pEntry;
        }
    }

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

    m_table = newTable;
    m_tableSize = newSize;
    m_hashMask = newHashMask;

    return true;
}

// this generic type or method is not a duplicate - enter it into the hash table
bool GenericUnificationHashtable::EnterDesc(GenericUnificationDesc *pDesc, UIntTarget *pIndirCells)
{
    if (m_tableSize < m_entryCount)
    {
        if (!GrowTable(m_entryCount))
            return false;
    }

    m_entryCount++;

    UInt32 hashCode = pDesc->m_hashCode & m_hashMask;

    Entry *pEntry = new (nothrow) Entry(m_table[hashCode], pDesc, pIndirCells);
    if (pEntry == nullptr)
        return false;
    m_table[hashCode] = pEntry;

    if (pDesc->m_flags & GUF_GC_STATICS)
    {
        UInt32 indirCellIndex = pDesc->GetIndirCellIndex(GUF_GC_STATICS);
        UInt8 *pGcStaticData = (UInt8 *)pIndirCells[indirCellIndex];
        StaticGcDesc *pGcStaticsDesc = (StaticGcDesc *)pIndirCells[indirCellIndex + 1];
        if (!GetRuntimeInstance()->AddDynamicGcStatics(pGcStaticData, pGcStaticsDesc))
            return false;
    }

    if (pDesc->m_flags & GUF_THREAD_STATICS)
    {
        UInt32 indirCellIndex = pDesc->GetIndirCellIndex(GUF_THREAD_STATICS);
        UInt32 tlsIndex = *(UInt32 *)pIndirCells[indirCellIndex];
        UInt32 tlsOffset = (UInt32)pIndirCells[indirCellIndex + 1];
        StaticGcDesc *pGcStaticsDesc = (StaticGcDesc *)pIndirCells[indirCellIndex + 2];
        if (!GetRuntimeInstance()->AddDynamicThreadStaticGcData(tlsIndex, tlsOffset, pGcStaticsDesc))
            return false;
    }

    return true;
}

// we have found a duplicate - copy the indirection cells from the winner over those from the loser
void GenericUnificationHashtable::CopyIndirCells(Entry *pWinnerEntry, GenericUnificationDesc *pLoserDesc, UIntTarget *pLoserIndirCells)
{
    GenericUnificationDesc *pWinnerDesc = pWinnerEntry->m_desc;
    UIntTarget *pWinnerIndirCells = pWinnerEntry->m_indirCells;

    ASSERT(pWinnerDesc->m_flags == pLoserDesc->m_flags);

    UInt32 winnerIndirCellCount = pWinnerDesc->GetIndirCellCount();
    UInt32 loserIndirCellCount = pLoserDesc->GetIndirCellCount();

    ASSERT(winnerIndirCellCount == loserIndirCellCount);
    for (UInt32 i = 0; i < winnerIndirCellCount; i++)
    {
        if (i < loserIndirCellCount && pWinnerIndirCells[i] != 0)
        {
            pLoserIndirCells[i] = pWinnerIndirCells[i];
        }
    }
}

// unify one generic type or method
bool GenericUnificationHashtable::UnifyDesc(GenericUnificationDesc *pDesc, UIntTarget *pIndirCells)
{
    UInt32 hashCode = pDesc->m_hashCode & m_hashMask;

    for (Entry *pEntry = m_table[hashCode]; pEntry != nullptr; pEntry = pEntry->m_nextInHash)
    {
        if (pEntry->m_desc->Equals(pDesc))
        {
            CopyIndirCells(pEntry, pDesc, pIndirCells);

#if defined(GENERIC_UNIFICATION_STATS)
            m_duplicateCount++;
#endif

            return true;
        }
    }
    return EnterDesc(pDesc, pIndirCells);
}

#if defined(GENERIC_UNIFICATION_STATS)
#ifdef _X86_
static UInt64 GetTicks()
{
    _asm rdtsc
}
#else
#define GetTicks    PalGetTickCount
#endif
#endif

// unify an array of descriptors describing a parallel array of indirection cells
bool GenericUnificationHashtable::UnifyDescs(GenericUnificationDesc *descs, UInt32 descCount, UIntTarget *pIndirCells, UInt32 indirCellCount)
{
    UNREFERENCED_PARAMETER(indirCellCount);
    ASSERT(descCount < 128 * 1024 * 1024);
    if (m_tableSize < descCount)
    {
        if (!GrowTable(descCount))
            return false;
    }

#if defined(GENERIC_UNIFICATION_STATS)
    m_indirCellCount += indirCellCount;
    UInt64 startTicks = GetTicks();
#endif

    UInt32 indirCellIndex = 0;
    for (UInt32 i = 0; i < descCount; i++)
    {
        ASSERT(indirCellIndex <= indirCellCount);
        ASSERT(descs[i].GetIndirCellCount() <= indirCellCount - indirCellIndex);
        if (!UnifyDesc(&descs[i], &pIndirCells[indirCellIndex]))
            return false;
        indirCellIndex += descs[i].GetIndirCellCount();
    }

#if defined(GENERIC_UNIFICATION_STATS)
    UInt64 elapsedTicks = GetTicks() - startTicks;
    m_elapsedTicks += elapsedTicks;
#endif

    return true;
}

bool GenericUnificationDesc::Equals(GenericUnificationDesc *that)
{
    if (this->m_hashCode != that->m_hashCode)
        return false;

    if (this->m_openType.GetValue() != that->m_openType.GetValue())
        return false;

    if (this->GetOrdinal() != that->GetOrdinal())
        return false;

    return this->m_genericComposition->Equals(that->m_genericComposition);
}

bool GenericComposition::Equals(GenericComposition *that)
{
    if (this->m_arity != that->m_arity)
        return false;

    EETypeRef *thisArgList = this->GetArguments();
    EETypeRef *thatArgList = that->GetArguments();

    for (unsigned i = 0; i < m_arity; i++)
    {
        EEType *thisArg = thisArgList[i].GetValue();
        EEType *thatArg = thatArgList[i].GetValue();

        if (thisArg == thatArg)
            continue;

        if (thisArg == CANON_EETYPE || thatArg == CANON_EETYPE)
            return false;

        if (!thisArg->IsEquivalentTo(thatArg))
            return false;
    }

    return true;
}
<commit_msg>Fix #include casing<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "common.h"
#include "CommonTypes.h"
#include "CommonMacros.h"
#include "daccess.h"
#include "PalRedhawkCommon.h"
#include "PalRedhawk.h"
#include "rhassert.h"
#include "slist.h"
#include "holder.h"
#include "Crst.h"
#include "rhbinder.h"
#include "RWLock.h"
#include "RuntimeInstance.h"
#include "GenericUnification.h"
#include "eetype.h"

bool GenericUnificationHashtable::GrowTable(UInt32 minSize)
{
    // immediately give up for ridiculously large sizes
    if (minSize >= 1024 * 1024 * 1024 / sizeof(Entry *))
        return false;

    UInt32 newSize = max(1024, m_tableSize);
    while (newSize < minSize)
        newSize *= 2;

    // newSize should be a power of 2 as we always double the size of the table
    // we rely on this property, otherwise masking off bits to index wouldn't work
    ASSERT((newSize & (newSize - 1)) == 0);

    Entry ** newTable = new (nothrow) Entry*[newSize];
    if (newTable == nullptr)
        return false;

    memset(newTable, 0, sizeof(newTable[0])*newSize);
    UInt32 newHashMask = newSize - 1;

    for (UInt32 i = 0; i < m_tableSize; i++)
    {
        Entry * pNextEntry;
        for (Entry *pEntry = m_table[i]; pEntry != nullptr; pEntry = pNextEntry)
        {
            pNextEntry = pEntry->m_nextInHash;

            GenericUnificationDesc * pDesc = pEntry->m_desc;
            UInt32 hashCode = pDesc->m_hashCode & newHashMask;

            pEntry->m_nextInHash = newTable[hashCode];
            newTable[hashCode] = pEntry;
        }
    }

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

    m_table = newTable;
    m_tableSize = newSize;
    m_hashMask = newHashMask;

    return true;
}

// this generic type or method is not a duplicate - enter it into the hash table
bool GenericUnificationHashtable::EnterDesc(GenericUnificationDesc *pDesc, UIntTarget *pIndirCells)
{
    if (m_tableSize < m_entryCount)
    {
        if (!GrowTable(m_entryCount))
            return false;
    }

    m_entryCount++;

    UInt32 hashCode = pDesc->m_hashCode & m_hashMask;

    Entry *pEntry = new (nothrow) Entry(m_table[hashCode], pDesc, pIndirCells);
    if (pEntry == nullptr)
        return false;
    m_table[hashCode] = pEntry;

    if (pDesc->m_flags & GUF_GC_STATICS)
    {
        UInt32 indirCellIndex = pDesc->GetIndirCellIndex(GUF_GC_STATICS);
        UInt8 *pGcStaticData = (UInt8 *)pIndirCells[indirCellIndex];
        StaticGcDesc *pGcStaticsDesc = (StaticGcDesc *)pIndirCells[indirCellIndex + 1];
        if (!GetRuntimeInstance()->AddDynamicGcStatics(pGcStaticData, pGcStaticsDesc))
            return false;
    }

    if (pDesc->m_flags & GUF_THREAD_STATICS)
    {
        UInt32 indirCellIndex = pDesc->GetIndirCellIndex(GUF_THREAD_STATICS);
        UInt32 tlsIndex = *(UInt32 *)pIndirCells[indirCellIndex];
        UInt32 tlsOffset = (UInt32)pIndirCells[indirCellIndex + 1];
        StaticGcDesc *pGcStaticsDesc = (StaticGcDesc *)pIndirCells[indirCellIndex + 2];
        if (!GetRuntimeInstance()->AddDynamicThreadStaticGcData(tlsIndex, tlsOffset, pGcStaticsDesc))
            return false;
    }

    return true;
}

// we have found a duplicate - copy the indirection cells from the winner over those from the loser
void GenericUnificationHashtable::CopyIndirCells(Entry *pWinnerEntry, GenericUnificationDesc *pLoserDesc, UIntTarget *pLoserIndirCells)
{
    GenericUnificationDesc *pWinnerDesc = pWinnerEntry->m_desc;
    UIntTarget *pWinnerIndirCells = pWinnerEntry->m_indirCells;

    ASSERT(pWinnerDesc->m_flags == pLoserDesc->m_flags);

    UInt32 winnerIndirCellCount = pWinnerDesc->GetIndirCellCount();
    UInt32 loserIndirCellCount = pLoserDesc->GetIndirCellCount();

    ASSERT(winnerIndirCellCount == loserIndirCellCount);
    for (UInt32 i = 0; i < winnerIndirCellCount; i++)
    {
        if (i < loserIndirCellCount && pWinnerIndirCells[i] != 0)
        {
            pLoserIndirCells[i] = pWinnerIndirCells[i];
        }
    }
}

// unify one generic type or method
bool GenericUnificationHashtable::UnifyDesc(GenericUnificationDesc *pDesc, UIntTarget *pIndirCells)
{
    UInt32 hashCode = pDesc->m_hashCode & m_hashMask;

    for (Entry *pEntry = m_table[hashCode]; pEntry != nullptr; pEntry = pEntry->m_nextInHash)
    {
        if (pEntry->m_desc->Equals(pDesc))
        {
            CopyIndirCells(pEntry, pDesc, pIndirCells);

#if defined(GENERIC_UNIFICATION_STATS)
            m_duplicateCount++;
#endif

            return true;
        }
    }
    return EnterDesc(pDesc, pIndirCells);
}

#if defined(GENERIC_UNIFICATION_STATS)
#ifdef _X86_
static UInt64 GetTicks()
{
    _asm rdtsc
}
#else
#define GetTicks    PalGetTickCount
#endif
#endif

// unify an array of descriptors describing a parallel array of indirection cells
bool GenericUnificationHashtable::UnifyDescs(GenericUnificationDesc *descs, UInt32 descCount, UIntTarget *pIndirCells, UInt32 indirCellCount)
{
    UNREFERENCED_PARAMETER(indirCellCount);
    ASSERT(descCount < 128 * 1024 * 1024);
    if (m_tableSize < descCount)
    {
        if (!GrowTable(descCount))
            return false;
    }

#if defined(GENERIC_UNIFICATION_STATS)
    m_indirCellCount += indirCellCount;
    UInt64 startTicks = GetTicks();
#endif

    UInt32 indirCellIndex = 0;
    for (UInt32 i = 0; i < descCount; i++)
    {
        ASSERT(indirCellIndex <= indirCellCount);
        ASSERT(descs[i].GetIndirCellCount() <= indirCellCount - indirCellIndex);
        if (!UnifyDesc(&descs[i], &pIndirCells[indirCellIndex]))
            return false;
        indirCellIndex += descs[i].GetIndirCellCount();
    }

#if defined(GENERIC_UNIFICATION_STATS)
    UInt64 elapsedTicks = GetTicks() - startTicks;
    m_elapsedTicks += elapsedTicks;
#endif

    return true;
}

bool GenericUnificationDesc::Equals(GenericUnificationDesc *that)
{
    if (this->m_hashCode != that->m_hashCode)
        return false;

    if (this->m_openType.GetValue() != that->m_openType.GetValue())
        return false;

    if (this->GetOrdinal() != that->GetOrdinal())
        return false;

    return this->m_genericComposition->Equals(that->m_genericComposition);
}

bool GenericComposition::Equals(GenericComposition *that)
{
    if (this->m_arity != that->m_arity)
        return false;

    EETypeRef *thisArgList = this->GetArguments();
    EETypeRef *thatArgList = that->GetArguments();

    for (unsigned i = 0; i < m_arity; i++)
    {
        EEType *thisArg = thisArgList[i].GetValue();
        EEType *thatArg = thatArgList[i].GetValue();

        if (thisArg == thatArg)
            continue;

        if (thisArg == CANON_EETYPE || thatArg == CANON_EETYPE)
            return false;

        if (!thisArg->IsEquivalentTo(thatArg))
            return false;
    }

    return true;
}
<|endoftext|>


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

#ifndef _PAGES_HXX_
#define _PAGES_HXX_

#include <vcl/tabpage.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/dialog.hxx>
#include <vcl/scrbar.hxx>
#include <svtools/wizardmachine.hxx>
#include <svtools/svmedit.hxx>
#include <svtools/lstner.hxx>
#include <svtools/xtextedt.hxx>

namespace desktop
{
class WelcomePage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    svt::OWizardMachine *m_pParent;
    enum OEMType
    {
        OEM_NONE, OEM_NORMAL, OEM_EXTENDED
    };
    OEMType checkOEM();
    bool checkEval();

public:
    WelcomePage( svt::OWizardMachine* parent, const ResId& resid);
protected:
    virtual void ActivatePage();
};

class LicenseView : public MultiLineEdit, public SfxListener
{
    BOOL            mbEndReached;
    Link            maEndReachedHdl;
    Link            maScrolledHdl;

public:
    LicenseView( Window* pParent, const ResId& rResId );
    ~LicenseView();

    void ScrollDown( ScrollType eScroll );

    BOOL IsEndReached() const;
    BOOL EndReached() const { return mbEndReached; }
    void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; }

    void SetEndReachedHdl( const Link& rHdl )  { maEndReachedHdl = rHdl; }
    const Link& GetAutocompleteHdl() const { return maEndReachedHdl; }

    void SetScrolledHdl( const Link& rHdl )  { maScrolledHdl = rHdl; }
    const Link& GetScrolledHdl() const { return maScrolledHdl; }

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};

class LicensePage : public svt::OWizardPage
{
private:
    svt::OWizardMachine *m_pParent;
    FixedText m_ftHead;
    FixedText m_ftBody1;
    FixedText m_ftBody1Txt;
    FixedText m_ftBody2;
    FixedText m_ftBody2Txt;
    LicenseView m_mlLicense;
    PushButton m_pbDown;
    sal_Bool m_bLicenseRead;
public:
    LicensePage( svt::OWizardMachine* parent, const ResId& resid);
private:
    DECL_LINK(PageDownHdl, PushButton*);
    DECL_LINK(EndReachedHdl, LicenseView*);
    DECL_LINK(ScrolledHdl, LicenseView*);
protected:
    virtual sal_Bool determineNextButtonState();
    virtual void ActivatePage();
};

class MigrationPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    CheckBox m_cbMigration;
    sal_Bool m_bMigrationDone;
public:
    MigrationPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage(COMMIT_REASON _eReason);

protected:
    virtual void ActivatePage();
};

class UserPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    FixedText m_ftFirst;
    Edit m_edFirst;
    FixedText m_ftLast;
    Edit m_edLast;
    FixedText m_ftInitials;
    Edit m_edInitials;
    FixedText m_ftFather;
    Edit m_edFather;
    LanguageType m_lang;

public:
    UserPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage(COMMIT_REASON _eReason);
protected:
    virtual void ActivatePage();
};

class RegistrationPage : public svt::OWizardPage
{
private:
    FixedText m_ftHeader;
    FixedText m_ftBody;
    FixedImage m_fiImage;
    RadioButton m_rbNow;
    RadioButton m_rbLater;
    RadioButton m_rbNever;
    RadioButton m_rbReg;
    FixedLine m_flSeparator;
    FixedText m_ftEnd;
public:
    RegistrationPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage(COMMIT_REASON _eReason);
protected:
    virtual sal_Bool determineNextButtonState();
    virtual void ActivatePage();
};

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

#ifndef _PAGES_HXX_
#define _PAGES_HXX_

#include <vcl/tabpage.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/dialog.hxx>
#include <vcl/scrbar.hxx>
#include <svtools/wizardmachine.hxx>
#include <svtools/svmedit.hxx>
#include <svtools/lstner.hxx>
#include <svtools/xtextedt.hxx>

namespace desktop
{
class WelcomePage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    svt::OWizardMachine *m_pParent;
    enum OEMType
    {
        OEM_NONE, OEM_NORMAL, OEM_EXTENDED
    };
    OEMType checkOEM();
    bool checkEval();

public:
    WelcomePage( svt::OWizardMachine* parent, const ResId& resid);
protected:
    virtual void ActivatePage();
};

class LicenseView : public MultiLineEdit, public SfxListener
{
    BOOL            mbEndReached;
    Link            maEndReachedHdl;
    Link            maScrolledHdl;

public:
    LicenseView( Window* pParent, const ResId& rResId );
    ~LicenseView();

    void ScrollDown( ScrollType eScroll );

    BOOL IsEndReached() const;
    BOOL EndReached() const { return mbEndReached; }
    void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; }

    void SetEndReachedHdl( const Link& rHdl )  { maEndReachedHdl = rHdl; }
    const Link& GetAutocompleteHdl() const { return maEndReachedHdl; }

    void SetScrolledHdl( const Link& rHdl )  { maScrolledHdl = rHdl; }
    const Link& GetScrolledHdl() const { return maScrolledHdl; }

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};

class LicensePage : public svt::OWizardPage
{
private:
    svt::OWizardMachine *m_pParent;
    FixedText m_ftHead;
    FixedText m_ftBody1;
    FixedText m_ftBody1Txt;
    FixedText m_ftBody2;
    FixedText m_ftBody2Txt;
    LicenseView m_mlLicense;
    PushButton m_pbDown;
    sal_Bool m_bLicenseRead;
public:
    LicensePage( svt::OWizardMachine* parent, const ResId& resid);
private:
    DECL_LINK(PageDownHdl, PushButton*);
    DECL_LINK(EndReachedHdl, LicenseView*);
    DECL_LINK(ScrolledHdl, LicenseView*);
protected:
    virtual sal_Bool determineNextButtonState();
    virtual void ActivatePage();
};

class MigrationPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    CheckBox m_cbMigration;
    sal_Bool m_bMigrationDone;
public:
    MigrationPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage(COMMIT_REASON _eReason);

protected:
    virtual void ActivatePage();
};

class UserPage : public svt::OWizardPage
{
private:
    FixedText m_ftHead;
    FixedText m_ftBody;
    FixedText m_ftFirst;
    Edit m_edFirst;
    FixedText m_ftLast;
    Edit m_edLast;
    FixedText m_ftInitials;
    Edit m_edInitials;
    FixedText m_ftFather;
    Edit m_edFather;
    LanguageType m_lang;

public:
    UserPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage(COMMIT_REASON _eReason);
protected:
    virtual void ActivatePage();
};

class RegistrationPage : public svt::OWizardPage
{
private:
    FixedText m_ftHeader;
    FixedText m_ftBody;
    FixedImage m_fiImage;
    RadioButton m_rbNow;
    RadioButton m_rbLater;
    RadioButton m_rbNever;
    RadioButton m_rbReg;
    FixedLine m_flSeparator;
    FixedText m_ftEnd;
    sal_Bool    m_bNeverVisible;

    void updateButtonStates();
    void impl_retrieveConfigurationData();

public:
    RegistrationPage( svt::OWizardMachine* parent, const ResId& resid);
    virtual sal_Bool commitPage(COMMIT_REASON _eReason);
protected:
    virtual sal_Bool determineNextButtonState();
    virtual void ActivatePage();
};

}
#endif
<|endoftext|>


<commit_before>#define __STDC_FORMAT_MACROS

#include <stdio.h>
#include <iostream>
#include <signal.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <algorithm>
#include <unistd.h>
#include <getopt.h>

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "lpeg.h"
}

#include <sinsp.h>
#include "config_digwatch.h"
#include "configuration.h"
#include "rules.h"
#include "formats.h"
#include "fields.h"
#include "syslog.h"
#include "utils.h"
#include <yaml-cpp/yaml.h>

static bool g_terminate = false;

static void signal_callback(int signal)
{
	g_terminate = true;
}

std::vector<string> valid_output_names {"stdout", "syslog"};

//
// Program help
//
static void usage()
{
    printf(
	   "Usage: digwatch [options] rules_filename\n\n"
	   "Options:\n"
	   " -h, --help         Print this page\n"
	   " -o                 Output type (options are 'stdout', 'syslog', default is 'stdout')\n"
           " -r <readfile>, --read=<readfile>\n"
           "                    Read the events from <readfile>.\n"
	   "\n"
    );
}

string lua_on_event = "on_event";
string lua_add_output = "add_output";

//
// Event processing loop
//
void do_inspect(sinsp* inspector,
		digwatch_rules* rules,
		lua_State* ls)
{
	int32_t res;
	sinsp_evt* ev;
	string line;

	//
	// Loop through the events
	//
	while(1)
	{

		if(g_terminate)
		{
			break;
		}

		res = inspector->next(&ev);

		if(res == SCAP_TIMEOUT)
		{
			continue;
		}
		else if(res == SCAP_EOF)
		{
			break;
		}
		else if(res != SCAP_SUCCESS)
		{
			//
			// Event read error.
			// Notify the chisels that we're exiting, and then die with an error.
			//
			cerr << "res = " << res << endl;
			throw sinsp_exception(inspector->getlasterr().c_str());
		}

		if(!inspector->is_debug_enabled() &&
			ev->get_category() & EC_INTERNAL)
		{
			continue;
		}

		lua_getglobal(ls, lua_on_event.c_str());

		if(lua_isfunction(ls, -1))
		{
			lua_pushlightuserdata(ls, ev);
			lua_pushnumber(ls, ev->get_check_id());

			if(lua_pcall(ls, 2, 0, 0) != 0)
			{
				const char* lerr = lua_tostring(ls, -1);
				string err = "Error invoking function output: " + string(lerr);
				throw sinsp_exception(err);
			}
		}
		else
		{
			throw sinsp_exception("No function " + lua_on_event + " found in lua compiler module");
		}
	}
}

void add_lua_path(lua_State *ls, string path)
{
	string cpath = string(path);
	path += "?.lua";
	cpath += "?.so";

	lua_getglobal(ls, "package");

	lua_getfield(ls, -1, "path");
	string cur_path = lua_tostring(ls, -1 );
	cur_path += ';';
	lua_pop(ls, 1);

	cur_path.append(path.c_str());

	lua_pushstring(ls, cur_path.c_str());
	lua_setfield(ls, -2, "path");

	lua_getfield(ls, -1, "cpath");
	string cur_cpath = lua_tostring(ls, -1 );
	cur_cpath += ';';
	lua_pop(ls, 1);

	cur_cpath.append(cpath.c_str());

	lua_pushstring(ls, cur_cpath.c_str());
	lua_setfield(ls, -2, "cpath");

	lua_pop(ls, 1);
}

void add_output(lua_State *ls, output_config oc)
{

	uint8_t nargs = 1;
	lua_getglobal(ls, lua_add_output.c_str());

	if(!lua_isfunction(ls, -1))
	{
		throw sinsp_exception("No function " + lua_add_output + " found. ");
	}
	lua_pushstring(ls, oc.name.c_str());

	// If we have options, build up a lua table containing them
	if (oc.options.size())
	{
		nargs = 2;
		lua_createtable(ls, 0, oc.options.size());

		for (auto it = oc.options.cbegin(); it != oc.options.cend(); ++it)
		{
			lua_pushstring(ls, (*it).second.c_str());
			lua_setfield(ls, -2, (*it).first.c_str());
		}
	}

	if(lua_pcall(ls, nargs, 0, 0) != 0)
	{
		const char* lerr = lua_tostring(ls, -1);
		throw sinsp_exception(string(lerr));
	}

}

//
// ARGUMENT PARSING AND PROGRAM SETUP
//
int digwatch_init(int argc, char **argv)
{
	int result = EXIT_SUCCESS;
	sinsp* inspector = NULL;
	digwatch_rules* rules = NULL;
	int op;
	sinsp_evt::param_fmt event_buffer_format = sinsp_evt::PF_NORMAL;
	int long_index = 0;
	string lua_main_filename;
	string output_name = "stdout";
	string scap_filename;
	string conf_filename;
	string lua_dir = DIGWATCH_LUA_DIR;
	lua_State* ls = NULL;

	static struct option long_options[] =
	{
		{"help", no_argument, 0, 'h' },
		{"readfile", required_argument, 0, 'r' },
		{0, 0, 0, 0}
	};

	try
	{
		inspector = new sinsp();
		bool valid;

		//
		// Parse the args
		//
		while((op = getopt_long(argc, argv,
                                        "c:ho:r:u:",
                                        long_options, &long_index)) != -1)
		{
			switch(op)
			{
			case 'h':
				usage();
				goto exit;
			case 'c':
				conf_filename = optarg;
				break;
			case 'o':
				valid = std::find(valid_output_names.begin(), valid_output_names.end(), optarg) != valid_output_names.end();
				if (!valid)
				{
					throw sinsp_exception(string("Invalid output name ") + optarg);
				}
				output_name = optarg;
				break;
			case 'r':
				scap_filename = optarg;
				break;
			case '?':
				result = EXIT_FAILURE;
				goto exit;
			default:
				break;
			}

		}

		inspector->set_buffer_format(event_buffer_format);

		string rules_file;

		if(optind < argc)
		{
			for(int32_t j = optind ; j < argc; j++)
			{
				rules_file += argv[j];
				if(j < argc - 1)
				{
					rules_file += " ";
				}
			}

		}

		if(rules_file.size() == 0) {
			usage();
			result = EXIT_FAILURE;
			goto exit;

		}

		ifstream* conf_stream;
		if (conf_filename.size())
		{
			conf_stream = new ifstream(conf_filename);
			if (!conf_stream->good())
			{
				fprintf(stderr, "Could not find configuration file at %s \n", conf_filename.c_str());
				result = EXIT_FAILURE;
				goto exit;
			}
		}
		else
		{
			conf_stream = new ifstream(DIGWATCH_SOURCE_CONF_FILE);
			if (conf_stream->good())
			{
				conf_filename = DIGWATCH_SOURCE_CONF_FILE;
			}
			else
			{
				conf_stream = new ifstream(DIGWATCH_INSTALL_CONF_FILE);
				if (conf_stream->good())
				{
					conf_filename = DIGWATCH_INSTALL_CONF_FILE;
				}
				else
				{
					conf_filename = "";
				}
			}
		}

		digwatch_configuration config;
		if (conf_filename.size())
		{
			cout << "Using configuration file " + conf_filename + "\n";
			config.init(conf_filename);
		}
		else
		{
			cout << "No configuration file found, proceeding with defaults\n";
			config.init();
		}

		if(signal(SIGINT, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGINT signal handler.\n");
			result = EXIT_FAILURE;
			goto exit;
		}

		if(signal(SIGTERM, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGTERM signal handler.\n");
			result = EXIT_FAILURE;
			goto exit;
		}

		lua_main_filename = lua_dir + DIGWATCH_LUA_MAIN;
		if (!std::ifstream(lua_main_filename))
		{
			lua_dir = DIGWATCH_SOURCE_LUA_DIR;
			lua_main_filename = lua_dir + DIGWATCH_LUA_MAIN;
			if (!std::ifstream(lua_main_filename))
			{
				fprintf(stderr, "Could not find Digwatch Lua libraries (tried %s, %s). \n",
					DIGWATCH_LUA_DIR DIGWATCH_LUA_MAIN,
					lua_main_filename.c_str());
				result = EXIT_FAILURE;
				goto exit;
			}
		}

		// Initialize Lua interpreter
		ls = lua_open();
		luaL_openlibs(ls);
		luaopen_lpeg(ls);
		add_lua_path(ls, lua_dir);

		rules = new digwatch_rules(inspector, ls, lua_main_filename);

		digwatch_formats::init(inspector, ls);
		digwatch_fields::init(inspector, ls);

		digwatch_syslog::init(ls);

		rules->load_rules(config.m_rules_filename);
		inspector->set_filter(rules->get_filter());

		inspector->set_hostname_and_port_resolution_mode(false);

		for(std::vector<output_config>::iterator it = config.m_outputs.begin(); it != config.m_outputs.end(); ++it)
		{
			add_output(ls, *it);
		}

		if (scap_filename.size())
		{
			inspector->open(scap_filename);
		}
		else
		{
			try
			{
				inspector->open();
			}
			catch(sinsp_exception e)
			{
				if(system("modprobe " PROBE_NAME " > /dev/null 2> /dev/null"))
				{
					fprintf(stderr, "Unable to load the driver\n");
				}
				inspector->open();
			}
		}
		do_inspect(inspector,
			   rules,
			   ls);

		inspector->close();
	}
	catch(sinsp_exception& e)
	{
		cerr << e.what() << endl;
		result = EXIT_FAILURE;
	}
	catch(...)
	{
		printf("Error, exiting.\n");
		result = EXIT_FAILURE;
	}

exit:

	if(inspector)
	{
		delete inspector;
	}

	if(ls)
	{
		lua_close(ls);
	}
	return result;
}

//
// MAIN
//
int main(int argc, char **argv)
{
	return digwatch_init(argc, argv);
}
<commit_msg>Change rules file command-line setting<commit_after>#define __STDC_FORMAT_MACROS

#include <stdio.h>
#include <iostream>
#include <signal.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <algorithm>
#include <unistd.h>
#include <getopt.h>

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "lpeg.h"
}

#include <sinsp.h>
#include "config_digwatch.h"
#include "configuration.h"
#include "rules.h"
#include "formats.h"
#include "fields.h"
#include "syslog.h"
#include "utils.h"
#include <yaml-cpp/yaml.h>

static bool g_terminate = false;

static void signal_callback(int signal)
{
	g_terminate = true;
}

std::vector<string> valid_output_names {"stdout", "syslog"};

//
// Program help
//
static void usage()
{
    printf(
	   "Usage: digwatch [options] rules_filename\n\n"
	   "Options:\n"
	   " -h, --help         Print this page\n"
	   " -o                 Output type (options are 'stdout', 'syslog', default is 'stdout')\n"
           " -r <readfile>, --read=<readfile>\n"
           "                    Read the events from <readfile>.\n"
	   "\n"
    );
}

string lua_on_event = "on_event";
string lua_add_output = "add_output";

//
// Event processing loop
//
void do_inspect(sinsp* inspector,
		digwatch_rules* rules,
		lua_State* ls)
{
	int32_t res;
	sinsp_evt* ev;
	string line;

	//
	// Loop through the events
	//
	while(1)
	{

		if(g_terminate)
		{
			break;
		}

		res = inspector->next(&ev);

		if(res == SCAP_TIMEOUT)
		{
			continue;
		}
		else if(res == SCAP_EOF)
		{
			break;
		}
		else if(res != SCAP_SUCCESS)
		{
			//
			// Event read error.
			// Notify the chisels that we're exiting, and then die with an error.
			//
			cerr << "res = " << res << endl;
			throw sinsp_exception(inspector->getlasterr().c_str());
		}

		if(!inspector->is_debug_enabled() &&
			ev->get_category() & EC_INTERNAL)
		{
			continue;
		}

		lua_getglobal(ls, lua_on_event.c_str());

		if(lua_isfunction(ls, -1))
		{
			lua_pushlightuserdata(ls, ev);
			lua_pushnumber(ls, ev->get_check_id());

			if(lua_pcall(ls, 2, 0, 0) != 0)
			{
				const char* lerr = lua_tostring(ls, -1);
				string err = "Error invoking function output: " + string(lerr);
				throw sinsp_exception(err);
			}
		}
		else
		{
			throw sinsp_exception("No function " + lua_on_event + " found in lua compiler module");
		}
	}
}

void add_lua_path(lua_State *ls, string path)
{
	string cpath = string(path);
	path += "?.lua";
	cpath += "?.so";

	lua_getglobal(ls, "package");

	lua_getfield(ls, -1, "path");
	string cur_path = lua_tostring(ls, -1 );
	cur_path += ';';
	lua_pop(ls, 1);

	cur_path.append(path.c_str());

	lua_pushstring(ls, cur_path.c_str());
	lua_setfield(ls, -2, "path");

	lua_getfield(ls, -1, "cpath");
	string cur_cpath = lua_tostring(ls, -1 );
	cur_cpath += ';';
	lua_pop(ls, 1);

	cur_cpath.append(cpath.c_str());

	lua_pushstring(ls, cur_cpath.c_str());
	lua_setfield(ls, -2, "cpath");

	lua_pop(ls, 1);
}

void add_output(lua_State *ls, output_config oc)
{

	uint8_t nargs = 1;
	lua_getglobal(ls, lua_add_output.c_str());

	if(!lua_isfunction(ls, -1))
	{
		throw sinsp_exception("No function " + lua_add_output + " found. ");
	}
	lua_pushstring(ls, oc.name.c_str());

	// If we have options, build up a lua table containing them
	if (oc.options.size())
	{
		nargs = 2;
		lua_createtable(ls, 0, oc.options.size());

		for (auto it = oc.options.cbegin(); it != oc.options.cend(); ++it)
		{
			lua_pushstring(ls, (*it).second.c_str());
			lua_setfield(ls, -2, (*it).first.c_str());
		}
	}

	if(lua_pcall(ls, nargs, 0, 0) != 0)
	{
		const char* lerr = lua_tostring(ls, -1);
		throw sinsp_exception(string(lerr));
	}

}

//
// ARGUMENT PARSING AND PROGRAM SETUP
//
int digwatch_init(int argc, char **argv)
{
	int result = EXIT_SUCCESS;
	sinsp* inspector = NULL;
	digwatch_rules* rules = NULL;
	int op;
	sinsp_evt::param_fmt event_buffer_format = sinsp_evt::PF_NORMAL;
	int long_index = 0;
	string lua_main_filename;
	string output_name = "stdout";
	string scap_filename;
	string conf_filename;
	string rules_filename;
	string lua_dir = DIGWATCH_LUA_DIR;
	lua_State* ls = NULL;

	static struct option long_options[] =
	{
		{"help", no_argument, 0, 'h' },
		{"readfile", required_argument, 0, 'r' },
		{0, 0, 0, 0}
	};

	try
	{
		inspector = new sinsp();
		bool valid;

		//
		// Parse the args
		//
		while((op = getopt_long(argc, argv,
                                        "c:ho:r:u:",
                                        long_options, &long_index)) != -1)
		{
			switch(op)
			{
			case 'h':
				usage();
				goto exit;
			case 'c':
				conf_filename = optarg;
				break;
			case 'o':
				valid = std::find(valid_output_names.begin(), valid_output_names.end(), optarg) != valid_output_names.end();
				if (!valid)
				{
					throw sinsp_exception(string("Invalid output name ") + optarg);
				}
				output_name = optarg;
				break;
			case 'r':
				scap_filename = optarg;
				break;
			case 'u':
				rules_filename = optarg;
				break;
			case '?':
				result = EXIT_FAILURE;
				goto exit;
			default:
				break;
			}

		}

		inspector->set_buffer_format(event_buffer_format);

		ifstream* conf_stream;
		if (conf_filename.size())
		{
			conf_stream = new ifstream(conf_filename);
			if (!conf_stream->good())
			{
				fprintf(stderr, "Could not find configuration file at %s \n", conf_filename.c_str());
				result = EXIT_FAILURE;
				goto exit;
			}
		}
		else
		{
			conf_stream = new ifstream(DIGWATCH_SOURCE_CONF_FILE);
			if (conf_stream->good())
			{
				conf_filename = DIGWATCH_SOURCE_CONF_FILE;
			}
			else
			{
				conf_stream = new ifstream(DIGWATCH_INSTALL_CONF_FILE);
				if (conf_stream->good())
				{
					conf_filename = DIGWATCH_INSTALL_CONF_FILE;
				}
				else
				{
					conf_filename = "";
				}
			}
		}

		digwatch_configuration config;
		if (conf_filename.size())
		{
			cout << "Using configuration file " + conf_filename + "\n";
			config.init(conf_filename);
		}
		else
		{
			cout << "No configuration file found, proceeding with defaults\n";
			config.init();
		}

		if (rules_filename.size())
		{
			config.m_rules_filename = rules_filename;
		}
		cout << "Using rules file " + config.m_rules_filename + "\n";

		if(signal(SIGINT, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGINT signal handler.\n");
			result = EXIT_FAILURE;
			goto exit;
		}

		if(signal(SIGTERM, signal_callback) == SIG_ERR)
		{
			fprintf(stderr, "An error occurred while setting SIGTERM signal handler.\n");
			result = EXIT_FAILURE;
			goto exit;
		}

		lua_main_filename = lua_dir + DIGWATCH_LUA_MAIN;
		if (!std::ifstream(lua_main_filename))
		{
			lua_dir = DIGWATCH_SOURCE_LUA_DIR;
			lua_main_filename = lua_dir + DIGWATCH_LUA_MAIN;
			if (!std::ifstream(lua_main_filename))
			{
				fprintf(stderr, "Could not find Digwatch Lua libraries (tried %s, %s). \n",
					DIGWATCH_LUA_DIR DIGWATCH_LUA_MAIN,
					lua_main_filename.c_str());
				result = EXIT_FAILURE;
				goto exit;
			}
		}

		// Initialize Lua interpreter
		ls = lua_open();
		luaL_openlibs(ls);
		luaopen_lpeg(ls);
		add_lua_path(ls, lua_dir);

		rules = new digwatch_rules(inspector, ls, lua_main_filename);

		digwatch_formats::init(inspector, ls);
		digwatch_fields::init(inspector, ls);

		digwatch_syslog::init(ls);

		rules->load_rules(config.m_rules_filename);
		inspector->set_filter(rules->get_filter());

		inspector->set_hostname_and_port_resolution_mode(false);

		for(std::vector<output_config>::iterator it = config.m_outputs.begin(); it != config.m_outputs.end(); ++it)
		{
			add_output(ls, *it);
		}

		if (scap_filename.size())
		{
			inspector->open(scap_filename);
		}
		else
		{
			try
			{
				inspector->open();
			}
			catch(sinsp_exception e)
			{
				if(system("modprobe " PROBE_NAME " > /dev/null 2> /dev/null"))
				{
					fprintf(stderr, "Unable to load the driver\n");
				}
				inspector->open();
			}
		}
		do_inspect(inspector,
			   rules,
			   ls);

		inspector->close();
	}
	catch(sinsp_exception& e)
	{
		cerr << e.what() << endl;
		result = EXIT_FAILURE;
	}
	catch(...)
	{
		printf("Error, exiting.\n");
		result = EXIT_FAILURE;
	}

exit:

	if(inspector)
	{
		delete inspector;
	}

	if(ls)
	{
		lua_close(ls);
	}
	return result;
}

//
// MAIN
//
int main(int argc, char **argv)
{
	return digwatch_init(argc, argv);
}
<|endoftext|>


<commit_before>#include "util/probing_hash_table.hh"

#define BOOST_TEST_MODULE ProbingHashTableTest
#include <boost/test/unit_test.hpp>
#include <boost/scoped_array.hpp>
#include <boost/functional/hash.hpp>

#include <stdint.h>

namespace util {
namespace {

struct Entry {
  unsigned char key;
  typedef unsigned char Key;

  unsigned char GetKey() const {
    return key;
  }

  uint64_t GetValue() const {
    return value;
  }

  uint64_t value;
};

typedef ProbingHashTable<Entry, boost::hash<unsigned char> > Table;

BOOST_AUTO_TEST_CASE(simple) {
  boost::scoped_array<char> mem(new char[Table::Size(10, 1.2)]);

  Table table(mem.get(), Table::Size(10, 1.2));
  const Entry *i = NULL;
  BOOST_CHECK(!table.Find(2, i));
  Entry to_ins;
  to_ins.key = 3;
  to_ins.value = 328920;
  table.Insert(to_ins);
  BOOST_REQUIRE(table.Find(3, i));
  BOOST_CHECK_EQUAL(3, i->GetKey());
  BOOST_CHECK_EQUAL(static_cast<uint64_t>(328920), i->GetValue());
  BOOST_CHECK(!table.Find(2, i));
}

} // namespace
} // namespace util
<commit_msg>Zero-initialize newed memory in a test<commit_after>#include "util/probing_hash_table.hh"

#define BOOST_TEST_MODULE ProbingHashTableTest
#include <boost/test/unit_test.hpp>
#include <boost/scoped_array.hpp>
#include <boost/functional/hash.hpp>

#include <stdint.h>

namespace util {
namespace {

struct Entry {
  unsigned char key;
  typedef unsigned char Key;

  unsigned char GetKey() const {
    return key;
  }

  uint64_t GetValue() const {
    return value;
  }

  uint64_t value;
};

typedef ProbingHashTable<Entry, boost::hash<unsigned char> > Table;

BOOST_AUTO_TEST_CASE(simple) {
  size_t size = Table::Size(10, 1.2);
  boost::scoped_array<char> mem(new char[size]);
  memset(mem.get(), 0, size);

  Table table(mem.get(), size);
  const Entry *i = NULL;
  BOOST_CHECK(!table.Find(2, i));
  Entry to_ins;
  to_ins.key = 3;
  to_ins.value = 328920;
  table.Insert(to_ins);
  BOOST_REQUIRE(table.Find(3, i));
  BOOST_CHECK_EQUAL(3, i->GetKey());
  BOOST_CHECK_EQUAL(static_cast<uint64_t>(328920), i->GetValue());
  BOOST_CHECK(!table.Find(2, i));
}

} // namespace
} // namespace util
<|endoftext|>


<commit_before>/**
 * @file   Logger.cpp
 * @brief  Logger class implementation.
 * @author zer0
 * @date   2017-04-13
 * @date   2019-07-02 (Move namespace: log/mgr -> log)
 */

#include <libtbag/log/Logger.hpp>
#include <cassert>
#include <cstring>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace log {

Logger::Logger(std::string const & name,
               SharedSink const & sink,
               SharedGenerator const & generator,
               int level,
               bool auto_flush)
        : NAME(name), _sink(sink), _generator(generator), _level(level), _auto_flush(auto_flush)
{
    assert(static_cast<bool>(_sink));
}

Logger::~Logger()
{
    _sink->flush();
    _sink.reset();
    _generator.reset();
}

void Logger::flush() const
{
    assert(static_cast<bool>(_sink));
    _sink->flush();
}

bool Logger::write(int level, char const * level_name, char const * message, int size) const
{
    if (youShallNotPass(level)) {
        return true;
    }

    assert(static_cast<bool>(_sink));
    assert(level_name != nullptr);
    assert(message != nullptr);
    assert(size >= 1);

    char buffer[Generator::STACK_BUFFER_SIZE];
    int write_buffer_size;
    if (_generator) {
        write_buffer_size = _generator->make(buffer, Generator::STACK_BUFFER_SIZE, NAME.c_str(),
                                             level, level_name, message, size);
    } else {
        write_buffer_size = 0;
    }

    bool write_result;
    if (write_buffer_size >= 1) {
        write_result = _sink->write(level, buffer, write_buffer_size);
    } else {
        write_result = _sink->write(level, message, size);
    }

    if (_auto_flush) {
        _sink->flush();
    }

    return write_result;
}

bool Logger::write(int level, char const * level_name, char const * message) const
{
    return write(level, level_name, message, ::strlen(message));
}

bool Logger::write(int level, char const * level_name, std::string const & message) const
{
    return write(level, level_name, message.c_str(), static_cast<int>(message.size()));
}

bool Logger::write(int level, char const * message, int size) const
{
    return write(level, getTextWithLevelStep(level), message, size);
}

bool Logger::write(int level, char const * message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(int level, std::string const & message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(Severity const & severity, char const * message, int size) const
{
    return write(severity.getLevel(), severity.getText(), message, size);
}

bool Logger::write(Severity const & severity, char const * message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

bool Logger::write(Severity const & severity, std::string const & message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

} // namespace log

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

<commit_msg>Update Logger::write() method.<commit_after>/**
 * @file   Logger.cpp
 * @brief  Logger class implementation.
 * @author zer0
 * @date   2017-04-13
 * @date   2019-07-02 (Move namespace: log/mgr -> log)
 */

#include <libtbag/log/Logger.hpp>
#include <cassert>
#include <cstring>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

namespace log {

Logger::Logger(std::string const & name,
               SharedSink const & sink,
               SharedGenerator const & generator,
               int level,
               bool auto_flush)
        : NAME(name), _sink(sink), _generator(generator), _level(level), _auto_flush(auto_flush)
{
    assert(static_cast<bool>(_sink));
}

Logger::~Logger()
{
    _sink->flush();
    _sink.reset();
    _generator.reset();
}

void Logger::flush() const
{
    assert(static_cast<bool>(_sink));
    _sink->flush();
}

bool Logger::write(int level, char const * level_name, char const * message, int size) const
{
    if (youShallNotPass(level)) {
        return true;
    }
    if (_sink) {
        return false;
    }

    assert(level_name != nullptr);
    assert(message != nullptr);
    assert(size >= 1);

    char buffer[Generator::STACK_BUFFER_SIZE];
    int write_buffer_size;
    if (_generator) {
        write_buffer_size = _generator->make(buffer, Generator::STACK_BUFFER_SIZE, NAME.c_str(),
                                             level, level_name, message, size);
    } else {
        write_buffer_size = 0;
    }

    bool write_result;
    if (write_buffer_size >= 1) {
        write_result = _sink->write(level, buffer, write_buffer_size);
    } else {
        write_result = _sink->write(level, message, size);
    }

    if (_auto_flush) {
        _sink->flush();
    }

    return write_result;
}

bool Logger::write(int level, char const * level_name, char const * message) const
{
    return write(level, level_name, message, ::strlen(message));
}

bool Logger::write(int level, char const * level_name, std::string const & message) const
{
    return write(level, level_name, message.c_str(), static_cast<int>(message.size()));
}

bool Logger::write(int level, char const * message, int size) const
{
    return write(level, getTextWithLevelStep(level), message, size);
}

bool Logger::write(int level, char const * message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(int level, std::string const & message) const
{
    return write(level, getTextWithLevelStep(level), message);
}

bool Logger::write(Severity const & severity, char const * message, int size) const
{
    return write(severity.getLevel(), severity.getText(), message, size);
}

bool Logger::write(Severity const & severity, char const * message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

bool Logger::write(Severity const & severity, std::string const & message) const
{
    return write(severity.getLevel(), severity.getText(), message);
}

} // namespace log

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

<|endoftext|>


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

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

// The unittest header must be included before vaapidisplay.h.
// In vaapidisplay.h we include va_x11.h which includes Xlib.h and X.h.
// The X headers define 'Bool' and 'None' preprocessor types.  Gtest
// uses the same names to define some struct placeholders.  Thus, this
// creates a compile conflict if X defines them before gtest.  Hence, the
// include order requirement here is the only fix for this right now.
// See bug filed on gtest at https://github.com/google/googletest/issues/371
// for more details.
#include "common/unittest.h"

// primary header
#include "vaapidisplay.h"

// system headers
#include <fcntl.h>
#include <set>
#include <unistd.h>

namespace YamiMediaCodec {

class VaapiDisplayTest : public ::testing::Test {
    typedef std::set<intptr_t> DrmHandles;

protected:
    bool isCompatible(const DisplayPtr display, const NativeDisplay& native) {
        return display->isCompatible(native);
    }

    virtual void SetUp() {
#if defined(__ENABLE_X11__)
        m_x11_handle = 0;
#endif
    }

    intptr_t openDrmHandle() {
        intptr_t handle = -1;
        handle = open("/dev/dri/renderD128", O_RDWR);
        if (handle < 0)
            handle = open("/dev/dri/card0", O_RDWR);
        if (handle != -1)
            m_drm_handles.insert(handle);
        return handle;
    }

    void closeDrmHandle(intptr_t handle) {
        if (handle == -1)
            return;
        close(handle);
        const DrmHandles::const_iterator match(m_drm_handles.find(handle));
        if (match != m_drm_handles.end())
            m_drm_handles.erase(match);
    }

#if defined(__ENABLE_X11__)
    intptr_t openX11Handle() {
        m_x11_handle = (intptr_t)XOpenDisplay(NULL);
        return m_x11_handle;
    }
#endif

    virtual void TearDown() {
        const DrmHandles::const_iterator endIt(m_drm_handles.end());
        DrmHandles::const_iterator it;
        for (it = m_drm_handles.begin(); it != endIt; ++it)
            close(*it);
        m_drm_handles.clear();

#if defined(__ENABLE_X11__)
        if (m_x11_handle)
            XCloseDisplay((Display*)(m_x11_handle));
#endif
    }

    DrmHandles m_drm_handles;

#if defined(__ENABLE_X11__)
    intptr_t m_x11_handle;
#endif
};

#define VAAPI_DISPLAY_TEST(name) \
    TEST_F(VaapiDisplayTest, name)

#if defined(__ENABLE_X11__)
VAAPI_DISPLAY_TEST(CreateInvalidHandleX11) {
    //this turn off gest warning about multithread
    //you can check details at
    //https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
    ::testing::FLAGS_gtest_death_test_style = "threadsafe";

    NativeDisplay native = {1, NATIVE_DISPLAY_X11};
    //this will crash vaGetDisplay
    ASSERT_DEATH({ DisplayPtr display = VaapiDisplay::create(native); }, "");
}
#endif

VAAPI_DISPLAY_TEST(CreateInvalidHandleDRM) {
    NativeDisplay native = {1, NATIVE_DISPLAY_DRM};
    DisplayPtr display = VaapiDisplay::create(native);

    EXPECT_FALSE(display.get());

    intptr_t handle = openDrmHandle();

    ASSERT_NE(handle, -1);

    // DRM handle is invalidated once it's closed.
    closeDrmHandle(handle);

    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    display = VaapiDisplay::create(native);

    EXPECT_FALSE(display.get());
}

VAAPI_DISPLAY_TEST(CreateInvalidHandleVA) {
    NativeDisplay native = {0, NATIVE_DISPLAY_VA};
    DisplayPtr display = VaapiDisplay::create(native);

    EXPECT_FALSE(display.get());

    //this turn off gest warning about multithread
    //you can check details at
    //https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
    ::testing::FLAGS_gtest_death_test_style = "threadsafe";

    native.handle = -1;
    native.type = NATIVE_DISPLAY_VA;

    //This will crash in vaDisplayIsValid
    ASSERT_DEATH({ display = VaapiDisplay::create(native); }, "");
}

#if defined(__ENABLE_X11__)
VAAPI_DISPLAY_TEST(CreateX11) {
    // Let yami create the native display
    NativeDisplay native = {0, NATIVE_DISPLAY_X11};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Test the display caching
    DisplayPtr display2 = VaapiDisplay::create(native);

    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());

    // DRM native type returns cached X11 display
    // TODO: Is this really supposed to be allowed?
    native.handle = 0;
    native.type = NATIVE_DISPLAY_DRM;
    display2 = VaapiDisplay::create(native);
    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());

    // FIXME: If client created the DRM handle, it seems
    // that we should not get the cached X11 display, but we do.
    intptr_t handle = openDrmHandle();
    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    display2 = VaapiDisplay::create(native);
    ASSERT_NE(handle, -1);
    ASSERT_TRUE(display2.get());
    EXPECT_FALSE(display.get() == display2.get());
    EXPECT_NE(display->getID(), display2->getID());

    // Let client create the native display
    native.handle = openX11Handle();
    native.type = NATIVE_DISPLAY_X11;
    display = VaapiDisplay::create(native);

    ASSERT_NE(m_x11_handle, -1);
    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Ensure we didn't get the yami cached display
    EXPECT_FALSE(display.get() == display2.get());
    EXPECT_NE(display->getID(), display2->getID());
}
#endif

VAAPI_DISPLAY_TEST(CreateDRM) {
    // Let yami create the native display
    NativeDisplay native = {0, NATIVE_DISPLAY_DRM};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Test the display caching
    DisplayPtr display2 = VaapiDisplay::create(native);

    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());

    // Let client create the native display
    intptr_t handle = openDrmHandle();
    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    display = VaapiDisplay::create(native);

    ASSERT_NE(handle, -1);
    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Ensure we didn't get the yami cached display
    EXPECT_FALSE(display.get() == display2.get());
    EXPECT_NE(display->getID(), display2->getID());
}

VAAPI_DISPLAY_TEST(CreateVA) {
    NativeDisplay native = {1, NATIVE_DISPLAY_VA};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Test the display caching
    DisplayPtr display2 = VaapiDisplay::create(native);

    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());
}

#if defined(__ENABLE_X11__)
VAAPI_DISPLAY_TEST(CompatibleX11) {
    NativeDisplay native = {openX11Handle(), NATIVE_DISPLAY_X11};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE((Display*)m_x11_handle != NULL);
    ASSERT_TRUE(display.get());

    EXPECT_TRUE(isCompatible(display, native));

    native.handle = m_x11_handle + 1;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_TRUE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_TRUE(isCompatible(display, native));

    // FIXME: If client created the DRM handle, it seems
    // that we should not get the cached X11 display
    intptr_t handle = openDrmHandle();
    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    ASSERT_NE(handle, -1);
    ASSERT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_AUTO;
    EXPECT_TRUE(isCompatible(display, native));
}
#endif

VAAPI_DISPLAY_TEST(CompatibleDRM) {
    intptr_t handle = openDrmHandle();
    intptr_t handle2 = openDrmHandle();
    NativeDisplay native = {handle, NATIVE_DISPLAY_DRM};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_NE(handle, -1);
    ASSERT_NE(handle2, -1);
    ASSERT_NE(handle, handle2);
    ASSERT_TRUE(display.get());

    EXPECT_TRUE(isCompatible(display, native));

    native.handle = handle2;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_TRUE(isCompatible(display, native));

    native.handle = -1;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_TRUE(isCompatible(display, native));

    native.type = NATIVE_DISPLAY_AUTO;
    EXPECT_TRUE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_FALSE(isCompatible(display, native));
}

VAAPI_DISPLAY_TEST(CompatibleVA) {
    NativeDisplay native = {1, NATIVE_DISPLAY_VA};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());

    EXPECT_TRUE(isCompatible(display, native));

    native.handle = 2;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = -1;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 1;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 1;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_FALSE(isCompatible(display, native));

    native.type = NATIVE_DISPLAY_AUTO;
    EXPECT_TRUE(isCompatible(display, native));
}

} //namespace YamiMediaCodec
<commit_msg>unittest: vaapi, fix x11 display fail issue<commit_after>/*
 * Copyright 2016 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

// The unittest header must be included before vaapidisplay.h.
// In vaapidisplay.h we include va_x11.h which includes Xlib.h and X.h.
// The X headers define 'Bool' and 'None' preprocessor types.  Gtest
// uses the same names to define some struct placeholders.  Thus, this
// creates a compile conflict if X defines them before gtest.  Hence, the
// include order requirement here is the only fix for this right now.
// See bug filed on gtest at https://github.com/google/googletest/issues/371
// for more details.
#include "common/unittest.h"

// primary header
#include "vaapidisplay.h"

// system headers
#include <fcntl.h>
#include <set>
#include <unistd.h>

namespace YamiMediaCodec {

class VaapiDisplayTest : public ::testing::Test {
    typedef std::set<intptr_t> DrmHandles;

protected:
    bool isCompatible(const DisplayPtr display, const NativeDisplay& native) {
        return display->isCompatible(native);
    }

    virtual void SetUp() {
#if defined(__ENABLE_X11__)
        m_x11_handle = 0;
#endif
    }

    intptr_t openDrmHandle() {
        intptr_t handle = -1;
        handle = open("/dev/dri/renderD128", O_RDWR);
        if (handle < 0)
            handle = open("/dev/dri/card0", O_RDWR);
        if (handle != -1)
            m_drm_handles.insert(handle);
        return handle;
    }

    void closeDrmHandle(intptr_t handle) {
        if (handle == -1)
            return;
        close(handle);
        const DrmHandles::const_iterator match(m_drm_handles.find(handle));
        if (match != m_drm_handles.end())
            m_drm_handles.erase(match);
    }

#if defined(__ENABLE_X11__)
    intptr_t openX11Handle() {
        m_x11_handle = (intptr_t)XOpenDisplay(NULL);
        return m_x11_handle;
    }
#endif

    virtual void TearDown() {
        const DrmHandles::const_iterator endIt(m_drm_handles.end());
        DrmHandles::const_iterator it;
        for (it = m_drm_handles.begin(); it != endIt; ++it)
            close(*it);
        m_drm_handles.clear();

#if defined(__ENABLE_X11__)
        if (m_x11_handle)
            XCloseDisplay((Display*)(m_x11_handle));
#endif
    }

    DrmHandles m_drm_handles;

#if defined(__ENABLE_X11__)
    intptr_t m_x11_handle;
#endif
};

#if defined(__ENABLE_X11__)
bool haveX11Display()
{
    Display* display = XOpenDisplay(NULL);
    if (display) {
        XCloseDisplay(display);
        return true;
    }
    return false;
}
#endif

const std::string getFullTestName()
{
    const ::testing::TestInfo* const info = ::testing::UnitTest::GetInstance()->current_test_info();
    return std::string(info->test_case_name())
        + std::string(".")
        + std::string(info->name());
}

#define VAAPI_DISPLAY_TEST(name) \
    TEST_F(VaapiDisplayTest, name)

#if defined(__ENABLE_X11__)
VAAPI_DISPLAY_TEST(CreateInvalidHandleX11) {
    //this turn off gest warning about multithread
    //you can check details at
    //https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
    ::testing::FLAGS_gtest_death_test_style = "threadsafe";

    NativeDisplay native = {1, NATIVE_DISPLAY_X11};
    //this will crash vaGetDisplay
    ASSERT_DEATH({ DisplayPtr display = VaapiDisplay::create(native); }, "");
}
#endif

VAAPI_DISPLAY_TEST(CreateInvalidHandleDRM) {
    NativeDisplay native = {1, NATIVE_DISPLAY_DRM};
    DisplayPtr display = VaapiDisplay::create(native);

    EXPECT_FALSE(display.get());

    intptr_t handle = openDrmHandle();

    ASSERT_NE(handle, -1);

    // DRM handle is invalidated once it's closed.
    closeDrmHandle(handle);

    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    display = VaapiDisplay::create(native);

    EXPECT_FALSE(display.get());
}

VAAPI_DISPLAY_TEST(CreateInvalidHandleVA) {
    NativeDisplay native = {0, NATIVE_DISPLAY_VA};
    DisplayPtr display = VaapiDisplay::create(native);

    EXPECT_FALSE(display.get());

    //this turn off gest warning about multithread
    //you can check details at
    //https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
    ::testing::FLAGS_gtest_death_test_style = "threadsafe";

    native.handle = -1;
    native.type = NATIVE_DISPLAY_VA;

    //This will crash in vaDisplayIsValid
    ASSERT_DEATH({ display = VaapiDisplay::create(native); }, "");
}

#if defined(__ENABLE_X11__)
VAAPI_DISPLAY_TEST(CreateX11) {

    if (!haveX11Display()) {
        RecordProperty("skipped", true);
        std::cout << "[  SKIPPED ] " << getFullTestName()
                  << " We can't test this in terminal, we need a X11 window for this" << std::endl;
        return;
    }

    // Let yami create the native display
    NativeDisplay native = {0, NATIVE_DISPLAY_X11};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Test the display caching
    DisplayPtr display2 = VaapiDisplay::create(native);

    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());

    // DRM native type returns cached X11 display
    // TODO: Is this really supposed to be allowed?
    native.handle = 0;
    native.type = NATIVE_DISPLAY_DRM;
    display2 = VaapiDisplay::create(native);
    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());

    // FIXME: If client created the DRM handle, it seems
    // that we should not get the cached X11 display, but we do.
    intptr_t handle = openDrmHandle();
    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    display2 = VaapiDisplay::create(native);
    ASSERT_NE(handle, -1);
    ASSERT_TRUE(display2.get());
    EXPECT_FALSE(display.get() == display2.get());
    EXPECT_NE(display->getID(), display2->getID());

    // Let client create the native display
    native.handle = openX11Handle();
    native.type = NATIVE_DISPLAY_X11;
    display = VaapiDisplay::create(native);

    ASSERT_NE(m_x11_handle, -1);
    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Ensure we didn't get the yami cached display
    EXPECT_FALSE(display.get() == display2.get());
    EXPECT_NE(display->getID(), display2->getID());
}
#endif

VAAPI_DISPLAY_TEST(CreateDRM) {
    // Let yami create the native display
    NativeDisplay native = {0, NATIVE_DISPLAY_DRM};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Test the display caching
    DisplayPtr display2 = VaapiDisplay::create(native);

    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());

    // Let client create the native display
    intptr_t handle = openDrmHandle();
    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    display = VaapiDisplay::create(native);

    ASSERT_NE(handle, -1);
    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Ensure we didn't get the yami cached display
    EXPECT_FALSE(display.get() == display2.get());
    EXPECT_NE(display->getID(), display2->getID());
}

VAAPI_DISPLAY_TEST(CreateVA) {
    NativeDisplay native = {1, NATIVE_DISPLAY_VA};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());
    EXPECT_TRUE(display->getID() > 0);

    // Test the display caching
    DisplayPtr display2 = VaapiDisplay::create(native);

    ASSERT_TRUE(display2.get());
    EXPECT_TRUE(display.get() == display2.get());
    EXPECT_EQ(display->getID(), display2->getID());
}

#if defined(__ENABLE_X11__)
VAAPI_DISPLAY_TEST(CompatibleX11) {

    if (!haveX11Display()) {
        RecordProperty("skipped", true);
        std::cout << "[  SKIPPED ] " << getFullTestName()
                  << " We can't test this in terminal, we need a X11 window for this" << std::endl;
        return;
    }

    NativeDisplay native = {openX11Handle(), NATIVE_DISPLAY_X11};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE((Display*)m_x11_handle != NULL);
    ASSERT_TRUE(display.get());

    EXPECT_TRUE(isCompatible(display, native));

    native.handle = m_x11_handle + 1;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_TRUE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_TRUE(isCompatible(display, native));

    // FIXME: If client created the DRM handle, it seems
    // that we should not get the cached X11 display
    intptr_t handle = openDrmHandle();
    native.handle = handle;
    native.type = NATIVE_DISPLAY_DRM;
    ASSERT_NE(handle, -1);
    ASSERT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_AUTO;
    EXPECT_TRUE(isCompatible(display, native));
}
#endif

VAAPI_DISPLAY_TEST(CompatibleDRM) {
    intptr_t handle = openDrmHandle();
    intptr_t handle2 = openDrmHandle();
    NativeDisplay native = {handle, NATIVE_DISPLAY_DRM};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_NE(handle, -1);
    ASSERT_NE(handle2, -1);
    ASSERT_NE(handle, handle2);
    ASSERT_TRUE(display.get());

    EXPECT_TRUE(isCompatible(display, native));

    native.handle = handle2;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_TRUE(isCompatible(display, native));

    native.handle = -1;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_TRUE(isCompatible(display, native));

    native.type = NATIVE_DISPLAY_AUTO;
    EXPECT_TRUE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_FALSE(isCompatible(display, native));
}

VAAPI_DISPLAY_TEST(CompatibleVA) {
    NativeDisplay native = {1, NATIVE_DISPLAY_VA};
    DisplayPtr display = VaapiDisplay::create(native);

    ASSERT_TRUE(display.get());

    EXPECT_TRUE(isCompatible(display, native));

    native.handle = 2;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 0;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = -1;
    native.type = NATIVE_DISPLAY_VA;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 1;
    native.type = NATIVE_DISPLAY_DRM;
    EXPECT_FALSE(isCompatible(display, native));

    native.handle = 1;
    native.type = NATIVE_DISPLAY_X11;
    EXPECT_FALSE(isCompatible(display, native));

    native.type = NATIVE_DISPLAY_AUTO;
    EXPECT_TRUE(isCompatible(display, native));
}

} //namespace YamiMediaCodec
<|endoftext|>


<commit_before>#include "CoreSuite.h"
#include "TestAssertTest.h"
#include <algorithm>

/*
 Note:
 - tests need to be added to test asserEquals() template function and
 use of assertion traits. Some check may need to be added to check
 the message content in Exception.
 - code need to be refactored with the use of a test caller that expect
 an exception.
 */

CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( TestAssertTest,
                                       coreSuiteName() );

TestAssertTest::TestAssertTest()
{
}

TestAssertTest::~TestAssertTest()
{
}

void
TestAssertTest::setUp()
{
}

void
TestAssertTest::tearDown()
{
}

void
TestAssertTest::testAssertThrow()
{
   CPPUNIT_ASSERT_THROW( throw std::string(), std::string );

   try
   {
      int x;
      CPPUNIT_ASSERT_THROW( x = 1234, std::string );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }

   throw std::exception();
}

void
TestAssertTest::testAssertNoThrow()
{
   int x;
   CPPUNIT_ASSERT_NO_THROW( x = 1234 );

   try
   {
      CPPUNIT_ASSERT_NO_THROW( throw std::exception() );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }
   throw std::exception();
}

void
TestAssertTest::testAssertAssertionFail()
{
   CPPUNIT_ASSERT_ASSERTION_FAIL( throw CPPUNIT_NS::Exception() );

   try
   {
      int x;
      CPPUNIT_ASSERT_ASSERTION_FAIL( x = 1234 );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }

   throw std::exception();
}

void
TestAssertTest::testAssertAssertionPass()
{
   int x;
   CPPUNIT_ASSERT_ASSERTION_PASS( x = 1234 );

   try
   {
      CPPUNIT_ASSERT_ASSERTION_PASS( throw CPPUNIT_NS::Exception() );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }

   throw std::exception();
}

void
TestAssertTest::testAssert()
{
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT( true ) );

  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT( false ) );
}

static int foo() { return 1; }

void
TestAssertTest::testAssertEqual()
{
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_EQUAL( 1, 1 ) );
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_EQUAL( 1, foo() ) );
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_EQUAL( 12345678, 12345678 ) );

  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_EQUAL( 1, 2 ) );
}

void
TestAssertTest::testAssertMessageTrue()
{
  CPPUNIT_ASSERT_ASSERTION_PASS(
     CPPUNIT_ASSERT_MESSAGE( "This test should not failed", true ) );
}

void
TestAssertTest::testAssertMessageFalse()
{
  bool exceptionCaught = false;
  std::string message( "This test message should not be seen" );
  try
  {
    CPPUNIT_ASSERT_MESSAGE( message, 2==3 );
  }
  catch( CPPUNIT_NS::Exception &e )
  {
    exceptionCaught = true; // ok, we were expecting an exception.
    checkMessageContains( &e, message );
  }

  CPPUNIT_ASSERT( exceptionCaught );
}

void
TestAssertTest::testAssertDoubleEquals()
{
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.1, 1.2, 0.101 ) );
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.2, 1.1, 0.101 ) );

  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.1, 1.2, 0.09 ) );
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.2, 1.1, 0.09 ) );
}

void
TestAssertTest::testFail()
{
  bool exceptionCaught = false;
  std::string failure( "FailureMessage" );
  try
  {
    CPPUNIT_FAIL( failure );
  }
  catch( CPPUNIT_NS::Exception &e )
  {
    exceptionCaught = true;
    checkMessageContains( &e, failure );
  }
  CPPUNIT_ASSERT( exceptionCaught );
}

void
TestAssertTest::checkMessageContains( CPPUNIT_NS::Exception *e,
                                      std::string expected )
{
  std::string actual = e->what();
  CPPUNIT_ASSERT_MESSAGE( "Expected message not found: " + expected +
                          ", was: " + actual,
      std::search( actual.begin(), actual.end(),
                   expected.begin(), expected.end() ) != actual.end() );
}
<commit_msg>Add unit tests for CPPUNIT_ASSERT_DOUBLES_EQUAL() that test with non-finite values.<commit_after>#include "CoreSuite.h"
#include "TestAssertTest.h"
#include <algorithm>

/*
 Note:
 - tests need to be added to test asserEquals() template function and
 use of assertion traits. Some check may need to be added to check
 the message content in Exception.
 - code need to be refactored with the use of a test caller that expect
 an exception.
 */

CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( TestAssertTest,
                                       coreSuiteName() );

TestAssertTest::TestAssertTest()
{
}

TestAssertTest::~TestAssertTest()
{
}

void
TestAssertTest::setUp()
{
}

void
TestAssertTest::tearDown()
{
}

void
TestAssertTest::testAssertThrow()
{
   CPPUNIT_ASSERT_THROW( throw std::string(), std::string );

   try
   {
      int x;
      CPPUNIT_ASSERT_THROW( x = 1234, std::string );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }

   throw std::exception();
}

void
TestAssertTest::testAssertNoThrow()
{
   int x;
   CPPUNIT_ASSERT_NO_THROW( x = 1234 );

   try
   {
      CPPUNIT_ASSERT_NO_THROW( throw std::exception() );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }
   throw std::exception();
}

void
TestAssertTest::testAssertAssertionFail()
{
   CPPUNIT_ASSERT_ASSERTION_FAIL( throw CPPUNIT_NS::Exception() );

   try
   {
      int x;
      CPPUNIT_ASSERT_ASSERTION_FAIL( x = 1234 );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }

   throw std::exception();
}

void
TestAssertTest::testAssertAssertionPass()
{
   int x;
   CPPUNIT_ASSERT_ASSERTION_PASS( x = 1234 );

   try
   {
      CPPUNIT_ASSERT_ASSERTION_PASS( throw CPPUNIT_NS::Exception() );
   }
   catch ( CPPUNIT_NS::Exception & )
   {
      return;
   }

   throw std::exception();
}

void
TestAssertTest::testAssert()
{
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT( true ) );

  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT( false ) );
}

static int foo() { return 1; }

void
TestAssertTest::testAssertEqual()
{
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_EQUAL( 1, 1 ) );
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_EQUAL( 1, foo() ) );
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_EQUAL( 12345678, 12345678 ) );

  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_EQUAL( 1, 2 ) );
}

void
TestAssertTest::testAssertMessageTrue()
{
  CPPUNIT_ASSERT_ASSERTION_PASS(
     CPPUNIT_ASSERT_MESSAGE( "This test should not failed", true ) );
}

void
TestAssertTest::testAssertMessageFalse()
{
  bool exceptionCaught = false;
  std::string message( "This test message should not be seen" );
  try
  {
    CPPUNIT_ASSERT_MESSAGE( message, 2==3 );
  }
  catch( CPPUNIT_NS::Exception &e )
  {
    exceptionCaught = true; // ok, we were expecting an exception.
    checkMessageContains( &e, message );
  }

  CPPUNIT_ASSERT( exceptionCaught );
}

void
TestAssertTest::testAssertDoubleEquals()
{
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.1, 1.2, 0.101 ) );
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.2, 1.1, 0.101 ) );

  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.1, 1.2, 0.09 ) );
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( 1.2, 1.1, 0.09 ) );

  double inf = std::numeric_limits<double>::infinity();
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( inf, 0.0, 1.0 ) );
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( 0.0, inf, 1.0 ) );
  CPPUNIT_ASSERT_ASSERTION_PASS( CPPUNIT_ASSERT_DOUBLES_EQUAL( inf, inf, 1.0 ) );

  double nan = std::numeric_limits<double>::quiet_NaN();
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( nan, 0.0, 1.0 ) );
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( nan, nan, 1.0 ) );
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( nan, inf, 1.0 ) );
  CPPUNIT_ASSERT_ASSERTION_FAIL( CPPUNIT_ASSERT_DOUBLES_EQUAL( inf, nan, 1.0 ) );
}

void
TestAssertTest::testFail()
{
  bool exceptionCaught = false;
  std::string failure( "FailureMessage" );
  try
  {
    CPPUNIT_FAIL( failure );
  }
  catch( CPPUNIT_NS::Exception &e )
  {
    exceptionCaught = true;
    checkMessageContains( &e, failure );
  }
  CPPUNIT_ASSERT( exceptionCaught );
}

void
TestAssertTest::checkMessageContains( CPPUNIT_NS::Exception *e,
                                      std::string expected )
{
  std::string actual = e->what();
  CPPUNIT_ASSERT_MESSAGE( "Expected message not found: " + expected +
                          ", was: " + actual,
      std::search( actual.begin(), actual.end(),
                   expected.begin(), expected.end() ) != actual.end() );
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH
#define DUNE_GDT_MAPPER_DEFAULT_FV_HH

#include <type_traits>

#include <dune/common/dynvector.hh>
#include <dune/common/typetraits.hh>

#include <dune/stuff/common/debug.hh>

#include "../../mapper/interface.hh"

namespace Dune {
namespace GDT {
namespace Mapper {

// forward
template< class GridViewImp, int rangeDim = 1, int rangeDimCols = 1 >
class FiniteVolume
{
  static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!");
};

namespace internal {

template< class GridViewImp, int rangeDim, int rangeDimCols >
class FiniteVolumeTraits
{
  static_assert(rangeDim >= 1, "Really?");
  static_assert(rangeDimCols >= 1, "Really?");
public:
  typedef GridViewImp GridViewType;
  typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type;
  typedef typename GridViewImp::IndexSet BackendType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
};

} // namespace internal

template< class GridViewImp >
class FiniteVolume< GridViewImp, 1, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, 1, 1 > Traits;
  typedef typename Traits::GridViewType                     GridViewType;
  typedef typename Traits::BackendType                      BackendType;
  typedef typename Traits::EntityType                       EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return 1;
  }

  size_t maxNumDofs() const
  {
    return 1;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < 1)
      ret.resize(1);
    ret[0] = mapToGlobal(entity, 0);
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
  {
    assert(localIndex == 0);
    return backend_.index(entity);
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >

template< class GridViewImp, int rangeDim >
class FiniteVolume< GridViewImp, rangeDim, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType;
  static const unsigned int dimRange = rangeDim;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits;
  typedef typename Traits::GridViewType                            GridViewType;
  typedef typename Traits::BackendType                             BackendType;
  typedef typename Traits::EntityType                              EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return dimRange * backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return dimRange;
  }

  size_t maxNumDofs() const
  {
    return dimRange;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < dimRange)
      ret.resize(dimRange);
    const size_t base = dimRange * backend_.index(entity);
    for (size_t ii = 0; ii < dimRange; ++ii)
      ret[ii] = base + ii;
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    assert(localIndex < dimRange);
    return (dimRange * backend_.index(entity)) + localIndex;
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace Mapper
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
<commit_msg>[mapper.default.fv] update includes<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_MAPPER_DEFAULT_FV_HH
#define DUNE_GDT_MAPPER_DEFAULT_FV_HH

#include <type_traits>

#include <dune/common/dynvector.hh>

#include <dune/stuff/common/debug.hh>
#include <dune/stuff/common/type_utils.hh>

#include "../../mapper/interface.hh"

namespace Dune {
namespace GDT {
namespace Mapper {

// forward
template< class GridViewImp, int rangeDim = 1, int rangeDimCols = 1 >
class FiniteVolume
{
  static_assert(AlwaysFalse< GridViewImp >::value, "Not available for these dimensions!");
};

namespace internal {

template< class GridViewImp, int rangeDim, int rangeDimCols >
class FiniteVolumeTraits
{
  static_assert(rangeDim >= 1, "Really?");
  static_assert(rangeDimCols >= 1, "Really?");
public:
  typedef GridViewImp GridViewType;
  typedef FiniteVolume< GridViewType, rangeDim, rangeDimCols> derived_type;
  typedef typename GridViewImp::IndexSet BackendType;
  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
};

} // namespace internal

template< class GridViewImp >
class FiniteVolume< GridViewImp, 1, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, 1, 1 > > InterfaceType;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, 1, 1 > Traits;
  typedef typename Traits::GridViewType                     GridViewType;
  typedef typename Traits::BackendType                      BackendType;
  typedef typename Traits::EntityType                       EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return 1;
  }

  size_t maxNumDofs() const
  {
    return 1;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < 1)
      ret.resize(1);
    ret[0] = mapToGlobal(entity, 0);
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& UNUSED_UNLESS_DEBUG(localIndex)) const
  {
    assert(localIndex == 0);
    return backend_.index(entity);
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., 1, 1 >

template< class GridViewImp, int rangeDim >
class FiniteVolume< GridViewImp, rangeDim, 1 >
  : public MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > >
{
  typedef MapperInterface< internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > > InterfaceType;
  static const unsigned int dimRange = rangeDim;
public:
  typedef internal::FiniteVolumeTraits< GridViewImp, rangeDim, 1 > Traits;
  typedef typename Traits::GridViewType                            GridViewType;
  typedef typename Traits::BackendType                             BackendType;
  typedef typename Traits::EntityType                              EntityType;

  FiniteVolume(const GridViewType& grid_view)
    : backend_(grid_view.indexSet())
  {}

  const BackendType& backend() const
  {
    return backend_;
  }

  size_t size() const
  {
    return dimRange * backend_.size(0);
  }

  size_t numDofs(const EntityType& /*entity*/) const
  {
    return dimRange;
  }

  size_t maxNumDofs() const
  {
    return dimRange;
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector< size_t >& ret) const
  {
    if (ret.size() < dimRange)
      ret.resize(dimRange);
    const size_t base = dimRange * backend_.index(entity);
    for (size_t ii = 0; ii < dimRange; ++ii)
      ret[ii] = base + ii;
  } // ... globalIndices(...)

  using InterfaceType::globalIndices;

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    assert(localIndex < dimRange);
    return (dimRange * backend_.index(entity)) + localIndex;
  }

private:
  const BackendType& backend_;
}; // class FiniteVolume< ..., rangeDim, 1 >

} // namespace Mapper
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_MAPPER_DEFAULT_FV_HH
<|endoftext|>