<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sbxsng.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2007-11-13 15:23:57 $
 *
 *  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_basic.hxx"

#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include <basic/sbx.hxx>
#include "sbxconv.hxx"

float ImpGetSingle( const SbxValues* p )
{
    SbxValues aTmp;
    float nRes;
start:
    switch( +p->eType )
    {
        case SbxNULL:
            SbxBase::SetError( SbxERR_CONVERSION );
        case SbxEMPTY:
            nRes = 0; break;
        case SbxCHAR:
            nRes = p->nChar; break;
        case SbxBYTE:
            nRes = p->nByte; break;
        case SbxINTEGER:
        case SbxBOOL:
            nRes = p->nInteger; break;
        case SbxERROR:
        case SbxUSHORT:
            nRes = p->nUShort; break;
        case SbxLONG:
            nRes = (float) p->nLong; break;
        case SbxULONG:
            nRes = (float) p->nULong; break;
        case SbxSINGLE:
            nRes = p->nSingle; break;
        case SbxSALINT64:
            nRes = (float) p->nInt64; break;
        case SbxSALUINT64:
            nRes = (float) ImpSalUInt64ToDouble( p->uInt64 ); break;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            if( p->pDecimal )
                p->pDecimal->getSingle( nRes );
            else
                nRes = 0.0;
            break;
        case SbxDATE:
        case SbxDOUBLE:
        case SbxLONG64:
        case SbxULONG64:
        case SbxCURRENCY:
            {
            double dVal;
            if( p->eType == SbxCURRENCY )
                dVal = ImpCurrencyToDouble( p->nLong64 );
            else if( p->eType == SbxLONG64 )
                dVal = ImpINT64ToDouble( p->nLong64 );
            else if( p->eType == SbxULONG64 )
                dVal = ImpUINT64ToDouble( p->nULong64 );
            else
                dVal = p->nDouble;

            if( dVal > SbxMAXSNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMAXSNG);
            }
            else if( dVal < SbxMINSNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMINSNG);
            }
            else if( dVal > 0 && dVal < SbxMAXSNG2 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMAXSNG2);
            }
            else if( dVal < 0 && dVal > SbxMINSNG2 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMINSNG2);
            }
            else
                nRes = (float) dVal;
            break;
            }
        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
            if( !p->pString )
                nRes = 0;
            else
            {
                double d;
                SbxDataType t;
                if( ImpScan( *p->pString, d, t, NULL ) != SbxERR_OK )
                    nRes = 0;
                else if( d > SbxMAXSNG )
                {
                    SbxBase::SetError( SbxERR_OVERFLOW );
                    nRes = static_cast< float >(SbxMAXSNG);
                }
                else if( d < SbxMINSNG )
                {
                    SbxBase::SetError( SbxERR_OVERFLOW );
                    nRes = static_cast< float >(SbxMINSNG);
                }
                else
                    nRes = (float) d;
            }
            break;
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                nRes = pVal->GetSingle();
            else
            {
                SbxBase::SetError( SbxERR_NO_OBJECT ); nRes = 0;
            }
            break;
        }

        case SbxBYREF | SbxCHAR:
            nRes = *p->pChar; break;
        case SbxBYREF | SbxBYTE:
            nRes = *p->pByte; break;
        case SbxBYREF | SbxINTEGER:
        case SbxBYREF | SbxBOOL:
            nRes = *p->pInteger; break;
        case SbxBYREF | SbxLONG:
            nRes = (float) *p->pLong; break;
        case SbxBYREF | SbxULONG:
            nRes = (float) *p->pULong; break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            nRes = *p->pUShort; break;
        case SbxBYREF | SbxSINGLE:
            nRes = *p->pSingle; break;
        // ab hier muss getestet werden
        case SbxBYREF | SbxDATE:
        case SbxBYREF | SbxDOUBLE:
            aTmp.nDouble = *p->pDouble; goto ref;
        case SbxBYREF | SbxULONG64:
            aTmp.nULong64 = *p->pULong64; goto ref;
        case SbxBYREF | SbxLONG64:
        case SbxBYREF | SbxSALINT64:
            nRes = (float) *p->pnInt64; break;
        case SbxBYREF | SbxSALUINT64:
            nRes = (float) ImpSalUInt64ToDouble( *p->puInt64 ); break;
        case SbxBYREF | SbxCURRENCY:
            aTmp.nLong64 = *p->pLong64; goto ref;
        ref:
            aTmp.eType = SbxDataType( p->eType & 0x0FFF );
            p = &aTmp; goto start;

        default:
            SbxBase::SetError( SbxERR_CONVERSION ); nRes = 0;
    }
    return nRes;
}

void ImpPutSingle( SbxValues* p, float n )
{
    SbxValues aTmp;
start:
    switch( +p->eType )
    {
        case SbxCHAR:
            aTmp.pChar = &p->nChar; goto direct;
        case SbxBYTE:
            aTmp.pByte = &p->nByte; goto direct;
        case SbxINTEGER:
        case SbxBOOL:
            aTmp.pInteger = &p->nInteger; goto direct;
        case SbxLONG:
            aTmp.pLong = &p->nLong; goto direct;
        case SbxULONG:
            aTmp.pULong = &p->nULong; goto direct;
        case SbxERROR:
        case SbxUSHORT:
            aTmp.pUShort = &p->nUShort; goto direct;
        case SbxULONG64:
            aTmp.pULong64 = &p->nULong64; goto direct;
        case SbxLONG64:
        case SbxCURRENCY:
            aTmp.pLong64 = &p->nLong64; goto direct;
        case SbxSALINT64:
            aTmp.pnInt64 = &p->nInt64; goto direct;
        case SbxSALUINT64:
            aTmp.puInt64 = &p->uInt64; goto direct;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            {
            SbxDecimal* pDec = ImpCreateDecimal( p );
            if( !pDec->setSingle( n ) )
                SbxBase::SetError( SbxERR_OVERFLOW );
            break;
            }
        direct:
            aTmp.eType = SbxDataType( p->eType | SbxBYREF );
            p = &aTmp; goto start;

        // keine Tests ab hier
        case SbxSINGLE:
            p->nSingle = n; break;
        case SbxDATE:
        case SbxDOUBLE:
            p->nDouble = n; break;

        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
        {
            if( !p->pString )
                p->pString = new XubString;
            ImpCvtNum( (double) n, 6, *p->pString );
            break;
        }
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                pVal->PutSingle( n );
            else
                SbxBase::SetError( SbxERR_NO_OBJECT );
            break;
        }
        case SbxBYREF | SbxCHAR:
            if( n > SbxMAXCHAR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXCHAR;
            }
            else if( n < SbxMINCHAR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMINCHAR;
            }
            *p->pChar = (xub_Unicode) n; break;
        case SbxBYREF | SbxBYTE:
            if( n > SbxMAXBYTE )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXBYTE;
            }
            else if( n < 0 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
            }
            *p->pByte = (BYTE) n; break;
        case SbxBYREF | SbxINTEGER:
        case SbxBYREF | SbxBOOL:
            if( n > SbxMAXINT )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXINT;
            }
            else if( n < SbxMININT )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMININT;
            }
            *p->pInteger = (INT16) n; break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            if( n > SbxMAXUINT )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXUINT;
            }
            else if( n < 0 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
            }
            *p->pUShort = (UINT16) n; break;
        case SbxBYREF | SbxLONG:
        {
            INT32 i;
            if( n > SbxMAXLNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXLNG;
            }
            else if( n < SbxMINLNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMINLNG;
            }
            else
            {
                i = sal::static_int_cast< INT32 >(n);
            }
            *p->pLong = i; break;
        }
        case SbxBYREF | SbxULONG:
        {
            UINT32 i;
            if( n > SbxMAXULNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXULNG;
            }
            else if( n < 0 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = 0;
            }
            else
            {
                i = sal::static_int_cast< UINT32 >(n);
            }
            *p->pULong = i; break;
        }
        case SbxBYREF | SbxSINGLE:
            *p->pSingle = n; break;
        case SbxBYREF | SbxDATE:
        case SbxBYREF | SbxDOUBLE:
            *p->pDouble = (double) n; break;
        case SbxBYREF | SbxSALINT64:
            *p->pnInt64 = ImpDoubleToSalInt64( (double) n ); break;
        case SbxBYREF | SbxSALUINT64:
            *p->puInt64 = ImpDoubleToSalUInt64( (double) n ); break;
        case SbxBYREF | SbxCURRENCY:
            double d;
            if( n > SbxMAXCURR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMAXCURR;
            }
            else if( n < SbxMINCURR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMINCURR;
            }
            else
            {
                d = n;
            }
            *p->pLong64 = ImpDoubleToCurrency( n ); break;

        default:
            SbxBase::SetError( SbxERR_CONVERSION );
    }
}

<commit_msg>INTEGRATION: CWS changefileheader (1.7.46); FILE MERGED 2008/04/01 15:02:00 thb 1.7.46.2: #i85898# Stripping all external header guards 2008/03/28 16:07:49 rt 1.7.46.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: sbxsng.cxx,v $
 * $Revision: 1.8 $
 *
 * 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_basic.hxx"
#include <tools/errcode.hxx>
#include <basic/sbx.hxx>
#include "sbxconv.hxx"

float ImpGetSingle( const SbxValues* p )
{
    SbxValues aTmp;
    float nRes;
start:
    switch( +p->eType )
    {
        case SbxNULL:
            SbxBase::SetError( SbxERR_CONVERSION );
        case SbxEMPTY:
            nRes = 0; break;
        case SbxCHAR:
            nRes = p->nChar; break;
        case SbxBYTE:
            nRes = p->nByte; break;
        case SbxINTEGER:
        case SbxBOOL:
            nRes = p->nInteger; break;
        case SbxERROR:
        case SbxUSHORT:
            nRes = p->nUShort; break;
        case SbxLONG:
            nRes = (float) p->nLong; break;
        case SbxULONG:
            nRes = (float) p->nULong; break;
        case SbxSINGLE:
            nRes = p->nSingle; break;
        case SbxSALINT64:
            nRes = (float) p->nInt64; break;
        case SbxSALUINT64:
            nRes = (float) ImpSalUInt64ToDouble( p->uInt64 ); break;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            if( p->pDecimal )
                p->pDecimal->getSingle( nRes );
            else
                nRes = 0.0;
            break;
        case SbxDATE:
        case SbxDOUBLE:
        case SbxLONG64:
        case SbxULONG64:
        case SbxCURRENCY:
            {
            double dVal;
            if( p->eType == SbxCURRENCY )
                dVal = ImpCurrencyToDouble( p->nLong64 );
            else if( p->eType == SbxLONG64 )
                dVal = ImpINT64ToDouble( p->nLong64 );
            else if( p->eType == SbxULONG64 )
                dVal = ImpUINT64ToDouble( p->nULong64 );
            else
                dVal = p->nDouble;

            if( dVal > SbxMAXSNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMAXSNG);
            }
            else if( dVal < SbxMINSNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMINSNG);
            }
            else if( dVal > 0 && dVal < SbxMAXSNG2 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMAXSNG2);
            }
            else if( dVal < 0 && dVal > SbxMINSNG2 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW );
                nRes = static_cast< float >(SbxMINSNG2);
            }
            else
                nRes = (float) dVal;
            break;
            }
        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
            if( !p->pString )
                nRes = 0;
            else
            {
                double d;
                SbxDataType t;
                if( ImpScan( *p->pString, d, t, NULL ) != SbxERR_OK )
                    nRes = 0;
                else if( d > SbxMAXSNG )
                {
                    SbxBase::SetError( SbxERR_OVERFLOW );
                    nRes = static_cast< float >(SbxMAXSNG);
                }
                else if( d < SbxMINSNG )
                {
                    SbxBase::SetError( SbxERR_OVERFLOW );
                    nRes = static_cast< float >(SbxMINSNG);
                }
                else
                    nRes = (float) d;
            }
            break;
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                nRes = pVal->GetSingle();
            else
            {
                SbxBase::SetError( SbxERR_NO_OBJECT ); nRes = 0;
            }
            break;
        }

        case SbxBYREF | SbxCHAR:
            nRes = *p->pChar; break;
        case SbxBYREF | SbxBYTE:
            nRes = *p->pByte; break;
        case SbxBYREF | SbxINTEGER:
        case SbxBYREF | SbxBOOL:
            nRes = *p->pInteger; break;
        case SbxBYREF | SbxLONG:
            nRes = (float) *p->pLong; break;
        case SbxBYREF | SbxULONG:
            nRes = (float) *p->pULong; break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            nRes = *p->pUShort; break;
        case SbxBYREF | SbxSINGLE:
            nRes = *p->pSingle; break;
        // ab hier muss getestet werden
        case SbxBYREF | SbxDATE:
        case SbxBYREF | SbxDOUBLE:
            aTmp.nDouble = *p->pDouble; goto ref;
        case SbxBYREF | SbxULONG64:
            aTmp.nULong64 = *p->pULong64; goto ref;
        case SbxBYREF | SbxLONG64:
        case SbxBYREF | SbxSALINT64:
            nRes = (float) *p->pnInt64; break;
        case SbxBYREF | SbxSALUINT64:
            nRes = (float) ImpSalUInt64ToDouble( *p->puInt64 ); break;
        case SbxBYREF | SbxCURRENCY:
            aTmp.nLong64 = *p->pLong64; goto ref;
        ref:
            aTmp.eType = SbxDataType( p->eType & 0x0FFF );
            p = &aTmp; goto start;

        default:
            SbxBase::SetError( SbxERR_CONVERSION ); nRes = 0;
    }
    return nRes;
}

void ImpPutSingle( SbxValues* p, float n )
{
    SbxValues aTmp;
start:
    switch( +p->eType )
    {
        case SbxCHAR:
            aTmp.pChar = &p->nChar; goto direct;
        case SbxBYTE:
            aTmp.pByte = &p->nByte; goto direct;
        case SbxINTEGER:
        case SbxBOOL:
            aTmp.pInteger = &p->nInteger; goto direct;
        case SbxLONG:
            aTmp.pLong = &p->nLong; goto direct;
        case SbxULONG:
            aTmp.pULong = &p->nULong; goto direct;
        case SbxERROR:
        case SbxUSHORT:
            aTmp.pUShort = &p->nUShort; goto direct;
        case SbxULONG64:
            aTmp.pULong64 = &p->nULong64; goto direct;
        case SbxLONG64:
        case SbxCURRENCY:
            aTmp.pLong64 = &p->nLong64; goto direct;
        case SbxSALINT64:
            aTmp.pnInt64 = &p->nInt64; goto direct;
        case SbxSALUINT64:
            aTmp.puInt64 = &p->uInt64; goto direct;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            {
            SbxDecimal* pDec = ImpCreateDecimal( p );
            if( !pDec->setSingle( n ) )
                SbxBase::SetError( SbxERR_OVERFLOW );
            break;
            }
        direct:
            aTmp.eType = SbxDataType( p->eType | SbxBYREF );
            p = &aTmp; goto start;

        // keine Tests ab hier
        case SbxSINGLE:
            p->nSingle = n; break;
        case SbxDATE:
        case SbxDOUBLE:
            p->nDouble = n; break;

        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
        {
            if( !p->pString )
                p->pString = new XubString;
            ImpCvtNum( (double) n, 6, *p->pString );
            break;
        }
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                pVal->PutSingle( n );
            else
                SbxBase::SetError( SbxERR_NO_OBJECT );
            break;
        }
        case SbxBYREF | SbxCHAR:
            if( n > SbxMAXCHAR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXCHAR;
            }
            else if( n < SbxMINCHAR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMINCHAR;
            }
            *p->pChar = (xub_Unicode) n; break;
        case SbxBYREF | SbxBYTE:
            if( n > SbxMAXBYTE )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXBYTE;
            }
            else if( n < 0 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
            }
            *p->pByte = (BYTE) n; break;
        case SbxBYREF | SbxINTEGER:
        case SbxBYREF | SbxBOOL:
            if( n > SbxMAXINT )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXINT;
            }
            else if( n < SbxMININT )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMININT;
            }
            *p->pInteger = (INT16) n; break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            if( n > SbxMAXUINT )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = SbxMAXUINT;
            }
            else if( n < 0 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); n = 0;
            }
            *p->pUShort = (UINT16) n; break;
        case SbxBYREF | SbxLONG:
        {
            INT32 i;
            if( n > SbxMAXLNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXLNG;
            }
            else if( n < SbxMINLNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMINLNG;
            }
            else
            {
                i = sal::static_int_cast< INT32 >(n);
            }
            *p->pLong = i; break;
        }
        case SbxBYREF | SbxULONG:
        {
            UINT32 i;
            if( n > SbxMAXULNG )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = SbxMAXULNG;
            }
            else if( n < 0 )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); i = 0;
            }
            else
            {
                i = sal::static_int_cast< UINT32 >(n);
            }
            *p->pULong = i; break;
        }
        case SbxBYREF | SbxSINGLE:
            *p->pSingle = n; break;
        case SbxBYREF | SbxDATE:
        case SbxBYREF | SbxDOUBLE:
            *p->pDouble = (double) n; break;
        case SbxBYREF | SbxSALINT64:
            *p->pnInt64 = ImpDoubleToSalInt64( (double) n ); break;
        case SbxBYREF | SbxSALUINT64:
            *p->puInt64 = ImpDoubleToSalUInt64( (double) n ); break;
        case SbxBYREF | SbxCURRENCY:
            double d;
            if( n > SbxMAXCURR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMAXCURR;
            }
            else if( n < SbxMINCURR )
            {
                SbxBase::SetError( SbxERR_OVERFLOW ); d = SbxMINCURR;
            }
            else
            {
                d = n;
            }
            *p->pLong64 = ImpDoubleToCurrency( n ); break;

        default:
            SbxBase::SetError( SbxERR_CONVERSION );
    }
}

<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "NaClApplication.h"

#include <ppapi/cpp/graphics_3d.h>
#include <ppapi/cpp/fullscreen.h>
#include <ppapi/cpp/completion_callback.h>

#include "Context.h"

namespace Magnum { namespace Platform {

NaClApplication::NaClApplication(const Arguments& arguments): Instance(arguments), Graphics3DClient(this), MouseLock(this), c(nullptr) {
    createContext(new Configuration);
}

NaClApplication::NaClApplication(const Arguments& arguments, Configuration* configuration): Instance(arguments), Graphics3DClient(this), MouseLock(this), c(nullptr) {
    if(configuration) createContext(configuration);
}

void NaClApplication::createContext(NaClApplication::Configuration* configuration) {
    CORRADE_ASSERT(!c, "NaClApplication::createContext(): context already created", );

    viewportSize = configuration->size();

    std::int32_t attributes[] = {
        PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
        PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24,
        PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8,
        PP_GRAPHICS3DATTRIB_SAMPLES, configuration->sampleCount(),
        PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, configuration->sampleCount() > 1? 1 : 0,
        PP_GRAPHICS3DATTRIB_WIDTH, configuration->size().x(),
        PP_GRAPHICS3DATTRIB_HEIGHT, configuration->size().y(),
        PP_GRAPHICS3DATTRIB_NONE
    };

    graphics = new pp::Graphics3D(this, attributes);
    if(graphics->is_null()) {
        Error() << "Platform::NaClApplication::NaClApplication(): cannot create graphics";
        std::exit(1);
    }
    if(!BindGraphics(*graphics)) {
        Error() << "Platform::NaClApplication::NaClApplication(): cannot bind graphics";
        std::exit(1);
    }

    fullscreen = new pp::Fullscreen(this);

    glSetCurrentContextPPAPI(graphics->pp_resource());

    c = new Context;

    /* Enable input handling for mouse and keyboard */
    RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE|PP_INPUTEVENT_CLASS_WHEEL);
    RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);

    /* Make sure viewportEvent() is called for first time */
    flags |= Flag::ViewportUpdated;

    delete configuration;
}

NaClApplication::~NaClApplication() {
    delete c;
    delete fullscreen;
    delete graphics;
}

bool NaClApplication::isFullscreen() {
    return fullscreen->IsFullscreen();
}

bool NaClApplication::setFullscreen(bool enabled) {
    /* Given fullscreen mode already set or switching to it is in progress, done */
    if(isFullscreen() == enabled || ((flags & Flag::FullscreenSwitchInProgress) && (flags & Flag::WillBeFullscreen) == enabled))
        return true;

    /* Switch to opposite fullscreen mode is in progress, can't revert it back */
    if((flags & Flag::FullscreenSwitchInProgress) && (flags & Flag::WillBeFullscreen) != enabled)
        return false;

    /* Set fullscreen */
    if(!fullscreen->SetFullscreen(enabled))
        return false;

    /* Set flags */
    flags |= Flag::FullscreenSwitchInProgress;
    enabled ? flags |= Flag::WillBeFullscreen : flags &= ~Flag::WillBeFullscreen;
    return true;
}

void NaClApplication::DidChangeView(const pp::View& view) {
    /* Fullscreen switch in progress */
    if(flags & Flag::FullscreenSwitchInProgress) {
        /* Done, remove the progress flag */
        if(isFullscreen() == bool(flags & Flag::WillBeFullscreen)) {
            flags &= ~Flag::FullscreenSwitchInProgress;
            flags |= Flag::Redraw;
        }

        /* Don't process anything during the switch */
        else return;
    }

    Vector2i size(view.GetRect().width(), view.GetRect().height());

    /* Canvas resized */
    if(viewportSize != size) {
        graphics->ResizeBuffers(size.x(), size.y());
        viewportSize = size;
        flags |= Flag::ViewportUpdated;
    }

    /* Update viewport, if changed */
    if(flags & Flag::ViewportUpdated) {
        flags &= ~Flag::ViewportUpdated;
        viewportEvent(size);
    }

    drawEvent();
}

bool NaClApplication::HandleInputEvent(const pp::InputEvent& event) {
    /* Don't handle anything during switch from/to fullscreen */
    if(flags & Flag::FullscreenSwitchInProgress) return false;

    Flags tmpFlags = flags;

    switch(event.GetType()) {
        case PP_INPUTEVENT_TYPE_KEYDOWN:
        case PP_INPUTEVENT_TYPE_KEYUP: {
            pp::KeyboardInputEvent keyEvent(event);
            KeyEvent e(static_cast<KeyEvent::Key>(keyEvent.GetKeyCode()), static_cast<InputEvent::Modifier>(keyEvent.GetModifiers()));
            event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN ? keyPressEvent(e) : keyReleaseEvent(e);
            if(!e.isAccepted()) return false;
            break;
        }

        case PP_INPUTEVENT_TYPE_MOUSEDOWN:
        case PP_INPUTEVENT_TYPE_MOUSEUP: {
            pp::MouseInputEvent mouseEvent(event);
            MouseEvent e(static_cast<MouseEvent::Button>(mouseEvent.GetButton()), {mouseEvent.GetPosition().x(), mouseEvent.GetPosition().y()}, static_cast<InputEvent::Modifier>(mouseEvent.GetModifiers()));
            event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN ? mousePressEvent(e) : mouseReleaseEvent(e);
            if(!e.isAccepted()) return false;
            break;
        }

        case PP_INPUTEVENT_TYPE_MOUSEMOVE: {
            pp::MouseInputEvent mouseEvent(event);
            MouseMoveEvent e({mouseEvent.GetPosition().x(), mouseEvent.GetPosition().y()},  {mouseEvent.GetMovement().x(), mouseEvent.GetMovement().y()}, static_cast<InputEvent::Modifier>(mouseEvent.GetModifiers()));
            mouseMoveEvent(e);
            if(!e.isAccepted()) return false;
            break;
        }

        default: return false;
    }

    /* Assume everything is properly sequential here */
    CORRADE_INTERNAL_ASSERT((tmpFlags & Flag::SwapInProgress) == (flags & Flag::SwapInProgress));

    /* Redraw, if it won't be handled after swap automatically */
    if((flags & Flag::Redraw) && !(flags & Flag::SwapInProgress)) {
        flags &= ~Flag::Redraw;
        drawEvent();
    }

    return true;
}

void NaClApplication::swapBuffers() {
    /* Swap already in progress, do nothing */
    if(flags & Flag::SwapInProgress) return;

    /* Swap buffers and call swapCallback() when done */
    flags |= Flag::SwapInProgress;
    graphics->SwapBuffers(pp::CompletionCallback(&swapCallback, this));
}

void NaClApplication::swapCallback(void* applicationInstance, std::int32_t) {
    NaClApplication* instance = static_cast<NaClApplication*>(applicationInstance);
    instance->flags &= ~Flag::SwapInProgress;

    /* Redraw, if requested */
    if(instance->flags & Flag::Redraw) {
        instance->flags &= ~Flag::Redraw;
        instance->drawEvent();
    }
}

void NaClApplication::setMouseLocked(bool enabled) {
    /* Already done, nothing to do */
    if(enabled == isMouseLocked()) return;

    if(enabled) LockMouse(pp::CompletionCallback(&mouseLockCallback, this));
    else UnlockMouse();
}

void NaClApplication::mouseLockCallback(void* applicationInstance, std::int32_t) {
    NaClApplication* instance = static_cast<NaClApplication*>(applicationInstance);
    instance->flags |= Flag::MouseLocked;
}

NaClApplication::Configuration::Configuration(): _size(640, 480), _sampleCount(0) {}
NaClApplication::Configuration::~Configuration() = default;

}}
<commit_msg>Platform: some const fascism.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "NaClApplication.h"

#include <ppapi/cpp/graphics_3d.h>
#include <ppapi/cpp/fullscreen.h>
#include <ppapi/cpp/completion_callback.h>

#include "Context.h"

namespace Magnum { namespace Platform {

NaClApplication::NaClApplication(const Arguments& arguments): Instance(arguments), Graphics3DClient(this), MouseLock(this), c(nullptr) {
    createContext(new Configuration);
}

NaClApplication::NaClApplication(const Arguments& arguments, Configuration* configuration): Instance(arguments), Graphics3DClient(this), MouseLock(this), c(nullptr) {
    if(configuration) createContext(configuration);
}

void NaClApplication::createContext(NaClApplication::Configuration* configuration) {
    CORRADE_ASSERT(!c, "NaClApplication::createContext(): context already created", );

    viewportSize = configuration->size();

    const std::int32_t attributes[] = {
        PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
        PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24,
        PP_GRAPHICS3DATTRIB_STENCIL_SIZE, 8,
        PP_GRAPHICS3DATTRIB_SAMPLES, configuration->sampleCount(),
        PP_GRAPHICS3DATTRIB_SAMPLE_BUFFERS, configuration->sampleCount() > 1? 1 : 0,
        PP_GRAPHICS3DATTRIB_WIDTH, configuration->size().x(),
        PP_GRAPHICS3DATTRIB_HEIGHT, configuration->size().y(),
        PP_GRAPHICS3DATTRIB_NONE
    };

    graphics = new pp::Graphics3D(this, attributes);
    if(graphics->is_null()) {
        Error() << "Platform::NaClApplication::NaClApplication(): cannot create graphics";
        std::exit(1);
    }
    if(!BindGraphics(*graphics)) {
        Error() << "Platform::NaClApplication::NaClApplication(): cannot bind graphics";
        std::exit(1);
    }

    fullscreen = new pp::Fullscreen(this);

    glSetCurrentContextPPAPI(graphics->pp_resource());

    c = new Context;

    /* Enable input handling for mouse and keyboard */
    RequestInputEvents(PP_INPUTEVENT_CLASS_MOUSE|PP_INPUTEVENT_CLASS_WHEEL);
    RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);

    /* Make sure viewportEvent() is called for first time */
    flags |= Flag::ViewportUpdated;

    delete configuration;
}

NaClApplication::~NaClApplication() {
    delete c;
    delete fullscreen;
    delete graphics;
}

bool NaClApplication::isFullscreen() {
    return fullscreen->IsFullscreen();
}

bool NaClApplication::setFullscreen(bool enabled) {
    /* Given fullscreen mode already set or switching to it is in progress, done */
    if(isFullscreen() == enabled || ((flags & Flag::FullscreenSwitchInProgress) && (flags & Flag::WillBeFullscreen) == enabled))
        return true;

    /* Switch to opposite fullscreen mode is in progress, can't revert it back */
    if((flags & Flag::FullscreenSwitchInProgress) && (flags & Flag::WillBeFullscreen) != enabled)
        return false;

    /* Set fullscreen */
    if(!fullscreen->SetFullscreen(enabled))
        return false;

    /* Set flags */
    flags |= Flag::FullscreenSwitchInProgress;
    enabled ? flags |= Flag::WillBeFullscreen : flags &= ~Flag::WillBeFullscreen;
    return true;
}

void NaClApplication::DidChangeView(const pp::View& view) {
    /* Fullscreen switch in progress */
    if(flags & Flag::FullscreenSwitchInProgress) {
        /* Done, remove the progress flag */
        if(isFullscreen() == bool(flags & Flag::WillBeFullscreen)) {
            flags &= ~Flag::FullscreenSwitchInProgress;
            flags |= Flag::Redraw;
        }

        /* Don't process anything during the switch */
        else return;
    }

    Vector2i size(view.GetRect().width(), view.GetRect().height());

    /* Canvas resized */
    if(viewportSize != size) {
        graphics->ResizeBuffers(size.x(), size.y());
        viewportSize = size;
        flags |= Flag::ViewportUpdated;
    }

    /* Update viewport, if changed */
    if(flags & Flag::ViewportUpdated) {
        flags &= ~Flag::ViewportUpdated;
        viewportEvent(size);
    }

    drawEvent();
}

bool NaClApplication::HandleInputEvent(const pp::InputEvent& event) {
    /* Don't handle anything during switch from/to fullscreen */
    if(flags & Flag::FullscreenSwitchInProgress) return false;

    Flags tmpFlags = flags;

    switch(event.GetType()) {
        case PP_INPUTEVENT_TYPE_KEYDOWN:
        case PP_INPUTEVENT_TYPE_KEYUP: {
            pp::KeyboardInputEvent keyEvent(event);
            KeyEvent e(static_cast<KeyEvent::Key>(keyEvent.GetKeyCode()), static_cast<InputEvent::Modifier>(keyEvent.GetModifiers()));
            event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN ? keyPressEvent(e) : keyReleaseEvent(e);
            if(!e.isAccepted()) return false;
            break;
        }

        case PP_INPUTEVENT_TYPE_MOUSEDOWN:
        case PP_INPUTEVENT_TYPE_MOUSEUP: {
            pp::MouseInputEvent mouseEvent(event);
            MouseEvent e(static_cast<MouseEvent::Button>(mouseEvent.GetButton()), {mouseEvent.GetPosition().x(), mouseEvent.GetPosition().y()}, static_cast<InputEvent::Modifier>(mouseEvent.GetModifiers()));
            event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN ? mousePressEvent(e) : mouseReleaseEvent(e);
            if(!e.isAccepted()) return false;
            break;
        }

        case PP_INPUTEVENT_TYPE_MOUSEMOVE: {
            pp::MouseInputEvent mouseEvent(event);
            MouseMoveEvent e({mouseEvent.GetPosition().x(), mouseEvent.GetPosition().y()},  {mouseEvent.GetMovement().x(), mouseEvent.GetMovement().y()}, static_cast<InputEvent::Modifier>(mouseEvent.GetModifiers()));
            mouseMoveEvent(e);
            if(!e.isAccepted()) return false;
            break;
        }

        default: return false;
    }

    /* Assume everything is properly sequential here */
    CORRADE_INTERNAL_ASSERT((tmpFlags & Flag::SwapInProgress) == (flags & Flag::SwapInProgress));

    /* Redraw, if it won't be handled after swap automatically */
    if((flags & Flag::Redraw) && !(flags & Flag::SwapInProgress)) {
        flags &= ~Flag::Redraw;
        drawEvent();
    }

    return true;
}

void NaClApplication::swapBuffers() {
    /* Swap already in progress, do nothing */
    if(flags & Flag::SwapInProgress) return;

    /* Swap buffers and call swapCallback() when done */
    flags |= Flag::SwapInProgress;
    graphics->SwapBuffers(pp::CompletionCallback(&swapCallback, this));
}

void NaClApplication::swapCallback(void* applicationInstance, std::int32_t) {
    NaClApplication* instance = static_cast<NaClApplication*>(applicationInstance);
    instance->flags &= ~Flag::SwapInProgress;

    /* Redraw, if requested */
    if(instance->flags & Flag::Redraw) {
        instance->flags &= ~Flag::Redraw;
        instance->drawEvent();
    }
}

void NaClApplication::setMouseLocked(bool enabled) {
    /* Already done, nothing to do */
    if(enabled == isMouseLocked()) return;

    if(enabled) LockMouse(pp::CompletionCallback(&mouseLockCallback, this));
    else UnlockMouse();
}

void NaClApplication::mouseLockCallback(void* applicationInstance, std::int32_t) {
    NaClApplication* instance = static_cast<NaClApplication*>(applicationInstance);
    instance->flags |= Flag::MouseLocked;
}

NaClApplication::Configuration::Configuration(): _size(640, 480), _sampleCount(0) {}
NaClApplication::Configuration::~Configuration() = default;

}}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <ctime>

#include "turbojpeg.h"

typedef unsigned char BYTE;

void save_buffer_to_file(const char *filename,BYTE* buffer,unsigned long size)
{
    FILE *outfile;
    if ((outfile = fopen(filename, "wb")) != NULL) {
        fwrite(buffer, size, 1, outfile);
        fclose(outfile);
    }
    else
    {
        fprintf(stderr, "can't open %s\n", filename);
        exit(1);
    }
}

/*
* Compress image buffer to a JPEG image in memory.
*
* @@input
*
* @param : [src] pointer to an image buffer that will be compressed.
* @param :
*
* @@output
* @param : [dst] pointer to an image buffer that will receive the compressed image.
           This variable should be passed in with NULL, and will be allocated by
           TurboJPEG(either by tjAlloc(),or by the Compress/Decompress) method
           So we need to use tjFree() to free memory allocated after we are done
           working on dst.
* @param : [dstLen] size of dst image buffer in bytes. This should be passed in with
           value 0.
*
* @@return
* @param void
*
* @@demo
*
        BYTE *dst = NULL;
        unsigned long dstLen = 0;
        tj_compress_jpeg_to_mem(
            ....,
            &dst,&dstLen
        )
*/
void tj_compress_jpeg_to_mem(
        /*IN*/BYTE *src, int width, int height, int pixelFormat, int subsamp, int quality, int flags,
        /*OUT*/BYTE **dst, unsigned long *dstLen
)
{
    // NOTICE : we must use tjAlloc() and tjFree() to allocate dst buffer.
    // for compress, we let **tjCompress2** allocate dst buffer.
    // for decompress, we allocate dst buffer by ourself.

    tjhandle handle = tjInitCompress();
    //tjCompress2(handle, src, width, 0/*pitch*/, height, TJPF::TJPF_GRAY,
    //    &pOutBuffer, &lOutSize, TJSAMP::TJSAMP_GRAY, quality,
    //    TJFLAG_FASTDCT); //TJFLAG_FASTDCT

    tjCompress2(
            handle, src, width, 0/*pitch*/, height, pixelFormat,
            dst, dstLen, subsamp, quality, flags
    );

    tjDestroy(handle);
}

void tj_compress_gray_jpeg_to_mem(
        /*IN*/BYTE *src, int width, int height, int quality,
        /*OUT*/BYTE **dst, unsigned long *dstLen
)
{
    int pixelFormat = TJPF::TJPF_GRAY;
    int subsamp = TJSAMP::TJSAMP_GRAY;
    int flags = TJFLAG_FASTDCT;

    tj_compress_jpeg_to_mem(
            src, width, height, pixelFormat, subsamp, quality, flags,
            dst, dstLen
    );
}

void tj_compress_gray_jpeg_to_file(
        /*IN*/BYTE *src, int width, int height, int quality,
        /*OUT*/const char* dst_filename
)
{
    int pixelFormat = TJPF::TJPF_GRAY;
    int subsamp = TJSAMP::TJSAMP_GRAY;
    int flags = TJFLAG_FASTDCT;

    // (1) init dst memory buffer
    BYTE *dst = NULL; // memory allocated by TurboJPEG tjAlloc()
    unsigned long dstLen = 0;

    // (2) compress
    tj_compress_jpeg_to_mem(
            src, width, height, pixelFormat, subsamp, quality, flags,
            &dst, &dstLen
    );

    // (3) write buffer to file
    save_buffer_to_file(dst_filename, dst, dstLen);

    // (4) free memory allocated by TurboJPEG
    tjFree(dst);
}

/*
* Compress image buffer to a JPEG image in memory.
*
* @@input
*
* @param : [src] pointer to an image buffer that will be compressed.
* @param :
*
* @@output
* @param : [dst] pointer to an image buffer that will receive the decompressed image.
           This variable should be passed in with NULL, and will be allocated in
           method by new[]. So we need to use delete[] to free memory allocated
           after we are done working on dst.
* @param : [dstLen] size of dst image buffer in bytes. This should be passed in with
            value 0.
*
* @@return
* @param void
*
* @@demo
*
        BYTE *dst = NULL;
        unsigned long dstLen = 0;
        tj_decompress_jpeg_from_mem(
        ....,
        &dst,&dstLen
        )
*/
void tj_decompress_jpeg_from_mem(
        /*IN*/BYTE *src, unsigned long srcLen,int tjPixelFormat,int flags,
        /*OUT*/BYTE **dst, unsigned long *dstLen, int *width, int *height, int *components, int *jpegSubsamp, int *jpegColorspace)
{
    tjhandle handle = tjInitDecompress();
    tjDecompressHeader3(handle, src, srcLen, width, height, jpegSubsamp, jpegColorspace);

    (*components) = tjPixelSize[(TJPF)tjPixelFormat]; // 1 for GRAY,3 for RGB
    (*dstLen) = (*width) * (*height) * (*components);

    BYTE *tmp_dst = new BYTE[*dstLen]; /* Allocate out buffer */

    tjDecompress2(
            handle, src, srcLen,
            tmp_dst, *width, 0/*pitch*/, *height, tjPixelFormat, flags
    );
    tjDestroy(handle);

    (*dst) = tmp_dst; // pass dst out
}

void tj_decompress_gray_jpeg_from_mem(
        /*IN*/BYTE *src, unsigned long srcLen,
        /*OUT*/BYTE **dst, unsigned long *dstLen, int *width, int *height, int *components
)
{
    int pixelFormat = TJPF::TJPF_GRAY;
    int flags = TJFLAG_ACCURATEDCT;
    int subsamp,colorspace; // no use for now  (3 TJSAMP::TJSAMP_GRAY, 2 TJCS::TJCS_GRAY)

    tj_decompress_jpeg_from_mem(
            src, srcLen, pixelFormat, flags,
            dst, dstLen, width, height, components, &subsamp, &colorspace
    );
}

void tj_decompress_gray_jpeg_from_file(
        /*IN*/const char* src_filename,
        /*OUT*/BYTE **dst, unsigned long *dstLen, int *width, int *height, int *components
)
{
    // (0) read src memory buffer from file
    std::ifstream ifs(src_filename, std::ios_base::binary | std::ios_base::in);
    ifs.seekg(0, std::ios::end);
    int len = ifs.tellg();
    printf("file len : %d\n", len);

    if(len < 0) {
        return ;
    }

    uint64_t srcLen = len;
    ifs.seekg(0, std::ios::beg);

    BYTE *src = new BYTE[srcLen];
    ifs.read((char*)src, srcLen);

    // (2) decompress
    int pixelFormat = TJPF::TJPF_GRAY;
    int flags = TJFLAG_ACCURATEDCT;
    int subsamp, colorspace; // no use for now  (3 TJSAMP::TJSAMP_GRAY, 2 TJCS::TJCS_GRAY)

    tj_decompress_jpeg_from_mem(
            src, srcLen, pixelFormat, flags,
            dst, dstLen, width, height, components, &subsamp, &colorspace
    );

    // (3) free src memory buffer
    delete[] src;

    // (4) pass out dst buffer
}

void test_compress(std::string& filename)
{
    int width = 2000;
    int height = 1000;
    int channel = 1;

    unsigned long srcLen = width * height * channel;
    unsigned char * src = new unsigned char[srcLen]; // new buffer
    memset(src, 0, srcLen);
    for (int i = 100; i < 300; i++) // row [height]
    {
        for (int j = 0; j < width; j++) // column [width]
        {
            *(src + width * i + j) = (char)255;
        }
    }

    //========================================================================
    // compress to file
    int quality = 90;
    tj_compress_gray_jpeg_to_file(src, width, height, quality, filename.c_str());
    //========================================================================

    delete[] src;
}

void test_decompress(std::string& srcFile, std::string& dstFile)
{
    // (0) create memory src buffer
    const char *src_filename = srcFile.c_str();

    // (2) decompress
    BYTE *dst = NULL; // allocated inside **decompress** function by new[].
    unsigned long dstLen = 0;
    int width, height, components;

    tj_decompress_gray_jpeg_from_file(
            src_filename,
            &dst, &dstLen, &width, &height, &components
    );

    std::cout << dstLen << std::endl;
    std::cout << width << std::endl;
    std::cout << height << std::endl;
    std::cout << components << std::endl;

    // (3) use dst buffer
    //========================================================================
    // compress to file
    int quality = 90;
    const char* dst_filename = dstFile.c_str();
    tj_compress_gray_jpeg_to_file(dst, width, height, quality, dst_filename);
    //========================================================================

    // (4) free dst buffer
    delete[] dst;
}

int IMAGE_COUNT = 10000;
void test_compress_time()
{
    int width = 2000;
    int height = 1000;
    int channel = 1;

    unsigned long srcLen = width * height * channel;
    unsigned char * src = new unsigned char[srcLen]; // new buffer
    memset(src, 0, srcLen);
    for (int i = 100; i < 300; i++) // row [height]
    {
        for (int j = 0; j < width; j++) // column [width]
        {
            *(src + width * i + j) = (char)255;
        }
    }

    int quality = 90;
    time_t start = time(NULL);

    for (int i = 0; i < IMAGE_COUNT; i++)
    {
        //========================================================================
        // (1) init dst memory buffer
        BYTE *dst = NULL; // memory allocated by TurboJPEG tjAlloc()
        unsigned long dstLen = 0;

        // (2) compress
        tj_compress_gray_jpeg_to_mem(
                src, width, height, quality,
                &dst, &dstLen
        );

        // (3) free memory allocated by TurboJPEG
        tjFree(dst);
        //========================================================================
    }

    time_t end = time(NULL);
    std::cout << "======================================" << std::endl;
    double ms = (double)(end - start) * 1000;
    std::cout << " use times = " << ms << "ms; avg = " << ms / IMAGE_COUNT << " ms; " << " #" << IMAGE_COUNT << std::endl;
    // avg = 4.9 ms  #10000 for jpeg
    // avg = 4.5 ms  #10000 for turbojpeg
    std::cout << "======================================" << std::endl;

    delete[] src;
}

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

    std::string file("/Users/frank/workspace/github/c_practice/jpeg/image/test.jpg");
    std::string file2("/Users/frank/workspace/github/c_practice/jpeg/image/new.jpeg");
//    test_compress(file);
    test_decompress(file,file2);
    return 0;
}<commit_msg>update<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <ctime>

#include "turbojpeg.h"

typedef unsigned char BYTE;

void save_buffer_to_file(const char *filename, BYTE *buffer, unsigned long size) {
    FILE *outfile;
    if ((outfile = fopen(filename, "wb")) != NULL) {
        fwrite(buffer, size, 1, outfile);
        fclose(outfile);
    } else {
        fprintf(stderr, "can't open %s\n", filename);
        exit(1);
    }
}

/*
* Compress image buffer to a JPEG image in memory.
*
* @@input
*
* @param : [src] pointer to an image buffer that will be compressed.
* @param :
*
* @@output
* @param : [dst] pointer to an image buffer that will receive the compressed image.
           This variable should be passed in with NULL, and will be allocated by
           TurboJPEG(either by tjAlloc(),or by the Compress/Decompress) method
           So we need to use tjFree() to free memory allocated after we are done
           working on dst.
* @param : [dstLen] size of dst image buffer in bytes. This should be passed in with
           value 0.
*
* @@return
* @param void
*
* @@demo
*
        BYTE *dst = NULL;
        unsigned long dstLen = 0;
        tj_compress_jpeg_to_mem(
            ....,
            &dst,&dstLen
        )
*/
void tj_compress_jpeg_to_mem(
        /*IN*/BYTE *src, int width, int height, int pixelFormat, int subsamp, int quality, int flags,
        /*OUT*/BYTE **dst, unsigned long *dstLen
) {
    // NOTICE : we must use tjAlloc() and tjFree() to allocate dst buffer.
    // for compress, we let **tjCompress2** allocate dst buffer.
    // for decompress, we allocate dst buffer by ourself.

    tjhandle handle = tjInitCompress();
    tjCompress2(
            handle, src, width, 0/*pitch*/, height, pixelFormat,
            dst, dstLen, subsamp, quality, flags
    );

    tjDestroy(handle);
}

//void tj_compress_gray_jpeg_to_mem(
//        /*IN*/BYTE *src, int width, int height, int quality,
//        /*OUT*/BYTE **dst, unsigned long *dstLen
//) {
//    int pixelFormat = TJPF::TJPF_GRAY;
//    int subsamp = TJSAMP::TJSAMP_GRAY;
//    int flags = TJFLAG_FASTDCT;
//
//    tj_compress_jpeg_to_mem(
//            src, width, height, pixelFormat, subsamp, quality, flags,
//            dst, dstLen
//    );
//}

void tj_compress_gray_jpeg_to_file(
        /*IN*/BYTE *src, int width, int height, int quality,
        /*OUT*/const char *dst_filename
) {
    int pixelFormat = TJPF::TJPF_GRAY;
    int subsamp = TJSAMP::TJSAMP_GRAY;
    int flags = TJFLAG_FASTDCT;

    // (1) init dst memory buffer
    BYTE *dst = NULL; // memory allocated by TurboJPEG tjAlloc()
    unsigned long dstLen = 0;

    // (2) compress
    tj_compress_jpeg_to_mem(
            src, width, height, pixelFormat, subsamp, quality, flags,
            &dst, &dstLen
    );

    // (3) write buffer to file
    save_buffer_to_file(dst_filename, dst, dstLen);

    // (4) free memory allocated by TurboJPEG
    tjFree(dst);
}

/*
* Decompress image buffer to a JPEG image in memory.
*
* @@input
*
* @param : [src] pointer to an image buffer that will be compressed.
* @param :
*
* @@output
* @param : [dst] pointer to an image buffer that will receive the decompressed image.
           This variable should be passed in with NULL, and will be allocated in
           method by new[]. So we need to use delete[] to free memory allocated
           after we are done working on dst.
* @param : [dstLen] size of dst image buffer in bytes. This should be passed in with
            value 0.
*
* @@return
* @param void
*
* @@demo
*
        BYTE *dst = NULL;
        unsigned long dstLen = 0;
        tj_decompress_jpeg_from_mem(
        ....,
        &dst,&dstLen
        )
*/
void tj_decompress_jpeg_from_mem(
        /*IN*/BYTE *src, unsigned long srcLen, int tjPixelFormat, int flags,
        /*OUT*/BYTE **dst, unsigned long *dstLen, int *width, int *height, int *components, int *jpegSubsamp,
              int *jpegColorspace) {
    tjhandle handle = tjInitDecompress();
    tjDecompressHeader3(handle, src, srcLen, width, height, jpegSubsamp, jpegColorspace);

    (*components) = tjPixelSize[(TJPF) tjPixelFormat]; // 1 for GRAY,3 for RGB
    (*dstLen) = (*width) * (*height) * (*components);

    BYTE *tmp_dst = new BYTE[*dstLen]; /* Allocate out buffer */

    tjDecompress2(
            handle, src, srcLen,
            tmp_dst, *width, 0/*pitch*/, *height, tjPixelFormat, flags
    );
    tjDestroy(handle);

    (*dst) = tmp_dst; // pass dst out
}

//void tj_decompress_gray_jpeg_from_mem(
//        /*IN*/BYTE *src, unsigned long srcLen,
//        /*OUT*/BYTE **dst, unsigned long *dstLen, int *width, int *height, int *components
//) {
////    int pixelFormat = TJPF::TJPF_GRAY;
//    int pixelFormat = TJPF::TJPF_RGB;
//    int flags = TJFLAG_ACCURATEDCT;
//    int subsamp, colorspace; // no use for now  (3 TJSAMP::TJSAMP_GRAY, 2 TJCS::TJCS_GRAY)
//
//    tj_decompress_jpeg_from_mem(
//            src, srcLen, pixelFormat, flags,
//            dst, dstLen, width, height, components, &subsamp, &colorspace
//    );
//}

void tj_decompress_gray_jpeg_from_file(
        /*IN*/const char *src_filename,
        /*OUT*/BYTE **dst, unsigned long *dstLen, int *width, int *height, int *components
) {
    // (0) read src memory buffer from file
    std::ifstream ifs(src_filename, std::ios_base::binary | std::ios_base::in);
    ifs.seekg(0, std::ios::end);
    int len = ifs.tellg();
    printf("file len : %d\n", len);

    if (len < 0) {
        return;
    }

    uint64_t srcLen = len;
    ifs.seekg(0, std::ios::beg);

    // 读取文件数据
    BYTE *src = new BYTE[srcLen];
    ifs.read((char *) src, srcLen);

    // (2) decompress
    int pixelFormat = TJPF::TJPF_GRAY;
    int flags = TJFLAG_ACCURATEDCT;
    int subsamp, colorspace; // no use for now  (3 TJSAMP::TJSAMP_GRAY, 2 TJCS::TJCS_GRAY)

    tj_decompress_jpeg_from_mem(
            src, srcLen, pixelFormat, flags,
            dst, dstLen, width, height, components, &subsamp, &colorspace
    );

    // (3) free src memory buffer
    delete[] src;

    // (4) pass out dst buffer
}

//void test_compress(std::string &filename) {
//    int width = 2000;
//    int height = 1000;
//    int channel = 1;
//
//    unsigned long srcLen = width * height * channel;
//    unsigned char *src = new unsigned char[srcLen]; // new buffer
//    memset(src, 0, srcLen);
//    for (int i = 100; i < 300; i++) // row [height]
//    {
//        for (int j = 0; j < width; j++) // column [width]
//        {
//            *(src + width * i + j) = (char) 255;
//        }
//    }
//
//    //========================================================================
//    // compress to file
//    int quality = 90;
//    tj_compress_gray_jpeg_to_file(src, width, height, quality, filename.c_str());
//    //========================================================================
//
//    delete[] src;
//}

void test_decompress(std::string &srcFile, std::string &dstFile) {
    // (0) create memory src buffer
    const char *src_filename = srcFile.c_str();

    // (2) decompress
    BYTE *dst = NULL; // allocated inside **decompress** function by new[].
    unsigned long dstLen = 0;
    int width, height, components;

    tj_decompress_gray_jpeg_from_file(
            src_filename,
            &dst, &dstLen, &width, &height, &components
    );

    std::cout << dstLen << std::endl;
    std::cout << width << std::endl;
    std::cout << height << std::endl;
    std::cout << components << std::endl;

    // (3) use dst buffer
    //========================================================================
    // compress to file
    int quality = 100;
    const char *dst_filename = dstFile.c_str();
    tj_compress_gray_jpeg_to_file(dst, width, height, quality, dst_filename);
    //========================================================================

    // (4) free dst buffer
    delete[] dst;
}

//int IMAGE_COUNT = 10000;
//
//void test_compress_time() {
//    int width = 2000;
//    int height = 1000;
//    int channel = 1;
//
//    unsigned long srcLen = width * height * channel;
//    unsigned char *src = new unsigned char[srcLen]; // new buffer
//    memset(src, 0, srcLen);
//    for (int i = 100; i < 300; i++) // row [height]
//    {
//        for (int j = 0; j < width; j++) // column [width]
//        {
//            *(src + width * i + j) = (char) 255;
//        }
//    }
//
//    int quality = 90;
//    time_t start = time(NULL);
//
//    for (int i = 0; i < IMAGE_COUNT; i++) {
//        //========================================================================
//        // (1) init dst memory buffer
//        BYTE *dst = NULL; // memory allocated by TurboJPEG tjAlloc()
//        unsigned long dstLen = 0;
//
//        // (2) compress
//        tj_compress_gray_jpeg_to_mem(
//                src, width, height, quality,
//                &dst, &dstLen
//        );
//
//        // (3) free memory allocated by TurboJPEG
//        tjFree(dst);
//        //========================================================================
//    }
//
//    time_t end = time(NULL);
//    std::cout << "======================================" << std::endl;
//    double ms = (double) (end - start) * 1000;
//    std::cout << " use times = " << ms << "ms; avg = " << ms / IMAGE_COUNT << " ms; " << " #" << IMAGE_COUNT
//              << std::endl;
//    // avg = 4.9 ms  #10000 for jpeg
//    // avg = 4.5 ms  #10000 for turbojpeg
//    std::cout << "======================================" << std::endl;
//
//    delete[] src;
//}

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

    std::string file("/Users/frank/workspace/github/c_practice/jpeg/image/test.jpg");
    std::string file2("/Users/frank/workspace/github/c_practice/jpeg/image/new.jpeg");
//    test_compress(file);
    test_decompress(file, file2);
    return 0;
}<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// bind_node_visitor.cpp
//
// Identification: src/binder/binder_node_visitor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <include/parser/statements.h>
#include <include/expression/tuple_value_expression.h>
#include "parser/select_statement.h"
#include "binder/bind_node_visitor.h"
#include "type/types.h"

namespace peloton {
namespace binder {

BindNodeVisitor::BindNodeVisitor() { context_ = nullptr; }

void BindNodeVisitor::BindNameToNode(parser::SQLStatement *tree) {
  tree->Accept(this);
}

void BindNodeVisitor::Visit(const parser::SelectStatement *node) {
  // Save the upper level context
  auto pre_context = context_;
  context_ = std::make_shared<BinderContext>();
  context_->upper_context = pre_context;

  if (node->from_table != nullptr) node->from_table->Accept(this);
  if (node->where_clause != nullptr) node->where_clause->Accept(this);
  if (node->order != nullptr) node->order->Accept(this);
  if (node->limit != nullptr) node->limit->Accept(this);
  if (node->group_by != nullptr) node->group_by->Accept(this);
  for (auto select_element : *(node->select_list)) {
    select_element->Accept(this);
  }

  // Restore the upper level context
  context_ = context_->upper_context;
}

// Some sub query nodes inside SelectStatement
void BindNodeVisitor::Visit(const parser::JoinDefinition *node) {
  // The columns in join condition can only bind to the join tables
  node->left->Accept(this);
  node->right->Accept(this);
  node->condition->Accept(this);
}

void BindNodeVisitor::Visit(const parser::TableRef *node) {
  // Nested select. Not supported in the current executors
  if (node->select != nullptr) node->select->Accept(this);
  // Join
  else if (node->join != nullptr)
    node->join->Accept(this);
  // Multiple tables
  else if (node->list != nullptr) {
    for (parser::TableRef *table : *(node->list)) table->Accept(this);
  }
  // Single table
  else {
    context_->AddTable(node);
  }
}

void BindNodeVisitor::Visit(const parser::GroupByDescription *node) {
  for (auto col : *(node->columns)) {
    col->Accept(this);
  }
  if (node->having != nullptr) node->having->Accept(this);
}
void BindNodeVisitor::Visit(const parser::OrderDescription *node) {
  for (auto expr : *(node->exprs))
    if (expr != nullptr) expr->Accept(this);
}

void BindNodeVisitor::Visit(const parser::UpdateStatement *node) {
  context_ = std::make_shared<BinderContext>();

  node->table->Accept(this);
  if (node->where != nullptr) node->where->Accept(this);
  for (auto update : *node->updates) {
    update->value->Accept(this);
  }

  // TODO: Update columns are not bound because they are char*
  // not TupleValueExpression in update_statement.h

  update_col_name_ = nullptr;
  context_ = nullptr;
}

void BindNodeVisitor::Visit(const parser::DeleteStatement *node) {
  context_ = std::make_shared<BinderContext>();

  context_->AddTable(node->GetDatabaseName(), node->GetTableName());

  if (node->expr != nullptr) node->expr->Accept(this);

  context_ = nullptr;
}

void BindNodeVisitor::Visit(const parser::LimitDescription *) {}
void BindNodeVisitor::Visit(const parser::CopyStatement *) {}
void BindNodeVisitor::Visit(const parser::CreateStatement *) {}
void BindNodeVisitor::Visit(const parser::InsertStatement *) {}
void BindNodeVisitor::Visit(const parser::DropStatement *) {}
void BindNodeVisitor::Visit(const parser::PrepareStatement *) {}
void BindNodeVisitor::Visit(const parser::ExecuteStatement *) {}
void BindNodeVisitor::Visit(const parser::TransactionStatement *) {}
void BindNodeVisitor::Visit(expression::ConstantValueExpression *) {}

void BindNodeVisitor::Visit(expression::TupleValueExpression *expr) {
  if (!expr->GetIsBound()) {
    std::tuple<oid_t, oid_t, oid_t> col_pos_tuple;
    std::tuple<oid_t, oid_t> table_id_tuple;

    std::string table_name = expr->GetTableName();
    std::string col_name = expr->GetColumnName();

    // Convert all the names to lower cases
    std::transform(table_name.begin(), table_name.end(), table_name.begin(),
                   ::tolower);
    std::transform(col_name.begin(), col_name.end(), col_name.begin(),
                   ::tolower);

    type::Type::TypeId value_type;
    // Table name not specified in the expression
    if (table_name.empty()) {
      if (!BinderContext::GetColumnPosTuple(context_, col_name, col_pos_tuple,
                                            table_name, value_type))
        throw Exception("Cannot find column " + col_name);
      expr->SetTableName(table_name);
    }
    // Table name is present
    else {
      // Find the corresponding table in the context
      if (!BinderContext::GetTableIdTuple(context_, table_name,
                                          &table_id_tuple))
        throw Exception("Invalid table reference " + expr->GetTableName());
      // Find the column offset in that table
      if (!BinderContext::GetColumnPosTuple(col_name, table_id_tuple,
                                            col_pos_tuple, value_type))
        throw Exception("Cannot find column " + col_name);
    }
    expr->SetValueType(value_type);
    expr->SetBoundOid(col_pos_tuple);
  }
}

}  // binder
}  // peloton
<commit_msg>Minor fix<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// bind_node_visitor.cpp
//
// Identification: src/binder/binder_node_visitor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <include/parser/statements.h>
#include <include/expression/tuple_value_expression.h>
#include "parser/select_statement.h"
#include "binder/bind_node_visitor.h"
#include "type/types.h"

namespace peloton {
namespace binder {

BindNodeVisitor::BindNodeVisitor() { context_ = nullptr; }

void BindNodeVisitor::BindNameToNode(parser::SQLStatement *tree) {
  tree->Accept(this);
}

void BindNodeVisitor::Visit(const parser::SelectStatement *node) {
  // Save the upper level context
  auto pre_context = context_;
  context_ = std::make_shared<BinderContext>();
  context_->upper_context = pre_context;

  if (node->from_table != nullptr) node->from_table->Accept(this);
  if (node->where_clause != nullptr) node->where_clause->Accept(this);
  if (node->order != nullptr) node->order->Accept(this);
  if (node->limit != nullptr) node->limit->Accept(this);
  if (node->group_by != nullptr) node->group_by->Accept(this);
  for (auto select_element : *(node->select_list)) {
    select_element->Accept(this);
  }

  // Restore the upper level context
  context_ = context_->upper_context;
}

// Some sub query nodes inside SelectStatement
void BindNodeVisitor::Visit(const parser::JoinDefinition *node) {
  // The columns in join condition can only bind to the join tables
  node->left->Accept(this);
  node->right->Accept(this);
  node->condition->Accept(this);
}

void BindNodeVisitor::Visit(const parser::TableRef *node) {
  // Nested select. Not supported in the current executors
  if (node->select != nullptr) node->select->Accept(this);
  // Join
  else if (node->join != nullptr)
    node->join->Accept(this);
  // Multiple tables
  else if (node->list != nullptr) {
    for (parser::TableRef *table : *(node->list)) table->Accept(this);
  }
  // Single table
  else {
    context_->AddTable(node);
  }
}

void BindNodeVisitor::Visit(const parser::GroupByDescription *node) {
  for (auto col : *(node->columns)) {
    col->Accept(this);
  }
  if (node->having != nullptr) node->having->Accept(this);
}
void BindNodeVisitor::Visit(const parser::OrderDescription *node) {
  for (auto expr : *(node->exprs))
    if (expr != nullptr) expr->Accept(this);
}

void BindNodeVisitor::Visit(const parser::UpdateStatement *node) {
  context_ = std::make_shared<BinderContext>();

  node->table->Accept(this);
  if (node->where != nullptr) node->where->Accept(this);
  for (auto update : *node->updates) {
    update->value->Accept(this);
  }

  // TODO: Update columns are not bound because they are char*
  // not TupleValueExpression in update_statement.h

  context_ = nullptr;
}

void BindNodeVisitor::Visit(const parser::DeleteStatement *node) {
  context_ = std::make_shared<BinderContext>();

  context_->AddTable(node->GetDatabaseName(), node->GetTableName());

  if (node->expr != nullptr) node->expr->Accept(this);

  context_ = nullptr;
}

void BindNodeVisitor::Visit(const parser::LimitDescription *) {}
void BindNodeVisitor::Visit(const parser::CopyStatement *) {}
void BindNodeVisitor::Visit(const parser::CreateStatement *) {}
void BindNodeVisitor::Visit(const parser::InsertStatement *) {}
void BindNodeVisitor::Visit(const parser::DropStatement *) {}
void BindNodeVisitor::Visit(const parser::PrepareStatement *) {}
void BindNodeVisitor::Visit(const parser::ExecuteStatement *) {}
void BindNodeVisitor::Visit(const parser::TransactionStatement *) {}
void BindNodeVisitor::Visit(expression::ConstantValueExpression *) {}

void BindNodeVisitor::Visit(expression::TupleValueExpression *expr) {
  if (!expr->GetIsBound()) {
    std::tuple<oid_t, oid_t, oid_t> col_pos_tuple;
    std::tuple<oid_t, oid_t> table_id_tuple;

    std::string table_name = expr->GetTableName();
    std::string col_name = expr->GetColumnName();

    // Convert all the names to lower cases
    std::transform(table_name.begin(), table_name.end(), table_name.begin(),
                   ::tolower);
    std::transform(col_name.begin(), col_name.end(), col_name.begin(),
                   ::tolower);

    type::Type::TypeId value_type;
    // Table name not specified in the expression
    if (table_name.empty()) {
      if (!BinderContext::GetColumnPosTuple(context_, col_name, col_pos_tuple,
                                            table_name, value_type))
        throw Exception("Cannot find column " + col_name);
      expr->SetTableName(table_name);
    }
    // Table name is present
    else {
      // Find the corresponding table in the context
      if (!BinderContext::GetTableIdTuple(context_, table_name,
                                          &table_id_tuple))
        throw Exception("Invalid table reference " + expr->GetTableName());
      // Find the column offset in that table
      if (!BinderContext::GetColumnPosTuple(col_name, table_id_tuple,
                                            col_pos_tuple, value_type))
        throw Exception("Cannot find column " + col_name);
    }
    expr->SetValueType(value_type);
    expr->SetBoundOid(col_pos_tuple);
  }
}

}  // binder
}  // peloton
<|endoftext|>


<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2010/05/25
//
// Copyright 2010-2012 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// \brief Kfs checksum (adler32) unit test.
//
//----------------------------------------------------------------------------

#include "kfsio/checksum.cc"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
        printf("Usage: %s [flags]\n"
               "       flags can be any combination of 'c', 'n', 'd'.\n"
               "       c: test adler32 combine.\n"
               "       n: pad with 0.\n"
               "       d: debug.\n"
               "       The test reads input from STDIN ended by Ctrl+D.\n",
               argv[0]);
        return 0;
    }

    static char   buf[KFS::CHECKSUM_BLOCKSIZE * 4];
    char*         p = buf;
    ssize_t       n = 0;
    unsigned long o = 0;
    const bool    padd  = argc <= 1 || strchr(argv[1], 'n') == 0;
    const bool    tcomb = argc > 1 && strchr(argv[1], 'c');
    const bool    debug = argc > 1 && strchr(argv[1], 'd');
    char* const   e = p + (tcomb ? sizeof(buf) : KFS::CHECKSUM_BLOCKSIZE);

    do {
        while (p < e && (n = read(0, p, e - p)) > 0) {
            p += n;
        }
        if (p <= buf) {
            break;
        }
        const size_t len = (padd ? e : p) - buf;
        if (padd && p < e) {
            memset(p, 0, e - p);
        }
        const uint32_t cksum = KFS::ComputeBlockChecksum(buf, len);
        if (tcomb) {
            uint32_t cck = 0;
            KFS::ComputeChecksums(buf, len, &cck);
            if (cck != cksum) {
                printf("mismatch %lu %lu %u %u\n", o, (unsigned long)len,
                    (unsigned int)cksum, (unsigned int)cck);
                abort();
            }
        }
        if (! tcomb || debug) {
            printf("%lu %lu %u\n", o, (unsigned long)len, (unsigned int)cksum);
        }
        o += len;
        p = buf;
    } while (n > 0);
    return 0;
}
<commit_msg>Check sum tool: fix help message.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2010/05/25
//
// Copyright 2010-2012 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// \brief Kfs checksum (adler32) unit test.
//
//----------------------------------------------------------------------------

#include "kfsio/checksum.cc"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
        printf("Usage: %s [flags]\n"
               "       flags can be any combination of 'c', 'n', 'd'.\n"
               "       c: test adler32 combine.\n"
               "       n: don't pad with 0.\n"
               "       d: debug.\n"
               "       The test reads input from STDIN ended by Ctrl+D.\n",
               argv[0]);
        return 0;
    }

    static char   buf[KFS::CHECKSUM_BLOCKSIZE * 4];
    char*         p = buf;
    ssize_t       n = 0;
    unsigned long o = 0;
    const bool    padd  = argc <= 1 || strchr(argv[1], 'n') == 0;
    const bool    tcomb = argc > 1 && strchr(argv[1], 'c');
    const bool    debug = argc > 1 && strchr(argv[1], 'd');
    char* const   e = p + (tcomb ? sizeof(buf) : KFS::CHECKSUM_BLOCKSIZE);

    do {
        while (p < e && (n = read(0, p, e - p)) > 0) {
            p += n;
        }
        if (p <= buf) {
            break;
        }
        const size_t len = (padd ? e : p) - buf;
        if (padd && p < e) {
            memset(p, 0, e - p);
        }
        const uint32_t cksum = KFS::ComputeBlockChecksum(buf, len);
        if (tcomb) {
            uint32_t cck = 0;
            KFS::ComputeChecksums(buf, len, &cck);
            if (cck != cksum) {
                printf("mismatch %lu %lu %u %u\n", o, (unsigned long)len,
                    (unsigned int)cksum, (unsigned int)cck);
                abort();
            }
        }
        if (! tcomb || debug) {
            printf("%lu %lu %u\n", o, (unsigned long)len, (unsigned int)cksum);
        }
        o += len;
        p = buf;
    } while (n > 0);
    return 0;
}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2016 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/ports/portinspector.h>
#include <inviwo/core/io/serialization/serialization.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/metadata/processormetadata.h>

namespace inviwo {
PortInspector::PortInspector(std::string portClassIdentifier,
                             std::string inspectorWorkspaceFileName)
    : inspectorNetworkFileName_(inspectorWorkspaceFileName)
    , portClassIdentifier_(portClassIdentifier) {

    // Deserialize the network
    auto app = InviwoApplication::getPtr();
    Deserializer deserializer(inspectorNetworkFileName_);
    deserializer.registerFactory(app->getProcessorFactory());
    deserializer.registerFactory(app->getMetaDataFactory());
    deserializer.registerFactory(app->getPropertyFactory());
    deserializer.registerFactory(app->getInportFactory());
    deserializer.registerFactory(app->getOutportFactory());
    inspectorNetwork_ = util::make_unique<ProcessorNetwork>(app);
    inspectorNetwork_->deserialize(deserializer);
    processors_ = inspectorNetwork_->getProcessors();

    for (auto processor : processors_) {
        // Set Identifiers
        std::string newIdentifier = dotSeperatedToPascalCase(getPortClassName()) +
            "PortInspector" + processor->getIdentifier();
        processor->setIdentifier(newIdentifier);

        // Find the and save inports.
        for (auto& inport : processor->getInports()) {
            if (!inport->isConnected()) inPorts_.push_back(inport);
        }

        auto meta =
            processor->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER);
        meta->setVisible(false);
        meta->setSelected(false);

        // Find and save the canvasProcessor
        if (auto canvasProcessor = dynamic_cast<CanvasProcessor*>(processor)) {
            canvasProcessor_ = canvasProcessor;
        }
    }

    // Store the connections and and disconnect them.
    auto connections = inspectorNetwork_->getConnections();
    for (auto& connection : connections) {
        connections_.emplace_back(connection.getOutport(), connection.getInport());
        inspectorNetwork_->removeConnection(connection.getOutport(), connection.getInport());
    }

    // store the processor links.
    propertyLinks_ = inspectorNetwork_->getLinks();
}

void PortInspector::setActive(bool val) { active_ = val; }
bool PortInspector::isActive() { return active_; }

std::string PortInspector::getInspectorNetworkFileName() { return inspectorNetworkFileName_; }
std::string PortInspector::getPortClassName() { return portClassIdentifier_; }
std::vector<Inport*>& PortInspector::getInports() { return inPorts_; }
CanvasProcessor* PortInspector::getCanvasProcessor() { return canvasProcessor_; }
std::vector<PortConnection>& PortInspector::getConnections() { return connections_; }
std::vector<PropertyLink>& PortInspector::getPropertyLinks() { return propertyLinks_; }
std::vector<Processor*>& PortInspector::getProcessors() { return processors_; }

}  // namespace
<commit_msg>Core: Portinspector, include fix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2016 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/ports/portinspector.h>
#include <inviwo/core/io/serialization/serialization.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/metadata/processormetadata.h>
#include <inviwo/core/processors/processorfactory.h>
#include <inviwo/core/metadata/metadatafactory.h>
#include <inviwo/core/properties/propertyfactory.h>
#include <inviwo/core/ports/portfactory.h>

namespace inviwo {
PortInspector::PortInspector(std::string portClassIdentifier,
                             std::string inspectorWorkspaceFileName)
    : inspectorNetworkFileName_(inspectorWorkspaceFileName)
    , portClassIdentifier_(portClassIdentifier) {

    // Deserialize the network
    auto app = InviwoApplication::getPtr();
    Deserializer deserializer(inspectorNetworkFileName_);
    deserializer.registerFactory(app->getProcessorFactory());
    deserializer.registerFactory(app->getMetaDataFactory());
    deserializer.registerFactory(app->getPropertyFactory());
    deserializer.registerFactory(app->getInportFactory());
    deserializer.registerFactory(app->getOutportFactory());
    inspectorNetwork_ = util::make_unique<ProcessorNetwork>(app);
    inspectorNetwork_->deserialize(deserializer);
    processors_ = inspectorNetwork_->getProcessors();

    for (auto processor : processors_) {
        // Set Identifiers
        std::string newIdentifier = dotSeperatedToPascalCase(getPortClassName()) +
            "PortInspector" + processor->getIdentifier();
        processor->setIdentifier(newIdentifier);

        // Find the and save inports.
        for (auto& inport : processor->getInports()) {
            if (!inport->isConnected()) inPorts_.push_back(inport);
        }

        auto meta =
            processor->getMetaData<ProcessorMetaData>(ProcessorMetaData::CLASS_IDENTIFIER);
        meta->setVisible(false);
        meta->setSelected(false);

        // Find and save the canvasProcessor
        if (auto canvasProcessor = dynamic_cast<CanvasProcessor*>(processor)) {
            canvasProcessor_ = canvasProcessor;
        }
    }

    // Store the connections and and disconnect them.
    auto connections = inspectorNetwork_->getConnections();
    for (auto& connection : connections) {
        connections_.emplace_back(connection.getOutport(), connection.getInport());
        inspectorNetwork_->removeConnection(connection.getOutport(), connection.getInport());
    }

    // store the processor links.
    propertyLinks_ = inspectorNetwork_->getLinks();
}

void PortInspector::setActive(bool val) { active_ = val; }
bool PortInspector::isActive() { return active_; }

std::string PortInspector::getInspectorNetworkFileName() { return inspectorNetworkFileName_; }
std::string PortInspector::getPortClassName() { return portClassIdentifier_; }
std::vector<Inport*>& PortInspector::getInports() { return inPorts_; }
CanvasProcessor* PortInspector::getCanvasProcessor() { return canvasProcessor_; }
std::vector<PortConnection>& PortInspector::getConnections() { return connections_; }
std::vector<PropertyLink>& PortInspector::getPropertyLinks() { return propertyLinks_; }
std::vector<Processor*>& PortInspector::getProcessors() { return processors_; }

}  // namespace
<|endoftext|>