<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: rscyacc.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:00:23 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_rsc.hxx"
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#include <tools/rc.h>

#ifndef _RSCERROR_H
#include <rscerror.h>
#endif

#ifndef _RSCTOOLS_HXX
#include <rsctools.hxx>
#endif
#ifndef _RSCCLASS_HXX
#include <rscclass.hxx>
#endif
#ifndef _RSCCONT_HXX
#include <rsccont.hxx>
#endif
#ifndef _RSCTREE_HXX
#include <rsctree.hxx>
#endif
#ifndef _RSCDB_HXX
#include <rscdb.hxx>
#endif
#ifndef _RSCDEF_HXX
#include <rscdef.hxx>
#endif
#ifndef _RSCPAR_HXX
#include <rscpar.hxx>
#endif

#include "rsclex.hxx"

/************** V a r i a b l e n ****************************************/
ObjectStack                     S;
RscTop *                        pCurClass;
sal_uInt32                      nCurMask;
char                            szErrBuf[ 100 ];

/************** H i l f s F u n k t i o n e n ****************************/
RSCINST GetVarInst( const RSCINST & rInst, const char * pVarName )
{
    RSCINST aInst;

    aInst = rInst.pClass->GetVariable( rInst, pHS->getID( pVarName ),
                                       RSCINST() );

    if( !aInst.pData )
        pTC->pEH->Error( ERR_NOVARIABLENAME, rInst.pClass, RscId() );

    return( aInst );
}

void SetNumber( const RSCINST & rInst, const char * pVarName, INT32 lValue )
{
    RSCINST aInst;

    aInst = GetVarInst( rInst, pVarName );

    if( aInst.pData ){
        ERRTYPE aError;
        aError = aInst.pClass->SetNumber( aInst, lValue );

        if( aError.IsError() )
            pTC->pEH->Error( aError, aInst.pClass, RscId() );
    }
}

void SetConst( const RSCINST & rInst, const char * pVarName,
               Atom nValueId, INT32 nVal )
{
    RSCINST aInst;

    aInst = GetVarInst( rInst, pVarName );
    if( aInst.pData )
    {
        ERRTYPE aError;
        aError = aInst.pClass->SetConst( aInst, nValueId, nVal );

        if( aError.IsError() )
            pTC->pEH->Error( aError, aInst.pClass, RscId() );
    }
}

void SetString( const RSCINST & rInst, const char * pVarName, const char * pStr )
{
    RSCINST aInst;

    aInst = GetVarInst( rInst, pVarName );
    if( aInst.pData ){
        ERRTYPE aError;
        aError = aInst.pClass->SetString( aInst, pStr );

        if( aError.IsError() )
            pTC->pEH->Error( aError, aInst.pClass, RscId() );
    }
}

RscId MakeRscId( RscExpType aExpType )
{
    if( !aExpType.IsNothing() ){
        INT32       lValue;

        if( !aExpType.Evaluate( &lValue ) )
            pTC->pEH->Error( ERR_ZERODIVISION, NULL, RscId() );
        if( lValue < 1 || lValue > (INT32)0x7FFF )
        {
            pTC->pEH->Error( ERR_IDRANGE, NULL, RscId(),
                             ByteString::CreateFromInt32( lValue ).GetBuffer() );
        }

        if( aExpType.IsDefinition() )
            return RscId( aExpType.aExp.pDef );
        else
            return RscId( lValue );
    }
    return RscId();
}

BOOL DoClassHeader( RSCHEADER * pHeader, BOOL bMember )
{
    RSCINST aCopyInst;
    RscId aName1 = MakeRscId( pHeader->nName1 );
    RscId aName2 = MakeRscId( pHeader->nName2 );

    if( pHeader->pRefClass )
        aCopyInst.pClass = pHeader->pRefClass;
    else
        aCopyInst.pClass = pHeader->pClass;

    if( TYPE_COPY == pHeader->nTyp )
    {
        ObjNode * pCopyObj = aCopyInst.pClass->GetObjNode( aName2 );

        if( !pCopyObj )
        {
            ByteString aMsg( pHS->getString( aCopyInst.pClass->GetId() ) );
            aMsg += ' ';
            aMsg += aName2.GetName();
            pTC->pEH->Error( ERR_NOCOPYOBJ, pHeader->pClass, aName1,
                             aMsg.GetBuffer() );
        }
        else
            aCopyInst.pData = pCopyObj->GetRscObj();
    }

    if( bMember )
    {
        // Angabe von Superklassen oder abgeleiteten Klassen ist jetzt erlaubt
        if( S.Top().pClass->InHierarchy( pHeader->pClass )
          ||  pHeader->pClass->InHierarchy( S.Top().pClass) )
        {
            if( aCopyInst.IsInst() )
            {
                RSCINST aTmpI( S.Top() );
                aTmpI.pClass->Destroy( aTmpI );
                aTmpI.pClass->Create( &aTmpI, aCopyInst );
            };
        }
        else
            pTC->pEH->Error( ERR_FALSETYPE, S.Top().pClass, aName1,
                             pHS->getString( pHeader->pClass->GetId() ) );
    }
    else
    {
        if( S.IsEmpty() )
        {
            if( (INT32)aName1 < 256 )
                pTC->pEH->Error( WRN_GLOBALID, pHeader->pClass, aName1 );

            if( aCopyInst.IsInst() )
                S.Push( pHeader->pClass->Create( NULL, aCopyInst ) );
            else
                S.Push( pHeader->pClass->Create( NULL, RSCINST() ) );

            ObjNode * pNode = new ObjNode( aName1, S.Top().pData,
                                           pFI->GetFileIndex() );
            pTC->pEH->StdOut( "." );

            if( !aName1.IsId() )
                pTC->pEH->Error( ERR_IDEXPECTED, pHeader->pClass, aName1 );
            else if( !pHeader->pClass->PutObjNode( pNode ) )
                pTC->pEH->Error( ERR_DOUBLEID, pHeader->pClass, aName1 );
        }
        else
        {
            RSCINST aTmpI;
            ERRTYPE aError;

            if( (INT32)aName1 >= 256 && aName1.IsId() )
                pTC->pEH->Error( WRN_LOCALID, pHeader->pClass, aName1 );
            aError = S.Top().pClass->GetElement( S.Top(), aName1,
                                                 pHeader->pClass, aCopyInst, &aTmpI );

            if( aError.IsWarning() )
                pTC->pEH->Error( aError, pHeader->pClass, aName1 );
            else if( aError.IsError() )
            {
                if( ERR_CONT_INVALIDTYPE == aError )
                    pTC->pEH->Error( aError, S.Top().pClass, aName1,
                                     pHS->getString( pHeader->pClass->GetId() ) );
                else
                    pTC->pEH->Error( aError, S.Top().pClass, aName1 );
                S.Top().pClass->GetElement( S.Top(), RscId(),
                                            pHeader->pClass, RSCINST(), &aTmpI );

                if( !aTmpI.IsInst() )
                    return( FALSE );
            }
            S.Push( aTmpI );
        };
    };
    if( TYPE_REF == pHeader->nTyp )
    {
        ERRTYPE aError;

        aError = S.Top().pClass->SetRef( S.Top(), aName2 );
        pTC->pEH->Error( aError, S.Top().pClass, aName1 );
    }

    return( TRUE );
}

RSCINST GetFirstTupelEle( const RSCINST & rTop )
{ // Aufwaertskompatible, Tupel probieren
    RSCINST aInst;
    ERRTYPE aErr;

    aErr = rTop.pClass->GetElement( rTop, RscId(), NULL, RSCINST(), &aInst );
    if( !aErr.IsError() )
        aInst = aInst.pClass->GetTupelVar( aInst, 0, RSCINST() );
    return aInst;
}

/************** Y a c c   C o d e ****************************************/
//#define YYDEBUG 1

#define TYPE_Atom             0
#define TYPE_RESID                1

#ifdef UNX
#define YYMAXDEPTH              2000
#else
#ifdef W30
#define YYMAXDEPTH              300
#else
#define YYMAXDEPTH              800
#endif
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable:4129 4273 4701)
#endif
#include "yyrscyacc.cxx"
#if defined _MSC_VER
#pragma warning(pop)
#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.9.54); FILE MERGED 2008/04/01 12:33:29 thb 1.9.54.2: #i85898# Stripping all external header guards 2008/03/31 13:15:58 rt 1.9.54.1: #i87441# Change license header to LPGL v3.<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: rscyacc.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_rsc.hxx"
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#include <tools/rc.h>
#include <rscerror.h>
#include <rsctools.hxx>
#include <rscclass.hxx>
#include <rsccont.hxx>
#include <rsctree.hxx>
#include <rscdb.hxx>
#include <rscdef.hxx>
#include <rscpar.hxx>

#include "rsclex.hxx"

/************** V a r i a b l e n ****************************************/
ObjectStack                     S;
RscTop *                        pCurClass;
sal_uInt32                      nCurMask;
char                            szErrBuf[ 100 ];

/************** H i l f s F u n k t i o n e n ****************************/
RSCINST GetVarInst( const RSCINST & rInst, const char * pVarName )
{
    RSCINST aInst;

    aInst = rInst.pClass->GetVariable( rInst, pHS->getID( pVarName ),
                                       RSCINST() );

    if( !aInst.pData )
        pTC->pEH->Error( ERR_NOVARIABLENAME, rInst.pClass, RscId() );

    return( aInst );
}

void SetNumber( const RSCINST & rInst, const char * pVarName, INT32 lValue )
{
    RSCINST aInst;

    aInst = GetVarInst( rInst, pVarName );

    if( aInst.pData ){
        ERRTYPE aError;
        aError = aInst.pClass->SetNumber( aInst, lValue );

        if( aError.IsError() )
            pTC->pEH->Error( aError, aInst.pClass, RscId() );
    }
}

void SetConst( const RSCINST & rInst, const char * pVarName,
               Atom nValueId, INT32 nVal )
{
    RSCINST aInst;

    aInst = GetVarInst( rInst, pVarName );
    if( aInst.pData )
    {
        ERRTYPE aError;
        aError = aInst.pClass->SetConst( aInst, nValueId, nVal );

        if( aError.IsError() )
            pTC->pEH->Error( aError, aInst.pClass, RscId() );
    }
}

void SetString( const RSCINST & rInst, const char * pVarName, const char * pStr )
{
    RSCINST aInst;

    aInst = GetVarInst( rInst, pVarName );
    if( aInst.pData ){
        ERRTYPE aError;
        aError = aInst.pClass->SetString( aInst, pStr );

        if( aError.IsError() )
            pTC->pEH->Error( aError, aInst.pClass, RscId() );
    }
}

RscId MakeRscId( RscExpType aExpType )
{
    if( !aExpType.IsNothing() ){
        INT32       lValue;

        if( !aExpType.Evaluate( &lValue ) )
            pTC->pEH->Error( ERR_ZERODIVISION, NULL, RscId() );
        if( lValue < 1 || lValue > (INT32)0x7FFF )
        {
            pTC->pEH->Error( ERR_IDRANGE, NULL, RscId(),
                             ByteString::CreateFromInt32( lValue ).GetBuffer() );
        }

        if( aExpType.IsDefinition() )
            return RscId( aExpType.aExp.pDef );
        else
            return RscId( lValue );
    }
    return RscId();
}

BOOL DoClassHeader( RSCHEADER * pHeader, BOOL bMember )
{
    RSCINST aCopyInst;
    RscId aName1 = MakeRscId( pHeader->nName1 );
    RscId aName2 = MakeRscId( pHeader->nName2 );

    if( pHeader->pRefClass )
        aCopyInst.pClass = pHeader->pRefClass;
    else
        aCopyInst.pClass = pHeader->pClass;

    if( TYPE_COPY == pHeader->nTyp )
    {
        ObjNode * pCopyObj = aCopyInst.pClass->GetObjNode( aName2 );

        if( !pCopyObj )
        {
            ByteString aMsg( pHS->getString( aCopyInst.pClass->GetId() ) );
            aMsg += ' ';
            aMsg += aName2.GetName();
            pTC->pEH->Error( ERR_NOCOPYOBJ, pHeader->pClass, aName1,
                             aMsg.GetBuffer() );
        }
        else
            aCopyInst.pData = pCopyObj->GetRscObj();
    }

    if( bMember )
    {
        // Angabe von Superklassen oder abgeleiteten Klassen ist jetzt erlaubt
        if( S.Top().pClass->InHierarchy( pHeader->pClass )
          ||  pHeader->pClass->InHierarchy( S.Top().pClass) )
        {
            if( aCopyInst.IsInst() )
            {
                RSCINST aTmpI( S.Top() );
                aTmpI.pClass->Destroy( aTmpI );
                aTmpI.pClass->Create( &aTmpI, aCopyInst );
            };
        }
        else
            pTC->pEH->Error( ERR_FALSETYPE, S.Top().pClass, aName1,
                             pHS->getString( pHeader->pClass->GetId() ) );
    }
    else
    {
        if( S.IsEmpty() )
        {
            if( (INT32)aName1 < 256 )
                pTC->pEH->Error( WRN_GLOBALID, pHeader->pClass, aName1 );

            if( aCopyInst.IsInst() )
                S.Push( pHeader->pClass->Create( NULL, aCopyInst ) );
            else
                S.Push( pHeader->pClass->Create( NULL, RSCINST() ) );

            ObjNode * pNode = new ObjNode( aName1, S.Top().pData,
                                           pFI->GetFileIndex() );
            pTC->pEH->StdOut( "." );

            if( !aName1.IsId() )
                pTC->pEH->Error( ERR_IDEXPECTED, pHeader->pClass, aName1 );
            else if( !pHeader->pClass->PutObjNode( pNode ) )
                pTC->pEH->Error( ERR_DOUBLEID, pHeader->pClass, aName1 );
        }
        else
        {
            RSCINST aTmpI;
            ERRTYPE aError;

            if( (INT32)aName1 >= 256 && aName1.IsId() )
                pTC->pEH->Error( WRN_LOCALID, pHeader->pClass, aName1 );
            aError = S.Top().pClass->GetElement( S.Top(), aName1,
                                                 pHeader->pClass, aCopyInst, &aTmpI );

            if( aError.IsWarning() )
                pTC->pEH->Error( aError, pHeader->pClass, aName1 );
            else if( aError.IsError() )
            {
                if( ERR_CONT_INVALIDTYPE == aError )
                    pTC->pEH->Error( aError, S.Top().pClass, aName1,
                                     pHS->getString( pHeader->pClass->GetId() ) );
                else
                    pTC->pEH->Error( aError, S.Top().pClass, aName1 );
                S.Top().pClass->GetElement( S.Top(), RscId(),
                                            pHeader->pClass, RSCINST(), &aTmpI );

                if( !aTmpI.IsInst() )
                    return( FALSE );
            }
            S.Push( aTmpI );
        };
    };
    if( TYPE_REF == pHeader->nTyp )
    {
        ERRTYPE aError;

        aError = S.Top().pClass->SetRef( S.Top(), aName2 );
        pTC->pEH->Error( aError, S.Top().pClass, aName1 );
    }

    return( TRUE );
}

RSCINST GetFirstTupelEle( const RSCINST & rTop )
{ // Aufwaertskompatible, Tupel probieren
    RSCINST aInst;
    ERRTYPE aErr;

    aErr = rTop.pClass->GetElement( rTop, RscId(), NULL, RSCINST(), &aInst );
    if( !aErr.IsError() )
        aInst = aInst.pClass->GetTupelVar( aInst, 0, RSCINST() );
    return aInst;
}

/************** Y a c c   C o d e ****************************************/
//#define YYDEBUG 1

#define TYPE_Atom             0
#define TYPE_RESID                1

#ifdef UNX
#define YYMAXDEPTH              2000
#else
#ifdef W30
#define YYMAXDEPTH              300
#else
#define YYMAXDEPTH              800
#endif
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#pragma warning(disable:4129 4273 4701)
#endif
#include "yyrscyacc.cxx"
#if defined _MSC_VER
#pragma warning(pop)
#endif

<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"

#define VERIFY_TRSM(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).solveInPlace(XB); \
    VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \
  }

#define VERIFY_TRSM_ONTHERIGHT(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).transpose().template solveInPlace<OnTheRight>(XB.transpose()); \
    VERIFY_IS_APPROX((XB).transpose() * (TRI).transpose().toDenseMatrix(), ref.transpose()); \
  }

template<typename Scalar,int Size, int Cols> void trsolve(int size=Size,int cols=Cols)
{
  typedef typename NumTraits<Scalar>::Real RealScalar;

  Matrix<Scalar,Size,Size,ColMajor> cmLhs(size,size);
  Matrix<Scalar,Size,Size,RowMajor> rmLhs(size,size);

  enum { order = Size==1 ? RowMajor : ColMajor };
  Matrix<Scalar,Size,Cols,order> cmRhs(size,cols), ref(size,cols);
  Matrix<Scalar,Size,Cols,order> rmRhs(size,cols);

  cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().array() += static_cast<RealScalar>(1);
  rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().array() += static_cast<RealScalar>(1);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);
}

void test_product_trsolve()
{
  for(int i = 0; i < g_repeat ; i++)
  {
    // matrices
    CALL_SUBTEST_1((trsolve<float,Dynamic,Dynamic>(ei_random<int>(1,320),ei_random<int>(1,320))));
    CALL_SUBTEST_2((trsolve<double,Dynamic,Dynamic>(ei_random<int>(1,320),ei_random<int>(1,320))));
    CALL_SUBTEST_3((trsolve<std::complex<float>,Dynamic,Dynamic>(ei_random<int>(1,200),ei_random<int>(1,200))));
    CALL_SUBTEST_4((trsolve<std::complex<double>,Dynamic,Dynamic>(ei_random<int>(1,200),ei_random<int>(1,200))));

    // vectors
    CALL_SUBTEST_5((trsolve<std::complex<double>,Dynamic,1>(ei_random<int>(1,320))));
    CALL_SUBTEST_6((trsolve<float,1,1>()));
    CALL_SUBTEST_7((trsolve<float,1,2>()));
    CALL_SUBTEST_8((trsolve<std::complex<float>,4,1>()));
  }
}
<commit_msg>it appears only the "on the left" case was tested<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"

#define VERIFY_TRSM(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).solveInPlace(XB); \
    VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \
  }

#define VERIFY_TRSM_ONTHERIGHT(TRI,XB) { \
    (XB).setRandom(); ref = (XB); \
    (TRI).transpose().template solveInPlace<OnTheRight>(XB.transpose()); \
    VERIFY_IS_APPROX((XB).transpose() * (TRI).transpose().toDenseMatrix(), ref.transpose()); \
  }

template<typename Scalar,int Size, int Cols> void trsolve(int size=Size,int cols=Cols)
{
  typedef typename NumTraits<Scalar>::Real RealScalar;

  Matrix<Scalar,Size,Size,ColMajor> cmLhs(size,size);
  Matrix<Scalar,Size,Size,RowMajor> rmLhs(size,size);

  enum { order = Size==1 ? RowMajor : ColMajor };
  Matrix<Scalar,Size,Cols,order> cmRhs(size,cols), ref(size,cols);
  Matrix<Scalar,Size,Cols,RowMajor> rmRhs(size,cols);

  cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().array() += static_cast<RealScalar>(1);
  rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().array() += static_cast<RealScalar>(1);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Upper>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<Lower>(), rmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Upper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(cmLhs            .template triangularView<UnitUpper>(), rmRhs);

  VERIFY_TRSM_ONTHERIGHT(rmLhs            .template triangularView<Lower>(), cmRhs);
  VERIFY_TRSM_ONTHERIGHT(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs);
}

void test_product_trsolve()
{
  for(int i = 0; i < g_repeat ; i++)
  {
    // matrices
    CALL_SUBTEST_1((trsolve<float,Dynamic,Dynamic>(ei_random<int>(1,320),ei_random<int>(1,320))));
    CALL_SUBTEST_2((trsolve<double,Dynamic,Dynamic>(ei_random<int>(1,320),ei_random<int>(1,320))));
    CALL_SUBTEST_3((trsolve<std::complex<float>,Dynamic,Dynamic>(ei_random<int>(1,200),ei_random<int>(1,200))));
    CALL_SUBTEST_4((trsolve<std::complex<double>,Dynamic,Dynamic>(ei_random<int>(1,200),ei_random<int>(1,200))));

    // vectors
    CALL_SUBTEST_5((trsolve<std::complex<double>,Dynamic,1>(ei_random<int>(1,320))));
    CALL_SUBTEST_6((trsolve<float,1,1>()));
    CALL_SUBTEST_7((trsolve<float,1,2>()));
    CALL_SUBTEST_8((trsolve<std::complex<float>,4,1>()));
  }
}
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TestEvent
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_array.hpp>
#include <boost/function.hpp>
#include <boost/any.hpp>
#include <cstring>
#include <iostream>

struct ConstCharArray
{
    const char* data;
    unsigned size;
    ConstCharArray(const char* data_, unsigned size_) : data(data_), size(size_) {}
};
typedef boost::shared_ptr<ConstCharArray> ConstCharArray_ptr;

struct MutableCharArray
{
    char* data;
    unsigned size;
    MutableCharArray(char* data_, unsigned size_) : data(data_), size(size_) {}
};
typedef boost::shared_ptr<MutableCharArray> MutableCharArray_ptr;

typedef boost::function<ConstCharArray_ptr (boost::any& data)> serialize_t;
typedef boost::function<boost::any (MutableCharArray_ptr serialized)> deserialize_t;

class Buffer;
typedef boost::shared_ptr<Buffer> Buffer_ptr;
class Buffer
{
    public:
        static Buffer_ptr make(boost::any anydata, serialize_t serializeFunc)
        {
            return boost::make_shared<Buffer>(anydata, serializeFunc);
        }

        static Buffer_ptr deserialize(MutableCharArray_ptr serialized,
                                      serialize_t serializeFunc,
                                      deserialize_t deserializeFunc)
        {
            boost::any anydata = deserializeFunc(serialized);
            return Buffer::make(anydata, serializeFunc);
        }

    public:
        Buffer(boost::any anydata, serialize_t serializeFunc) :
            _anydata(anydata), _serializeFunc(serializeFunc) {}

        ConstCharArray_ptr serialize()
        {
            return _serializeFunc(_anydata);
        }

        template<typename T> T data()
        {
            return boost::any_cast<T>(_anydata);
        }

    private:
        boost::any _anydata;
        serialize_t _serializeFunc;
};

//typedef std::pair<boost::any, serialize_t> Buffer;
typedef std::vector<Buffer_ptr> BufferVector;

template<typename T>
class Array
{
    public:
        typedef T value_type;
        typedef boost::shared_array<value_type> value_shared_array;
        value_shared_array data;
        unsigned size;
    public:
        Array(value_shared_array data_, unsigned size_) :
            data(data_), size(size_) {}
};
typedef Array<int> IntArray;
typedef boost::shared_ptr<IntArray> IntArray_ptr;

ConstCharArray_ptr serializeInt(boost::any& data)
{
    IntArray_ptr a = boost::any_cast<IntArray_ptr>(data);
    return boost::make_shared<ConstCharArray>(reinterpret_cast<const char*>(a->data.get()),
                                          a->size*sizeof(int));
}

boost::any deserializeInt(MutableCharArray_ptr serialized)
{
    int* data = reinterpret_cast<int*>(serialized->data);
    assert((serialized->size % sizeof(int)) == 0);
    IntArray_ptr arr = boost::make_shared<IntArray>(boost::shared_array<int>(data),
                                                    serialized->size/sizeof(int));
    return arr;
}

BOOST_AUTO_TEST_CASE(VectorInOut)
{
    boost::shared_array<int> intarr = boost::shared_array<int>(new int[2]);
    intarr[0] = 10;
    intarr[1] = 20;
    Buffer_ptr input = Buffer::make(boost::make_shared<IntArray>(intarr, 2),
                                serializeInt);
    ConstCharArray_ptr serialized = input->serialize();

    // Simulate network transfer (copy the serialized data)
    char* receivedData = new char[serialized->size];
    std::memcpy(receivedData, serialized->data, serialized->size);
    MutableCharArray_ptr received = boost::make_shared<MutableCharArray>(receivedData,
                                                                         serialized->size);

    // Deserialize the "received data"
    Buffer_ptr output = Buffer::deserialize(received, serializeInt, deserializeInt);
    IntArray_ptr aOut = output->data<IntArray_ptr>();
    std::cerr
        << aOut->data[0] << ":"
        << aOut->data[1] << ":"
        << aOut->size << std::endl;

    //BufferVector vec;
    //std::string s = "Hello world";
    //int i = 10;
    //BOOST_REQUIRE_EQUAL();
}

<commit_msg>Made the beginings of an Event class.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE TestEvent
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_array.hpp>
#include <boost/function.hpp>
#include <boost/any.hpp>
#include <cstring>
#include <iostream>

struct ConstCharArray;
typedef boost::shared_ptr<ConstCharArray> ConstCharArray_ptr;
struct ConstCharArray
{
    const char* data;
    unsigned size;
    ConstCharArray(const char* data_, unsigned size_) : data(data_), size(size_) {}

    static ConstCharArray_ptr make(const char* data, unsigned size)
    {
        return boost::make_shared<ConstCharArray>(data, size);
    }
};

struct MutableCharArray
{
    char* data;
    unsigned size;
    MutableCharArray(char* data_, unsigned size_) : data(data_), size(size_) {}
};
typedef boost::shared_ptr<MutableCharArray> MutableCharArray_ptr;

typedef boost::function<ConstCharArray_ptr (boost::any& data)> serialize_t;
typedef boost::function<boost::any (MutableCharArray_ptr serialized)> deserialize_t;

class Buffer;
typedef boost::shared_ptr<Buffer> Buffer_ptr;
class Buffer
{
    public:
        static Buffer_ptr make(boost::any anydata, serialize_t serializeFunc)
        {
            return boost::make_shared<Buffer>(anydata, serializeFunc);
        }

        static Buffer_ptr deserialize(MutableCharArray_ptr serialized,
                                      serialize_t serializeFunc,
                                      deserialize_t deserializeFunc)
        {
            boost::any anydata = deserializeFunc(serialized);
            return Buffer::make(anydata, serializeFunc);
        }

    public:
        Buffer(boost::any anydata, serialize_t serializeFunc) :
            _anydata(anydata), _serializeFunc(serializeFunc) {}

        ConstCharArray_ptr serialize()
        {
            return _serializeFunc(_anydata);
        }

        template<typename T> T data()
        {
            return boost::any_cast<T>(_anydata);
        }

    private:
        boost::any _anydata;
        serialize_t _serializeFunc;
};

//typedef std::pair<boost::any, serialize_t> Buffer;
typedef std::vector<Buffer_ptr> BufferVector;

template<typename T>
class Array
{
    public:
        typedef T value_type;
        typedef boost::shared_array<value_type> value_shared_array;
        value_shared_array sharedarr;
        unsigned size;
    public:
        Array(value_shared_array sharedarr_, unsigned size_) :
            sharedarr(sharedarr_), size(size_) {}
};
typedef Array<int> IntArray;
typedef boost::shared_ptr<IntArray> IntArray_ptr;

ConstCharArray_ptr serializeInt(boost::any& data)
{
    IntArray_ptr a = boost::any_cast<IntArray_ptr>(data);
    return ConstCharArray::make(reinterpret_cast<const char*>(a->sharedarr.get()),
                                a->size*sizeof(int));
}

boost::any deserializeInt(MutableCharArray_ptr serialized)
{
    int* data = reinterpret_cast<int*>(serialized->data);
    assert((serialized->size % sizeof(int)) == 0);
    IntArray_ptr arr = boost::make_shared<IntArray>(boost::shared_array<int>(data),
                                                    serialized->size/sizeof(int));
    return arr;
}

class Event;
typedef boost::shared_ptr<Event> Event_ptr;
class Event
{
    private:
        unsigned _eventid;
        BufferVector _buffers;
    public:
        static Event_ptr make(unsigned eventid, Buffer_ptr first)
        {
            return boost::make_shared<Event>(eventid, first);
        }

    public:
        Event(unsigned eventid) :
            _eventid(eventid)
        {}

        Event(unsigned eventid, Buffer_ptr first) :
            _eventid(eventid)
        {
            _buffers.push_back(first);
        }

        template<typename T>
        T first(serialize_t serializeFunc, deserialize_t deserializeFunc)
        {
            return _buffers.at(0)->data<T>();
        }
};

BOOST_AUTO_TEST_CASE(TestLowLevelSerialization)
{
    // Create and serialize an array
    boost::shared_array<int> intarr = boost::shared_array<int>(new int[2]);
    intarr[0] = 10;
    intarr[1] = 20;
    Buffer_ptr input = Buffer::make(boost::make_shared<IntArray>(intarr, 2),
                                    serializeInt);
    ConstCharArray_ptr serialized = input->serialize();

    // Simulate network transfer (copy the serialized data)
    char* receivedData = new char[serialized->size];
    std::memcpy(receivedData, serialized->data, serialized->size);
    MutableCharArray_ptr received = boost::make_shared<MutableCharArray>(receivedData,
                                                                         serialized->size);

    // Deserialize the "received data"
    Buffer_ptr output = Buffer::deserialize(received, serializeInt, deserializeInt);
    IntArray_ptr aOut = output->data<IntArray_ptr>();
    BOOST_REQUIRE_EQUAL(aOut->sharedarr[0], 10);
    BOOST_REQUIRE_EQUAL(aOut->sharedarr[1], 20);
    BOOST_REQUIRE_EQUAL(aOut->size, 2);
}

BOOST_AUTO_TEST_CASE(TestEvent)
{
    boost::shared_array<int> intarr = boost::shared_array<int>(new int[2]);
    intarr[0] = 10;
    intarr[1] = 20;
    Buffer_ptr inputArray = Buffer::make(boost::make_shared<IntArray>(intarr, 2),
                                    serializeInt);

    Event_ptr eventIn = Event::make(1010, inputArray);
    IntArray_ptr aOut = eventIn->first<IntArray_ptr>(serializeInt, deserializeInt);
    BOOST_REQUIRE_EQUAL(aOut->sharedarr[0], 10);
    BOOST_REQUIRE_EQUAL(aOut->sharedarr[1], 20);
    BOOST_REQUIRE_EQUAL(aOut->size, 2);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, Steinwurf ApS
// 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 Steinwurf ApS nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS 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.

#include <gtest/gtest.h>

#include <sak/buffer.hpp>

// TEST(TestBuffer, construct)
// {
//     {
//         sak::buffer b;
//         EXPECT_EQ(b.size(), 0U);
//     }
//
//     {
//         sak::buffer b;
//         b.resize(100);
//         EXPECT_EQ(b.size(), 100U);
//     }
//
//     {
//         sak::buffer b1;
//         b1.resize(100);
//         EXPECT_EQ(b1.size(), 100U);
//
//         sak::buffer b2 = b1;
//         EXPECT_EQ(b2.size(), 100U);
//     }
// }

//TEST(TestBuffer, append_to_empty)
//{
//     {
//         sak::buffer b;
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], static_cast<uint32_t>(data.size()));
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b;
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], &data[0] + data.size());
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b;
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(sak::storage(data));
//         EXPECT_EQ(b.size(), data.size());
//     }
//}

// TEST(TestBuffer, append_to_initialized)
// {
//     {
//         sak::buffer b(10);
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], static_cast<uint32_t>(data.size()));
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b(10);
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], &data[0] + data.size());
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b(10);
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(sak::storage(data));
//         EXPECT_EQ(b.size(), data.size());
//     }
//
// }

TEST(TestBuffer, resize_and_clear)
{
    sak::buffer b(100);
    EXPECT_EQ(b.size(), 0U);
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(10);
    EXPECT_EQ(b.size(), 10U);
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(101);
    EXPECT_EQ(b.size(), 101U);
    std::fill_n(b.data(), b.size(), 'x');

    b.clear();
    EXPECT_EQ(b.size(), 0U);

    b.resize(0);
    EXPECT_EQ(b.size(), 0U);

    b.resize(102);
    EXPECT_EQ(b.size(), 102U);
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(0);
    EXPECT_EQ(b.size(), 0U);

    b.clear();
    EXPECT_EQ(b.size(), 0U);
}
<commit_msg>Split construct test case in test_buffer.cpp<commit_after>// Copyright (c) 2012, Steinwurf ApS
// 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 Steinwurf ApS nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL Steinwurf ApS 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.

#include <gtest/gtest.h>

#include <sak/buffer.hpp>

TEST(TestBuffer, construct)
{
    sak::buffer b;
    EXPECT_EQ(b.size(), 0U);
}

TEST(TestBuffer, resize)
{
    sak::buffer b;
    b.resize(100);
    EXPECT_EQ(b.size(), 100U);
}

TEST(TestBuffer, resize_and_copy)
{
    sak::buffer b1;
    b1.resize(100);
    EXPECT_EQ(b1.size(), 100U);

    sak::buffer b2 = b1;
    EXPECT_EQ(b2.size(), 100U);
}

//TEST(TestBuffer, append_to_empty)
//{
//     {
//         sak::buffer b;
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], static_cast<uint32_t>(data.size()));
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b;
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], &data[0] + data.size());
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b;
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(sak::storage(data));
//         EXPECT_EQ(b.size(), data.size());
//     }
//}

// TEST(TestBuffer, append_to_initialized)
// {
//     {
//         sak::buffer b(10);
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], static_cast<uint32_t>(data.size()));
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b(10);
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(&data[0], &data[0] + data.size());
//         EXPECT_EQ(b.size(), data.size());
//     }
//
//     {
//         sak::buffer b(10);
//         EXPECT_EQ(b.size(), 0U);
//
//         std::vector<uint8_t> data(32, 'x');
//         b.append(sak::storage(data));
//         EXPECT_EQ(b.size(), data.size());
//     }
//
// }

TEST(TestBuffer, resize_and_clear)
{
    sak::buffer b(100);
    EXPECT_EQ(b.size(), 0U);
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(10);
    EXPECT_EQ(b.size(), 10U);
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(101);
    EXPECT_EQ(b.size(), 101U);
    std::fill_n(b.data(), b.size(), 'x');

    b.clear();
    EXPECT_EQ(b.size(), 0U);

    b.resize(0);
    EXPECT_EQ(b.size(), 0U);

    b.resize(102);
    EXPECT_EQ(b.size(), 102U);
    std::fill_n(b.data(), b.size(), 'x');

    b.resize(0);
    EXPECT_EQ(b.size(), 0U);

    b.clear();
    EXPECT_EQ(b.size(), 0U);
}
<|endoftext|>


<commit_before>#include <mettle.hpp>
using namespace mettle;

#include "helpers.hpp"

suite<> test_attr("attributes", [](auto &_) {
  subsuite<>(_, "bool_attr", [](auto &_) {
    _.test("without comment", []() {
      constexpr bool_attr attr("attribute");
      attr_instance a = attr;

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(true));
      expect(a.value(), array());
    });

    _.test("with comment", []() {
      constexpr bool_attr attr("attribute");
      attr_instance a = attr("comment");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("comment"));
    });

    _.test("skipped attribute", []() {
      constexpr bool_attr attr("attribute", attr_action::skip);
      attr_instance a = attr;

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::skip));
    });

    _.test("hidden attribute fails", []() {
      expect([]() { bool_attr("attribute", attr_action::hide); },
             thrown<std::invalid_argument>("attr's action can't be \"hide\""));
    });
  });

  subsuite<>(_, "string_attr", [](auto &_) {
    _.test("with value", []() {
      constexpr string_attr attr("attribute");
      attr_instance a = attr("value");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("value"));
    });
  });

  subsuite<>(_, "list_attr", [](auto &_) {
    _.test("single value", []() {
      constexpr list_attr attr("attribute");
      attr_instance a = attr("value");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("value"));
    });

    _.test("multiple values", []() {
      constexpr list_attr attr("attribute");
      attr_instance a = attr("value 1", "value 2");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("value 1", "value 2"));
    });
  });

  subsuite<>(_, "attr_list", [](auto &_) {
    _.test("unite", []() {
      constexpr bool_attr attr1("1");
      constexpr bool_attr attr2("2");
      constexpr bool_attr attr3("3");

      attr_list a = {attr1, attr2};
      attr_list b = {attr2, attr3};
      auto united = unite(a, b);
      expect(united, equal_to(attr_list{attr1, attr2, attr3}));
    });
  });

  subsuite<>(_, "default_attr_filter", [](auto &_) {
    _.test("no attributes", []() {
      expect(
        default_attr_filter{}( {} ),
        equal_to(filter_result{attr_action::run, nullptr})
      );
    });

    _.test("regular attribute", []() {
      constexpr bool_attr attr("bool");
      expect(
        default_attr_filter{}( {attr} ),
        equal_to(filter_result{attr_action::run, nullptr})
      );
    });

    _.test("skipped attribute", []() {
      constexpr bool_attr attr("bool", attr_action::skip);
      attr_list attrs = {attr};
      expect(
        default_attr_filter{}(attrs),
        equal_to(filter_result{attr_action::skip, &*attrs.begin()})
      );
    });
  });
});
<commit_msg>Improve tests for attribute unite()<commit_after>#include <mettle.hpp>
using namespace mettle;

#include "helpers.hpp"

suite<> test_attr("attributes", [](auto &_) {
  subsuite<>(_, "bool_attr", [](auto &_) {
    _.test("without comment", []() {
      constexpr bool_attr attr("attribute");
      attr_instance a = attr;

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(true));
      expect(a.value(), array());
    });

    _.test("with comment", []() {
      constexpr bool_attr attr("attribute");
      attr_instance a = attr("comment");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("comment"));
    });

    _.test("skipped attribute", []() {
      constexpr bool_attr attr("attribute", attr_action::skip);
      attr_instance a = attr;

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::skip));
    });

    _.test("hidden attribute fails", []() {
      expect([]() { bool_attr("attribute", attr_action::hide); },
             thrown<std::invalid_argument>("attr's action can't be \"hide\""));
    });
  });

  subsuite<>(_, "string_attr", [](auto &_) {
    _.test("with value", []() {
      constexpr string_attr attr("attribute");
      attr_instance a = attr("value");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("value"));
    });
  });

  subsuite<>(_, "list_attr", [](auto &_) {
    _.test("single value", []() {
      constexpr list_attr attr("attribute");
      attr_instance a = attr("value");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("value"));
    });

    _.test("multiple values", []() {
      constexpr list_attr attr("attribute");
      attr_instance a = attr("value 1", "value 2");

      expect(a.name(), equal_to("attribute"));
      expect(a.action(), equal_to(attr_action::run));
      expect(a.empty(), equal_to(false));
      expect(a.value(), array("value 1", "value 2"));
    });
  });

  subsuite<>(_, "unite(attr_list, attr_list)", [](auto &_) {
    _.test("empty sets", []() {
      constexpr string_attr attr("1");

      expect(unite({}, {}), equal_to(attr_list{}));
      expect(unite({attr("a")}, {}), equal_to(attr_list{attr("a")}));
      expect(unite({}, {attr("b")}), equal_to(attr_list{attr("b")}));
    });

    _.test("disjoint sets", []() {
      constexpr string_attr attr1("1");
      constexpr string_attr attr2("2");
      constexpr string_attr attr3("3");

      auto united = unite(
        {attr1("a")},
        {attr2("b"), attr3("b")}
      );
      expect(united, equal_to(attr_list{attr1("a"), attr2("b"), attr3("b")}));
    });

    _.test("intersecting sets", []() {
      constexpr string_attr attr1("1");
      constexpr string_attr attr2("2");
      constexpr string_attr attr3("3");

      auto united = unite(
        {attr1("a"), attr2("a")},
        {attr2("b"), attr3("b")}
      );
      expect(united, equal_to(attr_list{attr1("a"), attr2("a"), attr3("b")}));
    });
  });

  subsuite<>(_, "default_attr_filter", [](auto &_) {
    _.test("no attributes", []() {
      expect(
        default_attr_filter{}( {} ),
        equal_to(filter_result{attr_action::run, nullptr})
      );
    });

    _.test("regular attribute", []() {
      constexpr bool_attr attr("bool");
      expect(
        default_attr_filter{}( {attr} ),
        equal_to(filter_result{attr_action::run, nullptr})
      );
    });

    _.test("skipped attribute", []() {
      constexpr bool_attr attr("bool", attr_action::skip);
      attr_list attrs = {attr};
      expect(
        default_attr_filter{}(attrs),
        equal_to(filter_result{attr_action::skip, &*attrs.begin()})
      );
    });
  });
});
<|endoftext|>


<commit_before>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not 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.
 *
 */

#include "libtest/yatlcon.h"
#include <libtest/common.h>

#include <cstdio>
#include <cstdlib>
#include <unistd.h>

namespace libtest {

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool has_libmemcached(void)
{
#if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED
  if (HAVE_LIBMEMCACHED)
  {
    return true;
  }
#endif

  return false;
}
#pragma GCC diagnostic pop

bool has_libdrizzle(void)
{
#if defined(HAVE_LIBDRIZZLE) && HAVE_LIBDRIZZLE
  if (HAVE_LIBDRIZZLE)
  {
    return true;
  }
#endif

  return false;
}

bool has_postgres_support(void)
{
  char *getenv_ptr;
  if (bool((getenv_ptr= getenv("POSTGES_IS_RUNNING_AND_SETUP"))))
  {
    (void)(getenv_ptr);
    if (HAVE_LIBPQ)
    {
      return true;
    }
  }

  return false;
}

bool has_gearmand()
{
#if defined(GEARMAND_BINARY) && defined(HAVE_GEARMAND_BINARY) && HAVE_GEARMAND_BINARY
  if (HAVE_GEARMAND_BINARY)
  {
    std::stringstream arg_buffer;

    char *getenv_ptr;
    if (bool((getenv_ptr= getenv("PWD"))) and
        ((strcmp(GEARMAND_BINARY, "./gearmand/gearmand") == 0) or (strcmp(GEARMAND_BINARY, "gearmand/gearmand") == 0)))
    {
      arg_buffer << getenv_ptr;
      arg_buffer << "/";
    }
    arg_buffer << GEARMAND_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }
#endif

  return false;
}

bool has_drizzled()
{
#if defined(DRIZZLED_BINARY) && defined(HAVE_DRIZZLED_BINARY) && HAVE_DRIZZLED_BINARY
  if (HAVE_DRIZZLED_BINARY)
  {
    if (access(DRIZZLED_BINARY, X_OK) == 0)
    {
      return true;
    }
  }
#endif

  return false;
}

bool has_mysqld()
{
#if defined(MYSQLD_BINARY) && defined(HAVE_MYSQLD_BUILD) && HAVE_MYSQLD_BUILD
  if (HAVE_MYSQLD_BUILD)
  {
    if (access(MYSQLD_BINARY, X_OK) == 0)
    {
      return true;
    }
  }
#endif

  return false;
}

static char memcached_binary_path[FILENAME_MAX];

static void initialize_memcached_binary_path()
{
  memcached_binary_path[0]= 0;

#if defined(MEMCACHED_BINARY) && defined(HAVE_MEMCACHED_BINARY) && HAVE_MEMCACHED_BINARY
  if (HAVE_MEMCACHED_BINARY)
  {
    std::stringstream arg_buffer;

    char *getenv_ptr;
    if (bool((getenv_ptr= getenv("PWD"))) and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
    {
      arg_buffer << getenv_ptr;
      arg_buffer << "/";
    }
    arg_buffer << MEMCACHED_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      strncpy(memcached_binary_path, arg_buffer.str().c_str(), FILENAME_MAX);
    }
  }
#endif
}

static pthread_once_t memcached_binary_once= PTHREAD_ONCE_INIT;
static void initialize_memcached_binary(void)
{
  int ret;
  if ((ret= pthread_once(&memcached_binary_once, initialize_memcached_binary_path)) != 0)
  {
    FATAL(strerror(ret));
  }
}

bool has_memcached()
{
  initialize_memcached_binary();

  if (memcached_binary_path[0] and (strlen(memcached_binary_path) > 0))
  {
    return true;
  }

  return false;
}

const char* memcached_binary()
{
  initialize_memcached_binary();

  if (memcached_binary_path[0])
  {
    return memcached_binary_path;
  }

  return NULL;
}

const char *gearmand_binary()
{
#if defined(GEARMAND_BINARY)
  return GEARMAND_BINARY;
#else
  return NULL;
#endif
}

const char *drizzled_binary()
{
#if defined(DRIZZLED_BINARY)
  return DRIZZLED_BINARY;
#else
  return NULL;
#endif
}

} // namespace libtest
<commit_msg>Fix bad macro.<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not 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.
 *
 */

#include "libtest/yatlcon.h"
#include <libtest/common.h>

#include <cstdio>
#include <cstdlib>
#include <unistd.h>

namespace libtest {

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool has_libmemcached(void)
{
#if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED
  if (HAVE_LIBMEMCACHED)
  {
    return true;
  }
#endif

  return false;
}
#pragma GCC diagnostic pop

bool has_libdrizzle(void)
{
#if defined(HAVE_LIBDRIZZLE) && HAVE_LIBDRIZZLE
  if (HAVE_LIBDRIZZLE)
  {
    return true;
  }
#endif

  return false;
}

bool has_postgres_support(void)
{
  char *getenv_ptr;
  if (bool((getenv_ptr= getenv("POSTGES_IS_RUNNING_AND_SETUP"))))
  {
    (void)(getenv_ptr);
    if (HAVE_LIBPQ)
    {
      return true;
    }
  }

  return false;
}

bool has_gearmand()
{
#if defined(GEARMAND_BINARY) && defined(HAVE_GEARMAND_BINARY) && HAVE_GEARMAND_BINARY
  if (HAVE_GEARMAND_BINARY)
  {
    std::stringstream arg_buffer;

    char *getenv_ptr;
    if (bool((getenv_ptr= getenv("PWD"))) and
        ((strcmp(GEARMAND_BINARY, "./gearmand/gearmand") == 0) or (strcmp(GEARMAND_BINARY, "gearmand/gearmand") == 0)))
    {
      arg_buffer << getenv_ptr;
      arg_buffer << "/";
    }
    arg_buffer << GEARMAND_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }
#endif

  return false;
}

bool has_drizzled()
{
#if defined(DRIZZLED_BINARY) && defined(HAVE_DRIZZLED_BINARY) && HAVE_DRIZZLED_BINARY && defined(HAVE_LIBMYSQL_BUILD) && HAVE_LIBMYSQL_BUILD
  {
    if (access(DRIZZLED_BINARY, X_OK) == 0)
    {
      return true;
    }
  }
#endif

  return false;
}

bool has_mysqld()
{
#if defined(MYSQLD_BINARY) && defined(HAVE_MYSQLD_BUILD) && HAVE_MYSQLD_BUILD && defined(HAVE_LIBMYSQL_BUILD) && HAVE_LIBMYSQL_BUILD
  {
    if (access(MYSQLD_BINARY, X_OK) == 0)
    {
      return true;
    }
  }
#endif

  return false;
}

static char memcached_binary_path[FILENAME_MAX];

static void initialize_memcached_binary_path()
{
  memcached_binary_path[0]= 0;

#if defined(MEMCACHED_BINARY) && defined(HAVE_MEMCACHED_BINARY) && HAVE_MEMCACHED_BINARY
  if (HAVE_MEMCACHED_BINARY)
  {
    std::stringstream arg_buffer;

    char *getenv_ptr;
    if (bool((getenv_ptr= getenv("PWD"))) and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
    {
      arg_buffer << getenv_ptr;
      arg_buffer << "/";
    }
    arg_buffer << MEMCACHED_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      strncpy(memcached_binary_path, arg_buffer.str().c_str(), FILENAME_MAX);
    }
  }
#endif
}

static pthread_once_t memcached_binary_once= PTHREAD_ONCE_INIT;
static void initialize_memcached_binary(void)
{
  int ret;
  if ((ret= pthread_once(&memcached_binary_once, initialize_memcached_binary_path)) != 0)
  {
    FATAL(strerror(ret));
  }
}

bool has_memcached()
{
  initialize_memcached_binary();

  if (memcached_binary_path[0] and (strlen(memcached_binary_path) > 0))
  {
    return true;
  }

  return false;
}

const char* memcached_binary()
{
  initialize_memcached_binary();

  if (memcached_binary_path[0])
  {
    return memcached_binary_path;
  }

  return NULL;
}

const char *gearmand_binary()
{
#if defined(GEARMAND_BINARY)
  return GEARMAND_BINARY;
#else
  return NULL;
#endif
}

const char *drizzled_binary()
{
#if defined(DRIZZLED_BINARY)
  return DRIZZLED_BINARY;
#else
  return NULL;
#endif
}

} // namespace libtest
<|endoftext|>


<commit_before>#include "../src/rational_geometry/Direction.hpp"

#include "doctest.h"

#include <string>
#include <typeinfo>

namespace rational_geometry {

TEST_CASE("Testing Direction.hpp")
{
  using Direction3D = Direction<int, 3>;
  using Direction2D = Direction<int, 2>;

  const Direction3D null_dir_3{0, 0, 0};

  const Direction3D x3{1, 0, 0};
  const Direction3D y3{0, 1, 0};
  const Direction3D z3{0, 0, 1};

  const Direction2D null_dir_2{0, 0};
  const Direction2D arb_vals{1, 7};

  const Direction2D x2{1, 0};
  const Direction2D y2{0, 1};

  SUBCASE("Direction<> class")
  {
    SUBCASE("constructors")
    {
      SUBCASE("Direction()")
      {
        Direction2D a{};

        CHECK(a.get(0) == 0);
        CHECK(a.get(1) == 0);
      }

      SUBCASE("Direction(std::initializer_list<SignedIntT>)")
      {
        Direction3D val_a{1, 2, 3};
        CHECK(val_a.get_dimensionality() == 3);

        Direction3D val_b{2, 5};
        CHECK(val_b.get(1) == 5);
        CHECK(val_b.get(2) == 0);

        SUBCASE("normalization")
        {
          Direction3D val_c{2, 4, 6};
          CHECK(val_c.get(0) == 1);
          CHECK(val_c.get(1) == 2);
          CHECK(val_c.get(2) == 3);

          Direction3D val_d{-2, 4, 6};
          CHECK(val_d.get(0) == -1);
          CHECK(val_d.get(1) == 2);
          CHECK(val_d.get(2) == 3);

          Direction3D val_e{-2, 0, 6};
          CHECK(val_e.get(0) == -1);
          CHECK(val_e.get(1) == 0);
          CHECK(val_e.get(2) == 3);

          Direction3D val_f{-2, -4, -6};
          CHECK(val_f.get(0) == -1);
          CHECK(val_f.get(1) == -2);
          CHECK(val_f.get(2) == -3);
        }
      }

      SUBCASE("Direction(std::array<>)")
      {
        std::array<int, 3> argument{1, 2, 3};

        Direction3D val_a{argument};

        CHECK(val_a.get_dimensionality() == 3);
      }

      SUBCASE("Direction(std::initializer_list<std::pair>)")
      {
        Direction3D a{{1, 6}, {1, 4}, {-1, 3}};
        CHECK(a.get(0) == 2);
        CHECK(a.get(1) == 3);
        CHECK(a.get(2) == -4);

        Direction3D b{{0, 1}, {1, 4}, {1, 6}};
        CHECK(b.get(0) == 0);
        CHECK(b.get(1) == 3);
        CHECK(b.get(2) == 2);
      }
    }

    SUBCASE("accessors")
    {
      SUBCASE("get()")
      {
        std::array<int, 3> an_array{3, 4, 5};
        Direction3D a_direction{3, 4, 5};

        CHECK(an_array == a_direction.get());

        SUBCASE("Invariants in effect")
        {
          Direction3D equivalent_direction{6, 8, 10};

          CHECK(an_array == equivalent_direction.get());
        }

        // Doesn’t compile (as it shouldn't):
        // a_direction.get()[1] = 13;
      }

      SUBCASE("get(size_t)")
      {
        Direction3D a_value{4, 5, 6};

        CHECK(a_value.get(0) == 4);
        CHECK(a_value.get(1) == 5);
        CHECK(a_value.get(2) == 6);
      }

      SUBCASE("first_present_dimension()")
      {
        Direction3D val_a{1, 1, 0};
        CHECK(val_a.first_present_dimension() == 0);

        Direction3D val_b{0, 1, 0};
        CHECK(val_b.first_present_dimension() == 1);

        Direction3D val_c{0, 0, 5};
        CHECK(val_c.first_present_dimension() == 2);

        Direction3D val_d{0, 0, 0};
        CHECK(val_d.first_present_dimension() == 3); // 1 past the end!
      }
    }

    SUBCASE("operators")
    {
      Direction3D a{2, 3, 4};
      Direction3D b{2, 3, 4};
      Direction3D c{4, 6, 8};

      CHECK(a == b);
      CHECK(a == c);
    }

    SUBCASE("related functions")
    {
      SUBCASE("mutual_orthogonal(Direction, Direction, bool)")
      {
        Direction3D a{1, 0, 0};
        Direction3D b{0, 1, 0};
        Direction3D c{0, 0, 1};

        CHECK(mutual_orthogonal(a, b).get() == c.get());

        Direction3D c_minus{0, 0, -1};

        CHECK(mutual_orthogonal(a, b, true).get() == c_minus.get());

        Direction3D c_equivalent{0, 0, 1000};
        CHECK(mutual_orthogonal(a, b).get() == c_equivalent.get());
      }
    }
  }
}

} // namespace rational_geometry

// vim:set et ts=2 sw=2 sts=2:

<commit_msg>Use Direction::operator==(Direction) in Direction tests<commit_after>#include "../src/rational_geometry/Direction.hpp"

#include "doctest.h"

#include <string>
#include <typeinfo>

namespace rational_geometry {

TEST_CASE("Testing Direction.hpp")
{
  using Direction3D = Direction<int, 3>;
  using Direction2D = Direction<int, 2>;

  const Direction3D null_dir_3{0, 0, 0};

  const Direction3D x3{1, 0, 0};
  const Direction3D y3{0, 1, 0};
  const Direction3D z3{0, 0, 1};

  const Direction2D null_dir_2{0, 0};
  const Direction2D arb_vals{1, 7};

  const Direction2D x2{1, 0};
  const Direction2D y2{0, 1};

  SUBCASE("Direction<> class")
  {
    SUBCASE("constructors")
    {
      SUBCASE("Direction()")
      {
        Direction2D a{};

        CHECK(a.get(0) == 0);
        CHECK(a.get(1) == 0);
      }

      SUBCASE("Direction(std::initializer_list<SignedIntT>)")
      {
        Direction3D val_a{1, 2, 3};
        CHECK(val_a.get_dimensionality() == 3);

        Direction3D val_b{2, 5};
        CHECK(val_b.get(1) == 5);
        CHECK(val_b.get(2) == 0);

        SUBCASE("normalization")
        {
          Direction3D val_c{2, 4, 6};
          CHECK(val_c.get(0) == 1);
          CHECK(val_c.get(1) == 2);
          CHECK(val_c.get(2) == 3);

          Direction3D val_d{-2, 4, 6};
          CHECK(val_d.get(0) == -1);
          CHECK(val_d.get(1) == 2);
          CHECK(val_d.get(2) == 3);

          Direction3D val_e{-2, 0, 6};
          CHECK(val_e.get(0) == -1);
          CHECK(val_e.get(1) == 0);
          CHECK(val_e.get(2) == 3);

          Direction3D val_f{-2, -4, -6};
          CHECK(val_f.get(0) == -1);
          CHECK(val_f.get(1) == -2);
          CHECK(val_f.get(2) == -3);
        }
      }

      SUBCASE("Direction(std::array<>)")
      {
        std::array<int, 3> argument{1, 2, 3};

        Direction3D val_a{argument};

        CHECK(val_a.get_dimensionality() == 3);
      }

      SUBCASE("Direction(std::initializer_list<std::pair>)")
      {
        Direction3D a{{1, 6}, {1, 4}, {-1, 3}};
        CHECK(a.get(0) == 2);
        CHECK(a.get(1) == 3);
        CHECK(a.get(2) == -4);

        Direction3D b{{0, 1}, {1, 4}, {1, 6}};
        CHECK(b.get(0) == 0);
        CHECK(b.get(1) == 3);
        CHECK(b.get(2) == 2);
      }
    }

    SUBCASE("accessors")
    {
      SUBCASE("get()")
      {
        std::array<int, 3> an_array{3, 4, 5};
        Direction3D a_direction{3, 4, 5};

        CHECK(an_array == a_direction.get());

        SUBCASE("Invariants in effect")
        {
          Direction3D equivalent_direction{6, 8, 10};

          CHECK(an_array == equivalent_direction.get());
        }

        // Doesn’t compile (as it shouldn't):
        // a_direction.get()[1] = 13;
      }

      SUBCASE("get(size_t)")
      {
        Direction3D a_value{4, 5, 6};

        CHECK(a_value.get(0) == 4);
        CHECK(a_value.get(1) == 5);
        CHECK(a_value.get(2) == 6);
      }

      SUBCASE("first_present_dimension()")
      {
        Direction3D val_a{1, 1, 0};
        CHECK(val_a.first_present_dimension() == 0);

        Direction3D val_b{0, 1, 0};
        CHECK(val_b.first_present_dimension() == 1);

        Direction3D val_c{0, 0, 5};
        CHECK(val_c.first_present_dimension() == 2);

        Direction3D val_d{0, 0, 0};
        CHECK(val_d.first_present_dimension() == 3); // 1 past the end!
      }
    }

    SUBCASE("operators")
    {
      Direction3D a{2, 3, 4};
      Direction3D b{2, 3, 4};
      Direction3D c{4, 6, 8};

      CHECK(a == b);
      CHECK(a == c);
    }

    SUBCASE("related functions")
    {
      SUBCASE("mutual_orthogonal(Direction, Direction, bool)")
      {
        Direction3D a{1, 0, 0};
        Direction3D b{0, 1, 0};
        Direction3D c{0, 0, 1};

        CHECK(mutual_orthogonal(a, b) == c);

        Direction3D c_minus{0, 0, -1};

        CHECK(mutual_orthogonal(a, b, true) == c_minus);

        Direction3D c_equivalent{0, 0, 1000};
        CHECK(mutual_orthogonal(a, b) == c_equivalent);
      }
    }
  }
}

} // namespace rational_geometry

// vim:set et ts=2 sw=2 sts=2:

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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.
 */

#include "TestHarness.h"
#include "TestOutput.h"
#include "TestResult.h"
#include "MockTestOutput.h"

TEST_GROUP(TestOutput)
{
	TestOutput* printer;
	MockTestOutput* mock;
	Utest* tst;
	Failure *f;
	TestResult* result;

	TEST_SETUP()
	{
		mock = new MockTestOutput();
		printer = mock;
		tst = new Utest("group", "test", "file", 1);
		f = new Failure(tst, "failfile", 2, "message");
		result = new TestResult(*mock);
	}
	TEST_TEARDOWN()
	{
		delete printer;
		delete tst;
		delete f;
		delete result;
	}
};

TEST(TestOutput, PrintConstCharStar)
{
  printer->print("hello");
  printer->print("hello\n");
  STRCMP_EQUAL("hellohello\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintLong)
{
  printer->print(1234);
  STRCMP_EQUAL("1234", mock->getOutput().asCharString());
}

TEST(TestOutput, StreamOperators)
{
  *printer << "n=" << 1234;
  STRCMP_EQUAL("n=1234", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTest)
{
	printer->printCurrentTest(*tst);
	STRCMP_EQUAL(".", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestALot)
{
	for (int i = 0; i < 60; ++i) {
		printer->printCurrentTest(*tst);
	}
	STRCMP_EQUAL("..................................................\n..........", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestVerbose)
{
	mock->verbose();
	printer->printCurrentTest(*tst);
	STRCMP_EQUAL("TEST(group, test)\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestRun)
{
	printer->printTestRun(2, 3);
	STRCMP_EQUAL("Test run 2 of 3\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestRunOnlyOne)
{
	printer->printTestRun(1, 1);
	STRCMP_EQUAL("", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintFailure)
{
	printer->print(*f);
	STRCMP_EQUAL("\nfailfile:2:Failure in TEST(group, test)\n\tmessage\n\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestStarts)
{
	printer->printTestsStarted();
	STRCMP_EQUAL("", mock->getOutput().asCharString());
}

TEST(TestOutput, printTestsEnded)
{
	result->countTest();
	result->countCheck();
	result->countIgnored();
	result->countIgnored();
	result->countRun();
	result->countRun();
	result->countRun();
	printer->printTestsEnded(*result);
	STRCMP_EQUAL("\nOK (1 tests, 3 ran, 1 checks, 2 ignored, 0 filtered out)\n\n", mock->getOutput().asCharString());
}

TEST(TestOutput, printTestsEndedWithFailures)
{
	result->addFailure(*f);
	printer->flush();
	printer->printTestsEnded(*result);
	STRCMP_EQUAL("\nErrors (1 failures, 0 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out)\n\n", mock->getOutput().asCharString());
}
<commit_msg>Changed the Test output<commit_after>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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.
 */

#include "TestHarness.h"
#include "TestOutput.h"
#include "TestResult.h"
#include "MockTestOutput.h"

TEST_GROUP(TestOutput)
{
	TestOutput* printer;
	MockTestOutput* mock;
	Utest* tst;
	Failure *f;
	TestResult* result;

	TEST_SETUP()
	{
		mock = new MockTestOutput();
		printer = mock;
		tst = new Utest("group", "test", "file", 1);
		f = new Failure(tst, "failfile", 2, "message");
		result = new TestResult(*mock);
	}
	TEST_TEARDOWN()
	{
		delete printer;
		delete tst;
		delete f;
		delete result;
	}
};

TEST(TestOutput, PrintConstCharStar)
{
  printer->print("hello");
  printer->print("hello\n");
  STRCMP_EQUAL("hellohello\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintLong)
{
  printer->print(1234);
  STRCMP_EQUAL("1234", mock->getOutput().asCharString());
}

TEST(TestOutput, StreamOperators)
{
  *printer << "n=" << 1234;
  STRCMP_EQUAL("n=1234", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTest)
{
	printer->printCurrentTest(*tst);
	STRCMP_EQUAL(".", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestALot)
{
	for (int i = 0; i < 60; ++i) {
		printer->printCurrentTest(*tst);
	}
	STRCMP_EQUAL("..................................................\n..........", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestVerbose)
{
	mock->verbose();
	printer->printCurrentTest(*tst);
	STRCMP_EQUAL("TEST(group, test)\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestRun)
{
	printer->printTestRun(2, 3);
	STRCMP_EQUAL("Test run 2 of 3\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestRunOnlyOne)
{
	printer->printTestRun(1, 1);
	STRCMP_EQUAL("", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintFailure)
{
	printer->print(*f);
	STRCMP_EQUAL("\nfailfile:2: error: Failure in TEST(group, test)\n\tmessage\n\n", mock->getOutput().asCharString());
}

TEST(TestOutput, PrintTestStarts)
{
	printer->printTestsStarted();
	STRCMP_EQUAL("", mock->getOutput().asCharString());
}

TEST(TestOutput, printTestsEnded)
{
	result->countTest();
	result->countCheck();
	result->countIgnored();
	result->countIgnored();
	result->countRun();
	result->countRun();
	result->countRun();
	printer->printTestsEnded(*result);
	STRCMP_EQUAL("\nOK (1 tests, 3 ran, 1 checks, 2 ignored, 0 filtered out)\n\n", mock->getOutput().asCharString());
}

TEST(TestOutput, printTestsEndedWithFailures)
{
	result->addFailure(*f);
	printer->flush();
	printer->printTestsEnded(*result);
	STRCMP_EQUAL("\nErrors (1 failures, 0 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out)\n\n", mock->getOutput().asCharString());
}
<|endoftext|>


<commit_before>// Source : https://leetcode.com/problems/recover-binary-search-tree/
// Author : Siyuan Xu
// Date   : 2015-08-15

/**********************************************************************************
*
* Two elements of a binary search tree (BST) are swapped by mistake.
*
* Recover the tree without changing its structure.
*
* Note:
* A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
*
* confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
*
* OJ's Binary Tree Serialization:
*
* The serialization of a binary tree follows a level order traversal, where '#' signifies
* a path terminator where no node exists below.
*
* Here's an example:
*
*    1
*   / \
*  2   3
*     /
*    4
*     \
*      5
*
* The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*
*
**********************************************************************************/

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

 //bad solution
 //300ms(slow)
class Solution1 {
public:
    void recoverTree(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        TreeNode *n1 = NULL;
        TreeNode *n2 = NULL;
        TreeNode *prev = NULL;
        proc(root,n1,n2,prev);
        if(n1 && n2)
            swap(n1->val,n2->val);
        }
    void proc(TreeNode *root, TreeNode *&n1, TreeNode *&n2, TreeNode *&prev)
    {
        if(!root)
            return;
        proc(root->left,n1,n2,prev);
        if(prev && prev->val > root->val)
        {
            n2 = root;
            if(!n1)
            n1 = prev;
        }
        prev = root;
        proc(root->right,n1,n2,prev);
    }
};
<commit_msg>Update recoverBinarySearchTree.cpp<commit_after>// Source : https://leetcode.com/problems/recover-binary-search-tree/
// Author : Siyuan Xu
// Date   : 2015-08-15

/**********************************************************************************
*
* Two elements of a binary search tree (BST) are swapped by mistake.
*
* Recover the tree without changing its structure.
*
* Note:
* A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
*
* confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
*
* OJ's Binary Tree Serialization:
*
* The serialization of a binary tree follows a level order traversal, where '#' signifies
* a path terminator where no node exists below.
*
* Here's an example:
*
*    1
*   / \
*  2   3
*     /
*    4
*     \
*      5
*
* The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
*
*
**********************************************************************************/

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

 //52(good)
class Solution1 {
public:
    void recoverTree(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        TreeNode *n1 = NULL;
        TreeNode *n2 = NULL;
        TreeNode *prev = NULL;
        proc(root,n1,n2,prev);
        if(n1 && n2)
            swap(n1->val,n2->val);
        }
    void proc(TreeNode *root, TreeNode *&n1, TreeNode *&n2, TreeNode *&prev)
    {
        if(!root)
            return;
        proc(root->left,n1,n2,prev);
        if(prev && prev->val > root->val)
        {
            n2 = root;
            if(!n1)
            n1 = prev;
        }
        prev = root;
        proc(root->right,n1,n2,prev);
    }
};
<|endoftext|>